debuggerplugin.cpp 130 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30 31
#include "debuggerplugin.h"

Friedemann Kleint's avatar
Friedemann Kleint committed
32
#include "debuggerstartparameters.h"
33
#include "debuggeractions.h"
34
#include "debuggerinternalconstants.h"
35
#include "debuggercore.h"
36
#include "debuggerkitconfigwidget.h"
37 38
#include "debuggerdialogs.h"
#include "debuggerengine.h"
39
#include "debuggeritemmanager.h"
40
#include "debuggermainwindow.h"
con's avatar
con committed
41
#include "debuggerrunner.h"
42
#include "debuggerrunconfigurationaspect.h"
43
#include "debuggerruncontrolfactory.h"
44
#include "debuggerstringutils.h"
45
#include "debuggeroptionspage.h"
Tobias Hunger's avatar
Tobias Hunger committed
46
#include "debuggerkitinformation.h"
47
#include "memoryagent.h"
48
#include "breakhandler.h"
49
#include "breakwindow.h"
50
#include "disassemblerlines.h"
51
#include "logwindow.h"
52
#include "moduleswindow.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
53
#include "moduleshandler.h"
54 55
#include "registerwindow.h"
#include "snapshotwindow.h"
hjk's avatar
hjk committed
56
#include "stackhandler.h"
57 58 59
#include "stackwindow.h"
#include "sourcefileswindow.h"
#include "threadswindow.h"
hjk's avatar
hjk committed
60
#include "watchhandler.h"
61
#include "watchwindow.h"
hjk's avatar
hjk committed
62
#include "watchutils.h"
63
#include "debuggertooltipmanager.h"
64
#include "localsandexpressionswindow.h"
65
#include "loadcoredialog.h"
66
#include "sourceutils.h"
67
#include <debugger/shared/hostutils.h>
68

69 70
#include "snapshothandler.h"
#include "threadshandler.h"
71
#include "commonoptionspage.h"
72
#include "gdb/startgdbserverdialog.h"
con's avatar
con committed
73

74
#include <coreplugin/actionmanager/actionmanager.h>
75
#include <coreplugin/actionmanager/actioncontainer.h>
76
#include <coreplugin/imode.h>
con's avatar
con committed
77 78
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
79
#include <coreplugin/messagemanager.h>
con's avatar
con committed
80
#include <coreplugin/modemanager.h>
hjk's avatar
hjk committed
81

con's avatar
con committed
82
#include <cppeditor/cppeditorconstants.h>
83
#include <cpptools/cppmodelmanagerinterface.h>
hjk's avatar
hjk committed
84

85
#include <extensionsystem/invoker.h>
86

87
#include <projectexplorer/localapplicationrunconfiguration.h>
88
#include <projectexplorer/buildmanager.h>
89
#include <projectexplorer/taskhub.h>
90
#include <projectexplorer/toolchain.h>
91
#include <projectexplorer/devicesupport/deviceprocesslist.h>
92
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
93 94 95
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorersettings.h>
#include <projectexplorer/project.h>
con's avatar
con committed
96
#include <projectexplorer/session.h>
97
#include <projectexplorer/target.h>
98

hjk's avatar
hjk committed
99
#include <texteditor/basetexteditor.h>
100
#include <texteditor/fontsettings.h>
101
#include <texteditor/texteditorsettings.h>
hjk's avatar
hjk committed
102

103
#include <utils/hostosinfo.h>
hjk's avatar
hjk committed
104
#include <utils/qtcassert.h>
105
#include <utils/styledbar.h>
106
#include <utils/proxyaction.h>
107
#include <utils/statuslabel.h>
108 109 110
#ifdef Q_OS_WIN
#  include <utils/winutils.h>
#endif
con's avatar
con committed
111

112
#include <QComboBox>
113 114
#include <QDockWidget>
#include <QFileDialog>
hjk's avatar
hjk committed
115
#include <QInputDialog>
116 117 118
#include <QMessageBox>
#include <QTextBlock>
#include <QToolButton>
hjk's avatar
hjk committed
119
#include <QtPlugin>
120
#include <QTreeWidget>
con's avatar
con committed
121

hjk's avatar
hjk committed
122
#ifdef WITH_TESTS
123 124 125
#include <QTest>
#include <QSignalSpy>
#include <QTestEventLoop>
126 127 128 129

//#define WITH_BENCHMARK
#ifdef WITH_BENCHMARK
#include <valgrind/callgrind.h>
hjk's avatar
hjk committed
130 131
#endif

132 133
#endif // WITH_TESTS

134 135
#include <climits>

136 137 138 139 140
#define DEBUG_STATE 1
#ifdef DEBUG_STATE
//#   define STATE_DEBUG(s)
//    do { QString msg; QTextStream ts(&msg); ts << s;
//      showMessage(msg, LogDebug); } while (0)
141
#   define STATE_DEBUG(s) do { qDebug() << s; } while (0)
142 143 144 145
#else
#   define STATE_DEBUG(s)
#endif

146 147 148 149 150 151 152 153
/*!
    \namespace Debugger
    Debugger plugin namespace
*/

/*!
    \namespace Debugger::Internal
    Internal namespace of the Debugger plugin
154
    \internal
155 156 157 158 159
*/

/*!
    \class Debugger::DebuggerEngine

160
    \brief The DebuggerEngine class is the base class of a debugger engine.
161

Leena Miettinen's avatar
Leena Miettinen committed
162
    \note The Debugger process itself and any helper processes like
163 164
    gdbserver are referred to as 'Engine', whereas the debugged process
    is referred to as 'Inferior'.
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

    Transitions marked by '---' are done in the individual engines.
    Transitions marked by '+-+' are done in the base DebuggerEngine.
    Transitions marked by '*' are done asynchronously.

    The GdbEngine->setupEngine() function is described in more detail below.

    The engines are responsible for local roll-back to the last
    acknowledged state before calling notify*Failed. I.e. before calling
    notifyEngineSetupFailed() any process started during setupEngine()
    so far must be terminated.
    \code

                        DebuggerNotReady
                         progressmanager/progressmanager.cpp      +
                      EngineSetupRequested
                               +
                  (calls *Engine->setupEngine())
                            |      |
                            |      |
                       {notify-  {notify-
                        Engine-   Engine-
                        SetupOk}  SetupFailed}
                            +      +
                            +      `+-+-+> EngineSetupFailed
                            +                   +
                            +    [calls RunControl->startFailed]
                            +                   +
                            +             DebuggerFinished
                            v
                      EngineSetupOk
                            +
             [calls RunControl->StartSuccessful]
                            +
                  InferiorSetupRequested
                            +
             (calls *Engine->setupInferior())
                         |       |
                         |       |
                    {notify-   {notify-
                     Inferior- Inferior-
                     SetupOk}  SetupFailed}
                         +       +
                         +       ` +-+-> InferiorSetupFailed +-+-+-+-+-+->.
                         +                                                +
                  InferiorSetupOk                                         +
                         +                                                +
                  EngineRunRequested                                      +
                         +                                                +
                 (calls *Engine->runEngine())                             +
               /       |            |        \                            +
             /         |            |          \                          +
            | (core)   | (attach)   |           |                         +
            |          |            |           |                         +
      {notify-    {notifyER&- {notifyER&-  {notify-                       +
      Inferior-     Inferior-   Inferior-  EngineRun-                     +
     Unrunnable}     StopOk}     RunOk}     Failed}                       +
           +           +            +           +                         +
   InferiorUnrunnable  +     InferiorRunOk      +                         +
                       +                        +                         +
                InferiorStopOk            EngineRunFailed                 +
                                                +                         v
                                                 `-+-+-+-+-+-+-+-+-+-+-+>-+
                                                                          +
                                                                          +
                       #Interrupt@InferiorRunOk#                          +
                                  +                                       +
                          InferiorStopRequested                           +
  #SpontaneousStop                +                                       +
   @InferiorRunOk#         (calls *Engine->                               +
          +               interruptInferior())                            +
      {notify-               |          |                                 +
     Spontaneous-       {notify-    {notify-                              +
      Inferior-          Inferior-   Inferior-                            +
       StopOk}           StopOk}    StopFailed}                           +
           +              +             +                                 +
            +            +              +                                 +
            InferiorStopOk              +                                 +
                  +                     +                                 +
                  +                    +                                  +
                  +                   +                                   +
        #Stop@InferiorUnrunnable#    +                                    +
          #Creator Close Event#     +                                     +
                       +           +                                      +
                InferiorShutdownRequested                                 +
                            +                                             +
           (calls *Engine->shutdownInferior())                            +
                         |        |                                       +
                    {notify-   {notify-                                   +
                     Inferior- Inferior-                                  +
                  ShutdownOk}  ShutdownFailed}                            +
                         +        +                                       +
                         +        +                                       +
  #Inferior exited#      +        +                                       +
         |               +        +                                       +
   {notifyInferior-      +        +                                       +
      Exited}            +        +                                       +
           +             +        +                                       +
     InferiorExitOk      +        +                                       +
             +           +        +                                       +
            InferiorShutdownOk InferiorShutdownFailed                     +
                      *          *                                        +
                  EngineShutdownRequested                                 +
                            +                                             +
           (calls *Engine->shutdownEngine())  <+-+-+-+-+-+-+-+-+-+-+-+-+-+'
                         |        |
                         |        |
                    {notify-   {notify-
                     Engine-    Engine-
                  ShutdownOk}  ShutdownFailed}
                         +       +
            EngineShutdownOk  EngineShutdownFailed
                         *       *
                     DebuggerFinished

\endcode */
hjk's avatar
hjk committed
281

282 283 284
/* Here is a matching graph as a GraphViz graph. View it using
 * \code
grep "^sg1:" debuggerplugin.cpp | cut -c5- | dot -osg1.ps -Tps && gv sg1.ps
285

286 287 288 289 290 291
sg1: digraph DebuggerStates {
sg1:   DebuggerNotReady -> EngineSetupRequested
sg1:   EngineSetupRequested -> EngineSetupOk [ label="notifyEngineSetupOk", style="dashed" ];
sg1:   EngineSetupRequested -> EngineSetupFailed [ label= "notifyEngineSetupFailed", style="dashed"];
sg1:   EngineSetupFailed -> DebuggerFinished [ label= "RunControl::StartFailed" ];
sg1:   EngineSetupOk -> InferiorSetupRequested [ label= "RunControl::StartSuccessful" ];
292
sg1:   InferiorSetupRequested -> InferiorSetupOk [ label="notifyInferiorSetupOk", style="dashed" ];
293
sg1:   InferiorSetupRequested -> InferiorSetupFailed [ label="notifyInferiorFailed", style="dashed" ];
294
sg1:   InferiorSetupOk -> EngineRunRequested
295 296 297 298 299 300 301 302 303 304 305 306 307 308
sg1:   InferiorSetupFailed -> EngineShutdownRequested
sg1:   EngineRunRequested -> InferiorUnrunnable [ label="notifyInferiorUnrunnable", style="dashed" ];
sg1:   EngineRunRequested -> InferiorStopOk [ label="notifyEngineRunAndInferiorStopOk", style="dashed" ];
sg1:   EngineRunRequested -> InferiorRunOk [ label="notifyEngineRunAndInferiorRunOk", style="dashed" ];
sg1:   EngineRunRequested -> EngineRunFailed [ label="notifyEngineRunFailed", style="dashed" ];
sg1:   EngineRunFailed -> EngineShutdownRequested
sg1:   InferiorRunOk -> InferiorStopOk [ label="SpontaneousStop\nnotifyInferiorSpontaneousStop", style="dashed" ];
sg1:   InferiorRunOk -> InferiorStopRequested [ label="User stop\nEngine::interruptInferior", style="dashed"];
sg1:   InferiorStopRequested -> InferiorStopOk [ label="notifyInferiorStopOk", style="dashed" ];
sg1:   InferiorStopRequested -> InferiorShutdownRequested  [ label="notifyInferiorStopFailed", style="dashed" ];
sg1:   InferiorStopOk -> InferiorRunRequested [ label="User\nEngine::continueInferior" ];
sg1:   InferiorRunRequested -> InferiorRunOk [ label="notifyInferiorRunOk", style="dashed"];
sg1:   InferiorRunRequested -> InferiorRunFailed [ label="notifyInferiorRunFailed", style="dashed"];
sg1:   InferiorRunFailed -> InferiorStopOk
309 310
sg1:   InferiorStopOk -> InferiorShutdownRequested [ label="Close event" ];
sg1:   InferiorUnrunnable -> InferiorShutdownRequested [ label="Close event" ];
311 312
sg1:   InferiorShutdownRequested -> InferiorShutdownOk [ label= "Engine::shutdownInferior\nnotifyInferiorShutdownOk", style="dashed" ];
sg1:   InferiorShutdownRequested -> InferiorShutdownFailed [ label="Engine::shutdownInferior\nnotifyInferiorShutdownFailed", style="dashed" ];
313 314
sg1:   InferiorExited -> InferiorExitOk [ label="notifyInferiorExited", style="dashed"];
sg1:   InferiorExitOk -> InferiorShutdownOk
315 316 317 318 319 320 321 322
sg1:   InferiorShutdownOk -> EngineShutdownRequested
sg1:   InferiorShutdownFailed -> EngineShutdownRequested
sg1:   EngineShutdownRequested -> EngineShutdownOk [ label="Engine::shutdownEngine\nnotifyEngineShutdownOk", style="dashed" ];
sg1:   EngineShutdownRequested -> EngineShutdownFailed  [ label="Engine::shutdownEngine\nnotifyEngineShutdownFailed", style="dashed" ];
sg1:   EngineShutdownOk -> DebuggerFinished  [ style = "dotted" ];
sg1:   EngineShutdownFailed  -> DebuggerFinished [ style = "dotted" ];
sg1: }
* \endcode */
hjk's avatar
hjk committed
323
// Additional signalling:    {notifyInferiorIll}   {notifyEngineIll}
hjk's avatar
hjk committed
324 325


326 327
/*!
    \class Debugger::Internal::GdbEngine
328 329
    \brief The GdbEngine class implements Debugger::Engine driving a GDB
    executable.
330 331 332

    GdbEngine specific startup. All happens in EngineSetupRequested state:

Leena Miettinen's avatar
Leena Miettinen committed
333 334
    \list
        \li Transitions marked by '---' are done in the individual adapters.
335

Leena Miettinen's avatar
Leena Miettinen committed
336 337
        \li Transitions marked by '+-+' are done in the GdbEngine.
    \endlist
338 339 340 341 342 343 344 345 346 347 348 349 350

    \code
                  GdbEngine::setupEngine()
                          +
            (calls *Adapter->startAdapter())
                          |      |
                          |      `---> handleAdapterStartFailed()
                          |                   +
                          |             {notifyEngineSetupFailed}
                          |
                 handleAdapterStarted()
                          +
                 {notifyEngineSetupOk}
351 352 353



354 355 356 357 358 359 360 361 362 363 364
                GdbEngine::setupInferior()
                          +
            (calls *Adapter->prepareInferior())
                          |      |
                          |      `---> handlePrepareInferiorFailed()
                          |                   +
                          |             {notifyInferiorSetupFailed}
                          |
                handleInferiorPrepared()
                          +
                {notifyInferiorSetupOk}
365

366
\endcode */
367

con's avatar
con committed
368
using namespace Core;
hjk's avatar
hjk committed
369
using namespace Debugger::Constants;
370
using namespace ExtensionSystem;
con's avatar
con committed
371
using namespace ProjectExplorer;
hjk's avatar
hjk committed
372
using namespace TextEditor;
373
using namespace Utils;
con's avatar
con committed
374

hjk's avatar
hjk committed
375 376 377
namespace CC = Core::Constants;
namespace PE = ProjectExplorer::Constants;

con's avatar
con committed
378 379

namespace Debugger {
380 381
namespace Internal {

382 383 384 385 386 387 388 389 390 391 392 393 394
// To be passed through margin menu action's data
struct BreakpointMenuContextData : public ContextData
{
    enum Mode
    {
        Breakpoint,
        MessageTracePoint
    };

    BreakpointMenuContextData() : mode(Breakpoint) {}
    Mode mode;
};

395 396 397 398 399 400 401 402 403 404 405
struct TestCallBack
{
    TestCallBack() : receiver(0), slot(0) {}
    TestCallBack(QObject *ob, const char *s) : receiver(ob), slot(s) {}

    QObject *receiver;
    const char *slot;
    QVariant cookie;
};


406 407 408 409
} // namespace Internal
} // namespace Debugger

Q_DECLARE_METATYPE(Debugger::Internal::BreakpointMenuContextData)
410 411
Q_DECLARE_METATYPE(Debugger::Internal::TestCallBack)

412 413 414 415

namespace Debugger {
namespace Internal {

416 417 418 419 420 421
// FIXME: Outdated?
// The createCdbEngine 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.

422
void addCdbOptionPages(QList<IOptionsPage*> *opts);
423 424 425
void addGdbOptionPages(QList<IOptionsPage*> *opts);
void addScriptOptionPages(QList<IOptionsPage*> *opts);
void addTcfOptionPages(QList<IOptionsPage*> *opts);
426

427 428 429 430
#ifdef WITH_LLDB
void addLldbOptionPages(QList<IOptionsPage*> *opts);
#endif

431 432 433 434 435 436 437
static QToolButton *toolButton(QAction *action)
{
    QToolButton *button = new QToolButton;
    button->setDefaultAction(action);
    return button;
}

Orgad Shaneh's avatar
Orgad Shaneh committed
438
static void setProxyAction(ProxyAction *proxy, Core::Id id)
439
{
hjk's avatar
hjk committed
440
    proxy->setAction(ActionManager::command(id)->action());
441 442
}

Orgad Shaneh's avatar
Orgad Shaneh committed
443
static QToolButton *toolButton(Core::Id id)
444
{
hjk's avatar
hjk committed
445
    return toolButton(ActionManager::command(id)->action());
446 447
}

448 449 450 451 452 453 454 455 456 457 458
///////////////////////////////////////////////////////////////////////
//
// DummyEngine
//
///////////////////////////////////////////////////////////////////////

class DummyEngine : public DebuggerEngine
{
    Q_OBJECT

public:
459
    DummyEngine() : DebuggerEngine(DebuggerStartParameters()) {}
460 461 462 463 464 465 466
    ~DummyEngine() {}

    void setupEngine() {}
    void setupInferior() {}
    void runEngine() {}
    void shutdownEngine() {}
    void shutdownInferior() {}
467
    bool hasCapability(unsigned cap) const;
468
    bool acceptsBreakpoint(BreakpointModelId) const { return false; }
469
    bool acceptsDebuggerCommands() const { return false; }
hjk's avatar
hjk committed
470
    void selectThread(ThreadId) {}
471 472
};

473
bool DummyEngine::hasCapability(unsigned cap) const
474 475
{
    // This can only be a first approximation of what to expect when running.
476
    Project *project = ProjectExplorerPlugin::currentProject();
477 478 479 480 481 482 483 484
    if (!project)
        return 0;
    Target *target = project->activeTarget();
    QTC_ASSERT(target, return 0);
    RunConfiguration *activeRc = target->activeRunConfiguration();
    QTC_ASSERT(activeRc, return 0);

    // This is a non-started Cdb or Gdb engine:
485
    if (activeRc->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger())
486
        return cap & (WatchpointByAddressCapability
487 488
               | BreakConditionCapability
               | TracePointCapability
489
               | OperateByInstructionCapability);
490 491

    // This is a Qml or unknown engine.
492
    return cap & AddWatcherCapability;
493 494
}

495 496 497 498 499 500
///////////////////////////////////////////////////////////////////////
//
// DebugMode
//
///////////////////////////////////////////////////////////////////////

501
class DebugMode : public IMode
hjk's avatar
hjk committed
502 503
{
public:
504 505 506 507
    DebugMode()
    {
        setObjectName(QLatin1String("DebugMode"));
        setContext(Context(CC::C_EDITORMANAGER, C_DEBUGMODE, CC::C_NAVIGATION_PANE));
508 509
        setDisplayName(DebuggerPlugin::tr("Debug"));
        setIcon(QIcon(QLatin1String(":/fancyactionbar/images/mode_Debug.png")));
510
        setPriority(85);
511
        setId(MODE_DEBUG);
512
    }
hjk's avatar
hjk committed
513

hjk's avatar
hjk committed
514 515 516 517 518 519
    ~DebugMode()
    {
        // Make sure the editor manager does not get deleted.
        //EditorManager::instance()->setParent(0);
        delete m_widget;
    }
520
};
hjk's avatar
hjk committed
521

522 523 524 525 526 527
///////////////////////////////////////////////////////////////////////
//
// Misc
//
///////////////////////////////////////////////////////////////////////

hjk's avatar
hjk committed
528
static QString executableForPid(qint64 pid)
529
{
530
    foreach (const DeviceProcessItem &p, DeviceProcessList::localProcesses())
531 532 533 534 535
        if (p.pid == pid)
            return p.exe;
    return QString();
}

Tobias Hunger's avatar
Tobias Hunger committed
536
class AbiKitMatcher : public KitMatcher
537 538
{
public:
Tobias Hunger's avatar
Tobias Hunger committed
539
    explicit AbiKitMatcher(const QList<Abi> &abis) : m_abis(abis) {}
540
    bool matches(const Kit *k) const
541
    {
542
        if (const ToolChain *tc = ToolChainKitInformation::toolChain(k)) {
543
            return m_abis.contains(tc->targetAbi())
544
                   && DebuggerKitInformation::isValidDebugger(k);
545
        }
546 547 548 549 550 551 552
        return false;
    }

private:
    const QList<Abi> m_abis;
};

Tobias Hunger's avatar
Tobias Hunger committed
553
class CompatibleAbiKitMatcher : public KitMatcher
554 555
{
public:
Tobias Hunger's avatar
Tobias Hunger committed
556
    explicit CompatibleAbiKitMatcher(const QList<Abi> &abis) : m_abis(abis) {}
557
    bool matches(const Kit *k) const
558
    {
559
        if (const ToolChain *tc = ToolChainKitInformation::toolChain(k))
560
            foreach (const Abi &a, m_abis)
561
                if (a.isCompatibleWith(tc->targetAbi()) && DebuggerKitInformation::isValidDebugger(k))
562 563 564 565 566 567 568 569
                    return true;
        return false;
    }

private:
    const QList<Abi> m_abis;
};

Tobias Hunger's avatar
Tobias Hunger committed
570
class CdbMatcher : KitMatcher
hjk's avatar
hjk committed
571
{
572 573 574
public:
    CdbMatcher(char wordWidth = 0) : m_wordWidth(wordWidth) {}

Tobias Hunger's avatar
Tobias Hunger committed
575
    bool matches(const Kit *k) const
576
    {
577 578
        if (DebuggerKitInformation::engineType(k) != CdbEngineType
            || !DebuggerKitInformation::isValidDebugger(k)) {
579
            return false;
580 581 582 583 584
        }
        if (m_wordWidth) {
            const ToolChain *tc = ToolChainKitInformation::toolChain(k);
            return tc && m_wordWidth == tc->targetAbi().wordWidth();
        }
585 586 587
        return true;
    }

Tobias Hunger's avatar
Tobias Hunger committed
588
    // Find a CDB kit for debugging unknown processes.
589
    // On a 64bit OS, prefer a 64bit debugger.
Tobias Hunger's avatar
Tobias Hunger committed
590
    static Kit *findUniversalCdbKit()
591 592 593 594
    {
#ifdef Q_OS_WIN
        if (Utils::winIs64BitSystem()) {
            CdbMatcher matcher64(64);
595
            if (Kit *cdb64Kit = KitManager::find(matcher64))
Tobias Hunger's avatar
Tobias Hunger committed
596
                return cdb64Kit;
597 598 599
        }
#endif
        CdbMatcher matcher;
600
        return KitManager::find(matcher);
601 602 603 604 605 606
    }

private:
    const char m_wordWidth;
};

607
bool fillParameters(DebuggerStartParameters *sp, const Kit *kit, QString *errorMessage /* = 0 */)
608
{
Tobias Hunger's avatar
Tobias Hunger committed
609
    if (!kit) {
610 611
        // This code can only be reached when starting via the command line
        // (-debug pid or executable) or attaching from runconfiguration
Tobias Hunger's avatar
Tobias Hunger committed
612
        // without specifying a kit. Try to find a kit via ABI.
613 614 615 616 617 618 619 620 621 622 623
        QList<Abi> abis;
        if (sp->toolChainAbi.isValid()) {
            abis.push_back(sp->toolChainAbi);
        } else {
            // Try via executable.
            if (sp->executable.isEmpty()
                && (sp->startMode == AttachExternal || sp->startMode == AttachCrashedExternal)) {
                sp->executable = executableForPid(sp->attachPID);
            }
            if (!sp->executable.isEmpty())
                abis = Abi::abisOfBinary(Utils::FileName::fromString(sp->executable));
624
        }
625
        if (!abis.isEmpty()) {
626 627 628
            kit = KitManager::find(AbiKitMatcher(abis));
            if (!kit)
                kit = KitManager::find(CompatibleAbiKitMatcher(abis));
629
        }
Tobias Hunger's avatar
Tobias Hunger committed
630
        if (!kit)
631
            kit = KitManager::defaultKit();
632 633
    }

634 635 636 637 638 639 640
    // Verify that debugger and profile are valid
    if (!kit) {
        sp->startMode = NoStartMode;
        if (errorMessage)
            *errorMessage = DebuggerKitInformation::tr("No kit found.");
        return false;
    }
641 642
    // validate debugger if C++ debugging is enabled
    if (sp->languages & CppLanguage) {
hjk's avatar
hjk committed
643
        const QList<Task> tasks = DebuggerKitInformation::validateDebugger(kit);
644 645 646
        if (!tasks.isEmpty()) {
            sp->startMode = NoStartMode;
            if (errorMessage) {
hjk's avatar
hjk committed
647
                foreach (const Task &t, tasks) {
648 649 650 651
                    if (errorMessage->isEmpty())
                        errorMessage->append(QLatin1Char('\n'));
                    errorMessage->append(t.description);
                }
652
            }
653
            return false;
654 655 656
        }
    }
    sp->cppEngineType = DebuggerKitInformation::engineType(kit);
Tobias Hunger's avatar
Tobias Hunger committed
657 658
    sp->sysRoot = SysRootKitInformation::sysRoot(kit).toString();
    sp->debuggerCommand = DebuggerKitInformation::debuggerCommand(kit).toString();
659

Tobias Hunger's avatar
Tobias Hunger committed
660
    ToolChain *tc = ToolChainKitInformation::toolChain(kit);
hjk's avatar
hjk committed
661 662
    if (tc)
        sp->toolChainAbi = tc->targetAbi();
663

Tobias Hunger's avatar
Tobias Hunger committed
664
    IDevice::ConstPtr device = DeviceKitInformation::device(kit);
665 666
    if (device) {
        sp->connParams = device->sshParameters();
667 668 669
        // Could have been set from command line.
        if (sp->remoteChannel.isEmpty())
            sp->remoteChannel = sp->connParams.host + QLatin1Char(':') + QString::number(sp->connParams.port);
670
    }
671
    return true;
hjk's avatar
hjk committed
672 673
}

674
static TextEditor::ITextEditor *currentTextEditor()
675
{
hjk's avatar
hjk committed
676
    return qobject_cast<TextEditor::ITextEditor *>(EditorManager::currentEditor());
677
}
con's avatar
con committed
678

679 680
static bool currentTextEditorPosition(ContextData *data)
{
681 682 683
    TextEditor::ITextEditor *textEditor = currentTextEditor();
    if (!textEditor)
        return false;
hjk's avatar
hjk committed
684
    const IDocument *document = textEditor->document();
685
    QTC_ASSERT(document, return false);
686
    data->fileName = document->filePath();
687
    if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
688
        int lineNumber = textEditor->currentLine();
689
        QString line = textEditor->textDocument()->contents()
690 691 692 693
            .section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1);
        data->address = DisassemblerLine::addressFromDisassemblyLine(line);
    } else {
        data->lineNumber = textEditor->currentLine();
694
    }
695
    return true;
696
}
697

698 699
///////////////////////////////////////////////////////////////////////
//
700
// DebuggerPluginPrivate
701 702
//
///////////////////////////////////////////////////////////////////////
con's avatar
con committed
703

704
static DebuggerPluginPrivate *theDebuggerCore = 0;
con's avatar
con committed
705

706 707 708 709 710 711 712 713 714 715 716 717 718 719
/*!
    \class Debugger::Internal::DebuggerCore

    This is the "internal" interface of the debugger plugin that's
    used by debugger views and debugger engines. The interface is
    implemented in DebuggerPluginPrivate.
*/

/*!
    \class Debugger::Internal::DebuggerPluginPrivate

    Implementation of DebuggerCore.
*/

720
class DebuggerPluginPrivate : public DebuggerCore
721 722
{
    Q_OBJECT
723

724 725
public:
    explicit DebuggerPluginPrivate(DebuggerPlugin *plugin);
726
    ~DebuggerPluginPrivate();
727

728
    bool initialize(const QStringList &arguments, QString *errorMessage);
729 730 731
    void extensionsInitialized();
    void aboutToShutdown();

732
    void connectEngine(DebuggerEngine *engine);
hjk's avatar
hjk committed
733
    void disconnectEngine() { connectEngine(0); }
734
    DebuggerEngine *currentEngine() const { return m_currentEngine; }
735
    DebuggerEngine *dummyEngine();
736

737 738 739 740 741 742 743 744 745 746
    void setThreads(const QStringList &list, int index)
    {
        const bool state = m_threadBox->blockSignals(true);
        m_threadBox->clear();
        foreach (const QString &item, list)
            m_threadBox->addItem(item);
        m_threadBox->setCurrentIndex(index);
        m_threadBox->blockSignals(state);
    }

747
public slots:
748 749 750 751 752 753
    void writeSettings()
    {
        m_debuggerSettings->writeSettings();
        m_mainWindow->writeSettings();
    }

754 755
    void selectThread(int index)
    {
hjk's avatar
hjk committed
756 757
        ThreadId id = m_currentEngine->threadsHandler()->threadAt(index);
        m_currentEngine->selectThread(id);
758
    }
759

hjk's avatar
hjk committed
760
    void breakpointSetMarginActionTriggered()
761
    {
762 763
        const QAction *action = qobject_cast<const QAction *>(sender());
        QTC_ASSERT(action, return);
hjk's avatar
hjk committed
764 765
        const BreakpointMenuContextData data =
            action->data().value<BreakpointMenuContextData>();
766 767 768 769 770 771 772 773 774 775 776 777 778
        QString message;
        if (data.mode == BreakpointMenuContextData::MessageTracePoint) {
            if (data.address) {
                //: Message tracepoint: Address hit.
                message = tr("0x%1 hit").arg(data.address, 0, 16);
            } else {
                //: Message tracepoint: %1 file, %2 line %3 function hit.
                message = tr("%1:%2 %3() hit").arg(QFileInfo(data.fileName).fileName()).
                        arg(data.lineNumber).
                        arg(cppFunctionAt(data.fileName, data.lineNumber));
            }
            QInputDialog dialog; // Create wide input dialog.
            dialog.setWindowFlags(dialog.windowFlags()
hjk's avatar
hjk committed
779
              & ~(Qt::WindowContextHelpButtonHint|Qt::MSWindowsFixedSizeDialogHint));
780 781 782 783 784 785 786 787
            dialog.resize(600, dialog.height());
            dialog.setWindowTitle(tr("Add Message Tracepoint"));
            dialog.setLabelText (tr("Message:"));
            dialog.setTextValue(message);
            if (dialog.exec() != QDialog::Accepted || dialog.textValue().isEmpty())
                return;
            message = dialog.textValue();
        }
788
        if (data.address)
789
            toggleBreakpointByAddress(data.address, message);
790
        else
791
            toggleBreakpointByFileAndLine(data.fileName, data.lineNumber, message);
792
    }
793

hjk's avatar
hjk committed
794
    void breakpointRemoveMarginActionTriggered()
795
    {
hjk's avatar
hjk committed
796 797
        const QAction *act = qobject_cast<QAction *>(sender());
        QTC_ASSERT(act, return);
798
        BreakpointModelId id = act->data().value<BreakpointModelId>();
hjk's avatar
hjk committed
799
        m_breakHandler->removeBreakpoint(id);
hjk's avatar
hjk committed
800 801 802 803 804 805
     }

    void breakpointEnableMarginActionTriggered()
    {
        const QAction *act = qobject_cast<QAction *>(sender());
        QTC_ASSERT(act, return);
806
        BreakpointModelId id = act->data().value<BreakpointModelId>();
hjk's avatar
hjk committed
807
        breakHandler()->setEnabled(id, true);
hjk's avatar
hjk committed
808 809 810 811 812 813
    }

    void breakpointDisableMarginActionTriggered()
    {
        const QAction *act = qobject_cast<QAction *>(sender());
        QTC_ASSERT(act, return);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
814
        BreakpointModelId id = act->data().value<BreakpointModelId>();
hjk's avatar
hjk committed
815
        breakHandler()->setEnabled(id, false);
816 817
    }

818
    void updateWatchersHeader(int section, int, int newSize)
819 820
    {
        m_watchersWindow->header()->resizeSection(section, newSize);
821
        m_returnWindow->header()->resizeSection(section, newSize);
822
    }
823

824

825
    void sourceFilesDockToggled(bool on)
826
    {
827
        if (on && m_currentEngine->state() == InferiorStopOk)
828 829 830
            m_currentEngine->reloadSourceFiles();
    }

831
    void modulesDockToggled(bool on)
832
    {
833
        if (on && m_currentEngine->state() == InferiorStopOk)
834 835
            m_currentEngine->reloadModules();
    }
836

hjk's avatar
hjk committed
837
    void registerDockToggled(bool on)
838
    {
839
        if (on && m_currentEngine->state() == InferiorStopOk)
840 841
            m_currentEngine->reloadRegisters();
    }
842

843 844
    void synchronizeBreakpoints()
    {
845
        showMessage(QLatin1String("ATTEMPT SYNC"), LogDebug);
846
        for (int i = 0, n = m_snapshotHandler->size(); i != n; ++i) {
847
            if (DebuggerEngine *engine = m_snapshotHandler->at(i))
848 849 850 851
                engine->attemptBreakpointSynchronization();
        }
    }

hjk's avatar
hjk committed
852 853 854
    void synchronizeWatchers()
    {
        for (int i = 0, n = m_snapshotHandler->size(); i != n; ++i) {
855
            if (DebuggerEngine *engine = m_snapshotHandler->at(i))
856
                engine->watchHandler()->updateWatchers();
hjk's avatar
hjk committed
857 858 859
        }
    }

860
    void editorOpened(Core::IEditor *editor);
861
    void updateBreakMenuItem(Core::IEditor *editor);
862
    void setBusyCursor(bool busy);
863 864 865
    void requestMark(TextEditor::ITextEditor *editor,
                     int lineNumber,
                     TextEditor::ITextEditor::MarkRequestKind kind);
866 867
    void requestContextMenu(TextEditor::ITextEditor *editor,
        int lineNumber, QMenu *menu);
868

869 870 871
    void activatePreviousMode();
    void activateDebugMode();
    void toggleBreakpoint();
872 873 874 875
    void toggleBreakpointByFileAndLine(const QString &fileName, int lineNumber,
                                       const QString &tracePointMessage = QString());
    void toggleBreakpointByAddress(quint64 address,
                                   const QString &tracePointMessage = QString());
876
    void onModeChanged(Core::IMode *mode);
877
    void onCoreAboutToOpen();
878
    void showSettingsDialog();
879
    void updateDebugWithoutDeployMenu();
880

881
    void debugProject();
882
    void debugProjectWithoutDeploy();
883
    void debugProjectBreakMain();
884
    void startAndDebugApplication();
885
    void startRemoteCdbSession();
886
    void startRemoteServer();
887
    void attachToRemoteServer();
888
    void attachToProcess(bool startServerOnly);
hjk's avatar
hjk committed
889
    void attachToRunningApplication();
890
    void attachExternalApplication(ProjectExplorer::RunControl *rc);
891
    void attachToQmlPort();
892
    void startRemoteEngine();
893
    void runScheduled();
894
    void attachCore();
895

896
    void enableReverseDebuggingTriggered(const QVariant &value);
hjk's avatar
hjk committed
897
    void languagesChanged();
898
    void showStatusMessage(const QString &msg, int timeout = -1);
899
    void openMemoryEditor();
900

901 902
    const CPlusPlus::Snapshot &cppCodeModelSnapshot() const;

hjk's avatar
hjk committed
903
    DebuggerMainWindow *mainWindow() const { return m_mainWindow; }
904
    bool isDockVisible(const QString &objectName) const
hjk's avatar
hjk committed
905
        { return mainWindow()->isDockVisible(objectName); }
906 907

    bool hasSnapshots() const { return m_snapshotHandler->size(); }
hjk's avatar
hjk committed
908
    void createNewDock(QWidget *widget);
909

910 911
    void runControlStarted(DebuggerEngine *engine);
    void runControlFinished(DebuggerEngine *engine);
912 913 914 915
    DebuggerLanguages activeLanguages() const;
    void remoteCommand(const QStringList &options, const QStringList &);

    bool isReverseDebugging() const;
916

917 918 919
    BreakHandler *breakHandler() const { return m_breakHandler; }
    SnapshotHandler *snapshotHandler() const { return m_snapshotHandler; }

920
    void displayDebugger(DebuggerEngine *engine, bool updateEngine = true);
921 922 923

    void dumpLog();
    void cleanupViews();
924
    void setInitialState();
925 926 927 928

    void fontSettingsChanged(const TextEditor::FontSettings &settings);

    void updateState(DebuggerEngine *engine);
hjk's avatar
hjk committed
929
    void updateWatchersWindow(bool showWatch, bool showReturn);
930
    void onCurrentProjectChanged(ProjectExplorer::Project *project);
931 932 933 934

    void sessionLoaded();
    void aboutToUnloadSession();
    void aboutToSaveSession();
935

936
    void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
937
    void coreShutdown();
938

hjk's avatar
hjk committed
939 940
#ifdef WITH_TESTS
public slots:
941
    void testLoadProject(const QString &proFile, const TestCallBack &cb);
hjk's avatar
hjk committed
942
    void testProjectLoaded(ProjectExplorer::Project *project);
943 944
    void testProjectEvaluated();
    void testProjectBuilt(bool success);
945 946 947 948
    void testUnloadProject();
    void testFinished();

    void testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb);
hjk's avatar
hjk committed
949
    void testRunControlFinished();
950

hjk's avatar
hjk committed
951 952 953
//    void testStateMachine1();
//    void testStateMachine2();
//    void testStateMachine3();
954

955 956
    void testBenchmark1();

957
public:
hjk's avatar
hjk committed
958
    Project *m_testProject;
959 960 961
    bool m_testSuccess;
    QList<TestCallBack> m_testCallbacks;

hjk's avatar
hjk committed
962 963
#endif

hjk's avatar
hjk committed
964
public slots:
965
    void updateDebugActions();
966 967 968

    void handleExecDetach()
    {
969
        currentEngine()->resetLocation();
970 971 972 973 974
        currentEngine()->detachDebugger();
    }

    void handleExecContinue()
    {
975
        currentEngine()->resetLocation();
976 977 978 979 980
        currentEngine()->continueInferior();
    }

    void handleExecInterrupt()
    {
981
        currentEngine()->resetLocation();
982 983 984
        currentEngine()->requestInterruptInferior();
    }

985
    void handleAbort()
986
    {
987
        currentEngine()->resetLocation();
988
        currentEngine()->abortDebugger();
989
    }
hjk's avatar
hjk committed
990 991 992

    void handleExecStep()
    {
993 994 995 996 997 998 999 1000 1001
        if (currentEngine()->state() == DebuggerNotReady) {
            debugProjectBreakMain();
        } else {
            currentEngine()->resetLocation();
            if (boolSetting(OperateByInstruction))
                currentEngine()->executeStepI();
            else
                currentEngine()->executeStep();
        }
hjk's avatar
hjk committed
1002 1003 1004 1005
    }

    void handleExecNext()
    {