pdbengine.cpp 25.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
hjk's avatar
hjk committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
hjk's avatar
hjk committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
hjk's avatar
hjk committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** 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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
hjk's avatar
hjk committed
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30 31 32

#include "pdbengine.h"

33 34 35 36 37 38 39 40
#include <debugger/debuggeractions.h>
#include <debugger/debuggercore.h>
#include <debugger/debuggerdialogs.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerprotocol.h>
#include <debugger/debuggerstartparameters.h>
#include <debugger/debuggerstringutils.h>
#include <debugger/debuggertooltipmanager.h>
41

42 43 44 45 46 47 48
#include <debugger/breakhandler.h>
#include <debugger/moduleshandler.h>
#include <debugger/registerhandler.h>
#include <debugger/stackhandler.h>
#include <debugger/sourceutils.h>
#include <debugger/watchhandler.h>
#include <debugger/watchutils.h>
49

hjk's avatar
hjk committed
50 51
#include <utils/qtcassert.h>

52
#include <texteditor/texteditor.h>
53
#include <coreplugin/idocument.h>
hjk's avatar
hjk committed
54
#include <coreplugin/icore.h>
55
#include <coreplugin/messagebox.h>
hjk's avatar
hjk committed
56

57 58 59 60 61 62
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
#include <QVariant>
hjk's avatar
hjk committed
63

64 65
#include <QApplication>
#include <QToolTip>
hjk's avatar
hjk committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87


#define DEBUG_SCRIPT 1
#if DEBUG_SCRIPT
#   define SDEBUG(s) qDebug() << s
#else
#   define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s


#define CB(callback) &PdbEngine::callback, STRINGIFY(callback)

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// PdbEngine
//
///////////////////////////////////////////////////////////////////////

88
PdbEngine::PdbEngine(const DebuggerStartParameters &startParameters)
89
    : DebuggerEngine(startParameters)
Friedemann Kleint's avatar
Friedemann Kleint committed
90 91 92
{
    setObjectName(QLatin1String("PdbEngine"));
}
hjk's avatar
hjk committed
93 94 95 96

PdbEngine::~PdbEngine()
{}

97
void PdbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
hjk's avatar
hjk committed
98
{
99 100
    if (!(languages & CppLanguage))
        return;
101 102
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
    //XSDEBUG("PdbEngine::executeDebuggerCommand:" << command);
hjk's avatar
hjk committed
103
    if (state() == DebuggerNotReady) {
104
        showMessage(_("PDB PROCESS NOT RUNNING, PLAIN CMD IGNORED: ") + command);
hjk's avatar
hjk committed
105 106
        return;
    }
107 108 109 110 111 112 113 114 115 116 117 118 119
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
    postCommand(command.toLatin1(), CB(handleExecuteDebuggerCommand));
}

void PdbEngine::handleExecuteDebuggerCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

void PdbEngine::postDirectCommand(const QByteArray &command)
{
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
    showMessage(_(command), LogInput);
hjk's avatar
hjk committed
120
    m_pdbProc.write(command + '\n');
hjk's avatar
hjk committed
121 122 123 124 125 126 127 128
}

void PdbEngine::postCommand(const QByteArray &command,
//                 PdbCommandFlags flags,
                 PdbCommandCallback callback,
                 const char *callbackName,
                 const QVariant &cookie)
{
129
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
hjk's avatar
hjk committed
130 131 132 133 134 135
    PdbCommand cmd;
    cmd.command = command;
    cmd.callback = callback;
    cmd.callbackName = callbackName;
    cmd.cookie = cookie;
    m_commands.enqueue(cmd);
136
    qDebug() << "ENQUEUE: " << command << cmd.callbackName;
137
    showMessage(_(cmd.command), LogInput);
hjk's avatar
hjk committed
138
    m_pdbProc.write(cmd.command + '\n');
hjk's avatar
hjk committed
139 140
}

hjk's avatar
hjk committed
141
void PdbEngine::shutdownInferior()
hjk's avatar
hjk committed
142
{
hjk's avatar
hjk committed
143 144
    QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
    notifyInferiorShutdownOk();
hjk's avatar
hjk committed
145 146
}

hjk's avatar
hjk committed
147
void PdbEngine::shutdownEngine()
hjk's avatar
hjk committed
148
{
hjk's avatar
hjk committed
149
    QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
hjk's avatar
hjk committed
150 151 152
    m_pdbProc.kill();
}

hjk's avatar
hjk committed
153
void PdbEngine::setupEngine()
hjk's avatar
hjk committed
154
{
hjk's avatar
hjk committed
155
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
hjk's avatar
hjk committed
156

157
    m_pdb = _("python");
158
    showMessage(_("STARTING PDB ") + m_pdb);
hjk's avatar
hjk committed
159

160 161 162 163 164 165 166 167 168 169 170
    connect(&m_pdbProc, static_cast<void(QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
        this, &PdbEngine::handlePdbError);
    connect(&m_pdbProc, static_cast<void(QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished),
        this, &PdbEngine::handlePdbFinished);
    connect(&m_pdbProc, &QProcess::readyReadStandardOutput,
        this, &PdbEngine::readPdbStandardOutput);
    connect(&m_pdbProc, &QProcess::readyReadStandardError,
        this, &PdbEngine::readPdbStandardError);

    connect(this, &PdbEngine::outputReady,
        this, &PdbEngine::handleOutput2, Qt::QueuedConnection);
171

Tobias Hunger's avatar
Tobias Hunger committed
172
    // We will stop immediately, so setup a proper callback.
hjk's avatar
hjk committed
173
    PdbCommand cmd;
hjk's avatar
hjk committed
174
    cmd.callback = &PdbEngine::handleFirstCommand;
hjk's avatar
hjk committed
175 176
    m_commands.enqueue(cmd);

177
    m_pdbProc.start(m_pdb, QStringList() << _("-i"));
hjk's avatar
hjk committed
178 179

    if (!m_pdbProc.waitForStarted()) {
180
        const QString msg = tr("Unable to start pdb \"%1\": %2")
hjk's avatar
hjk committed
181
            .arg(m_pdb, m_pdbProc.errorString());
182
        notifyEngineSetupFailed();
183
        showMessage(_("ADAPTER START FAILED"));
hjk's avatar
hjk committed
184 185
        if (!msg.isEmpty()) {
            const QString title = tr("Adapter start failed");
hjk's avatar
hjk committed
186
            Core::ICore::showWarningWithOptions(title, msg);
hjk's avatar
hjk committed
187
        }
188
        notifyEngineSetupFailed();
hjk's avatar
hjk committed
189 190
        return;
    }
191
    notifyEngineSetupOk();
hjk's avatar
hjk committed
192 193 194 195
}

void PdbEngine::setupInferior()
{
hjk's avatar
hjk committed
196
    QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
hjk's avatar
hjk committed
197

198
    QString fileName = mainPythonFile();
199 200
    QFile scriptFile(fileName);
    if (!scriptFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
201
        Core::AsynchronousMessageBox::critical(tr("Python Error"),
202 203 204 205 206 207
            _("Cannot open script file %1:\n%2").
               arg(fileName, scriptFile.errorString()));
        notifyInferiorSetupFailed();
        return;
    }
    notifyInferiorSetupOk();
hjk's avatar
hjk committed
208 209
}

210 211 212 213 214
QString PdbEngine::mainPythonFile() const
{
    return QFileInfo(startParameters().processArgs).absoluteFilePath();
}

hjk's avatar
hjk committed
215
void PdbEngine::runEngine()
hjk's avatar
hjk committed
216
{
217
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
hjk's avatar
hjk committed
218
    showStatusMessage(tr("Running requested..."), 5000);
219
    const QByteArray dumperSourcePath =
220
        Core::ICore::resourcePath().toLocal8Bit() + "/debugger/";
221
    postDirectCommand("import sys");
222
    postDirectCommand("sys.argv.append('" + mainPythonFile().toLocal8Bit() + "')");
223
    postDirectCommand("execfile('/usr/bin/pdb')");
224
    postDirectCommand("execfile('" + dumperSourcePath + "pdbbridge.py')");
225 226 227
    attemptBreakpointSynchronization();
    notifyEngineRunAndInferiorStopOk();
    continueInferior();
hjk's avatar
hjk committed
228 229 230 231
}

void PdbEngine::interruptInferior()
{
232
    notifyInferiorStopOk();
hjk's avatar
hjk committed
233 234 235 236
}

void PdbEngine::executeStep()
{
237
    resetLocation();
238 239
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
240 241 242 243 244
    postCommand("step", CB(handleUpdateAll));
}

void PdbEngine::executeStepI()
{
245
    resetLocation();
246 247
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
248 249 250 251 252
    postCommand("step", CB(handleUpdateAll));
}

void PdbEngine::executeStepOut()
{
253
    resetLocation();
254 255
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
256 257 258 259 260
    postCommand("finish", CB(handleUpdateAll));
}

void PdbEngine::executeNext()
{
261
    resetLocation();
262 263
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
264 265 266 267 268
    postCommand("next", CB(handleUpdateAll));
}

void PdbEngine::executeNextI()
{
269
    resetLocation();
270 271
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
272 273 274 275 276
    postCommand("next", CB(handleUpdateAll));
}

void PdbEngine::continueInferior()
{
277
    resetLocation();
278 279
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
280 281 282 283
    // Callback will be triggered e.g. when breakpoint is hit.
    postCommand("continue", CB(handleUpdateAll));
}

284
void PdbEngine::executeRunToLine(const ContextData &data)
hjk's avatar
hjk committed
285
{
286
    Q_UNUSED(data)
hjk's avatar
hjk committed
287 288 289 290 291 292 293 294 295
    SDEBUG("FIXME:  PdbEngine::runToLineExec()");
}

void PdbEngine::executeRunToFunction(const QString &functionName)
{
    Q_UNUSED(functionName)
    XSDEBUG("FIXME:  PdbEngine::runToFunctionExec()");
}

296
void PdbEngine::executeJumpToLine(const ContextData &data)
hjk's avatar
hjk committed
297
{
298
    Q_UNUSED(data)
hjk's avatar
hjk committed
299 300 301 302 303
    XSDEBUG("FIXME:  PdbEngine::jumpToLineExec()");
}

void PdbEngine::activateFrame(int frameIndex)
{
304
    resetLocation();
hjk's avatar
hjk committed
305
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
hjk's avatar
hjk committed
306 307
        return;

308 309
    StackHandler *handler = stackHandler();
    int oldIndex = handler->currentIndex();
hjk's avatar
hjk committed
310

311
    //if (frameIndex == handler->stackSize()) {
hjk's avatar
hjk committed
312 313 314 315
    //    reloadFullStack();
    //    return;
    //}

316
    QTC_ASSERT(frameIndex < handler->stackSize(), return);
hjk's avatar
hjk committed
317 318 319 320 321

    if (oldIndex != frameIndex) {
        // Assuming the command always succeeds this saves a roundtrip.
        // Otherwise the lines below would need to get triggered
        // after a response to this -stack-select-frame here.
322
        handler->setCurrentIndex(frameIndex);
hjk's avatar
hjk committed
323 324 325
        //postCommand("-stack-select-frame " + QByteArray::number(frameIndex),
        //    CB(handleStackSelectFrame));
    }
326
    gotoLocation(handler->currentFrame());
hjk's avatar
hjk committed
327 328
}

hjk's avatar
hjk committed
329
void PdbEngine::selectThread(ThreadId threadId)
hjk's avatar
hjk committed
330
{
hjk's avatar
hjk committed
331
    Q_UNUSED(threadId)
hjk's avatar
hjk committed
332 333
}

334
bool PdbEngine::acceptsBreakpoint(Breakpoint bp) const
hjk's avatar
hjk committed
335
{
336
    const QString fileName = bp.fileName();
hjk's avatar
hjk committed
337 338 339
    return fileName.endsWith(QLatin1String(".py"));
}

340
void PdbEngine::insertBreakpoint(Breakpoint bp)
hjk's avatar
hjk committed
341
{
342 343
    QTC_CHECK(bp.state() == BreakpointInsertRequested);
    bp.notifyBreakpointInsertProceeding();
hjk's avatar
hjk committed
344 345

    QByteArray loc;
346 347
    if (bp.type() == BreakpointByFunction)
        loc = bp.functionName().toLatin1();
hjk's avatar
hjk committed
348
    else
349 350
        loc = bp.fileName().toLocal8Bit() + ':'
         + QByteArray::number(bp.lineNumber());
hjk's avatar
hjk committed
351

352
    postCommand("break " + loc, CB(handleBreakInsert), QVariant::fromValue(bp));
hjk's avatar
hjk committed
353 354 355 356 357 358 359 360 361 362
}

void PdbEngine::handleBreakInsert(const PdbResponse &response)
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
    QTC_ASSERT(response.data.startsWith("Breakpoint "), return);
    int pos1 = response.data.indexOf(" at ");
    QTC_ASSERT(pos1 != -1, return);
    QByteArray bpnr = response.data.mid(11, pos1 - 11);
363
    int pos2 = response.data.lastIndexOf(':');
hjk's avatar
hjk committed
364 365
    QByteArray file = response.data.mid(pos1 + 4, pos2 - pos1 - 4);
    QByteArray line = response.data.mid(pos2 + 1);
hjk's avatar
hjk committed
366
    BreakpointResponse br;
367
    br.id = BreakpointResponseId(bpnr);
368 369
    br.fileName = _(file);
    br.lineNumber = line.toInt();
370 371 372 373
    Breakpoint bp = response.cookie.value<Breakpoint>();
    bp.setResponse(br);
    QTC_CHECK(!bp.needsChange());
    bp.notifyBreakpointInsertOk();
hjk's avatar
hjk committed
374 375
}

376
void PdbEngine::removeBreakpoint(Breakpoint bp)
hjk's avatar
hjk committed
377
{
378 379 380 381
    QTC_CHECK(bp.state() == BreakpointRemoveRequested);
    bp.notifyBreakpointRemoveProceeding();
    BreakpointResponse br = bp.response();
    showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString()).arg(bp.fileName()));
382
    postCommand("clear " + br.id.toByteArray());
hjk's avatar
hjk committed
383
    // Pretend it succeeds without waiting for response.
384
    bp.notifyBreakpointRemoveOk();
hjk's avatar
hjk committed
385 386
}

hjk's avatar
hjk committed
387 388 389 390 391 392 393 394 395 396 397
void PdbEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void PdbEngine::loadAllSymbols()
{
}

void PdbEngine::reloadModules()
{
398
    //postCommand("qdebug('listmodules')", CB(handleListModules));
hjk's avatar
hjk committed
399 400 401 402 403 404
}

void PdbEngine::handleListModules(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
405 406
    ModulesHandler *handler = modulesHandler();
    handler->beginUpdateAll();
hjk's avatar
hjk committed
407 408
    foreach (const GdbMi &item, out.children()) {
        Module module;
409 410
        module.moduleName = _(item["name"].data());
        QString path = _(item["value"].data());
hjk's avatar
hjk committed
411 412 413 414 415 416 417 418 419 420
        int pos = path.indexOf(_("' from '"));
        if (pos != -1) {
            path = path.mid(pos + 8);
            if (path.size() >= 2)
                path.chop(2);
        } else if (path.startsWith(_("<module '"))
                && path.endsWith(_("' (built-in)>"))) {
            path = _("(builtin)");
        }
        module.modulePath = path;
421
        handler->updateModule(module);
hjk's avatar
hjk committed
422
    }
423
    handler->endUpdateAll();
hjk's avatar
hjk committed
424 425
}

hjk's avatar
hjk committed
426
void PdbEngine::requestModuleSymbols(const QString &moduleName)
hjk's avatar
hjk committed
427
{
hjk's avatar
hjk committed
428 429
    postCommand("qdebug('listsymbols','" + moduleName.toLatin1() + "')",
        CB(handleListSymbols), moduleName);
hjk's avatar
hjk committed
430 431
}

hjk's avatar
hjk committed
432 433 434 435
void PdbEngine::handleListSymbols(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
436
    Symbols symbols;
hjk's avatar
hjk committed
437 438 439
    QString moduleName = response.cookie.toString();
    foreach (const GdbMi &item, out.children()) {
        Symbol symbol;
440
        symbol.name = _(item["name"].data());
hjk's avatar
hjk committed
441 442
        symbols.append(symbol);
    }
443
    Internal::showModuleSymbols(moduleName, symbols);
hjk's avatar
hjk committed
444
}
hjk's avatar
hjk committed
445 446 447 448 449 450 451 452 453 454 455 456

//////////////////////////////////////////////////////////////////////
//
// Tooltip specific stuff
//
//////////////////////////////////////////////////////////////////////


static WatchData m_toolTip;
static QPoint m_toolTipPos;
static QHash<QString, WatchData> m_toolTipCache;

457
bool PdbEngine::setToolTipExpression(TextEditor::TextEditorWidget *editorWidget,
hjk's avatar
hjk committed
458
    const DebuggerToolTipContext &ctx)
hjk's avatar
hjk committed
459
{
hjk's avatar
hjk committed
460
    if (state() != InferiorStopOk) {
hjk's avatar
hjk committed
461
        //SDEBUG("SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED");
462
        return false;
hjk's avatar
hjk committed
463 464
    }
    // Check mime type and get expression (borrowing some C++ - functions)
465 466
    const QString javaPythonMimeType = QLatin1String("application/javascript");
    if (editorWidget->textDocument()->mimeType() != javaPythonMimeType)
467
        return false;
hjk's avatar
hjk committed
468 469 470

    int line;
    int column;
471
    QString exp = cppExpressionAt(editorWidget, ctx.position, &line, &column);
hjk's avatar
hjk committed
472 473 474 475

    QToolTip::hideText();
    if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')))  {
        QToolTip::hideText();
476
        return false;
hjk's avatar
hjk committed
477 478 479
    }

    if (!hasLetterOrNumber(exp)) {
480
        QToolTip::showText(m_toolTipPos, tr("\"%1\" contains no identifier").arg(exp));
481
        return true;
hjk's avatar
hjk committed
482 483 484 485
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
486
        return true;
hjk's avatar
hjk committed
487 488 489 490 491 492 493 494 495
    }

    if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
        exp.remove(0, 2);

    if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
        exp.remove(0, 2);

    if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
496
        return false;
hjk's avatar
hjk committed
497 498 499

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
500
            tr("Cowardly refusing to evaluate expression \"%1\" "
hjk's avatar
hjk committed
501
               "with potential side effects").arg(exp));
502
        return true;
hjk's avatar
hjk committed
503 504 505
    }

#if 0
hjk's avatar
hjk committed
506
    //if (status() != InferiorStopOk)
hjk's avatar
hjk committed
507 508 509 510 511 512 513 514 515
    //    return;

    // FIXME: 'exp' can contain illegal characters
    m_toolTip = WatchData();
    m_toolTip.exp = exp;
    m_toolTip.name = exp;
    m_toolTip.iname = tooltipIName;
    insertData(m_toolTip);
#endif
516
    return false;
hjk's avatar
hjk committed
517 518 519 520 521 522 523 524 525
}


//////////////////////////////////////////////////////////////////////
//
// Watch specific stuff
//
//////////////////////////////////////////////////////////////////////

526
void PdbEngine::assignValueInDebugger(const Internal::WatchData *, const QString &expression, const QVariant &value)
hjk's avatar
hjk committed
527 528 529
{
    Q_UNUSED(expression);
    Q_UNUSED(value);
530
    SDEBUG("ASSIGNING: " << (expression + QLatin1Char('=') + value.toString()));
hjk's avatar
hjk committed
531
#if 0
532
    m_scriptEngine->evaluate(expression + QLatin1Char('=') + value.toString());
hjk's avatar
hjk committed
533 534 535 536 537
    updateLocals();
#endif
}


538
void PdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
hjk's avatar
hjk committed
539 540
{
    Q_UNUSED(data);
hjk's avatar
hjk committed
541
    Q_UNUSED(flags);
hjk's avatar
hjk committed
542 543 544 545 546
    updateAll();
}

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
547
    qDebug() << "HANDLE PDB ERROR";
548
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
549 550 551 552 553 554 555 556
    switch (error) {
    case QProcess::Crashed:
        break; // will get a processExited() as well
    // impossible case QProcess::FailedToStart:
    case QProcess::ReadError:
    case QProcess::WriteError:
    case QProcess::Timedout:
    default:
557
        //setState(EngineShutdownRequested, true);
hjk's avatar
hjk committed
558
        m_pdbProc.kill();
559 560
        Core::AsynchronousMessageBox::critical(tr("Pdb I/O Error"),
                                               errorMessage(error));
hjk's avatar
hjk committed
561 562 563 564 565 566 567 568 569
        break;
    }
}

QString PdbEngine::errorMessage(QProcess::ProcessError error) const
{
    switch (error) {
        case QProcess::FailedToStart:
            return tr("The Pdb process failed to start. Either the "
570
                "invoked program \"%1\" is missing, or you may have insufficient "
hjk's avatar
hjk committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
                "permissions to invoke the program.")
                .arg(m_pdb);
        case QProcess::Crashed:
            return tr("The Pdb process crashed some time after starting "
                "successfully.");
        case QProcess::Timedout:
            return tr("The last waitFor...() function timed out. "
                "The state of QProcess is unchanged, and you can try calling "
                "waitFor...() again.");
        case QProcess::WriteError:
            return tr("An error occurred when attempting to write "
                "to the Pdb process. For example, the process may not be running, "
                "or it may have closed its input channel.");
        case QProcess::ReadError:
            return tr("An error occurred when attempting to read from "
                "the Pdb process. For example, the process may not be running.");
        default:
588
            return tr("An unknown error in the Pdb process occurred.") + QLatin1Char(' ');
hjk's avatar
hjk committed
589 590 591 592 593
    }
}

void PdbEngine::handlePdbFinished(int code, QProcess::ExitStatus type)
{
594
    qDebug() << "PDB FINISHED";
595
    showMessage(_("PDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
596
    notifyEngineSpontaneousShutdown();
hjk's avatar
hjk committed
597 598 599 600 601
}

void PdbEngine::readPdbStandardError()
{
    QByteArray err = m_pdbProc.readAllStandardError();
602 603 604 605
    qDebug() << "\nPDB STDERR" << err;
    //qWarning() << "Unexpected pdb stderr:" << err;
    //showMessage(_("Unexpected pdb stderr: " + err));
    //handleOutput(err);
hjk's avatar
hjk committed
606 607 608 609
}

void PdbEngine::readPdbStandardOutput()
{
610 611 612 613 614 615 616 617 618
    QByteArray out = m_pdbProc.readAllStandardOutput();
    qDebug() << "\nPDB STDOUT" << out;
    handleOutput(out);
}

void PdbEngine::handleOutput(const QByteArray &data)
{
    //qDebug() << "READ: " << data;
    m_inbuffer.append(data);
619
    qDebug() << "BUFFER FROM: '" << m_inbuffer << '\'';
620 621 622 623 624 625 626
    while (true) {
        int pos = m_inbuffer.indexOf("(Pdb)");
        if (pos == -1)
            pos = m_inbuffer.indexOf(">>>");
        if (pos == -1)
            break;
        QByteArray response = m_inbuffer.left(pos).trimmed();
hjk's avatar
hjk committed
627
        m_inbuffer = m_inbuffer.mid(pos + 6);
628 629
        emit outputReady(response);
    }
630
    qDebug() << "BUFFER LEFT: '" << m_inbuffer << '\'';
631 632 633 634 635 636 637 638 639
    //m_inbuffer.clear();
}


void PdbEngine::handleOutput2(const QByteArray &data)
{
    PdbResponse response;
    response.data = data;
    showMessage(_(data));
640
    QTC_ASSERT(!m_commands.isEmpty(), qDebug() << "RESPONSE: " << data; return);
641 642 643 644 645 646 647 648 649
    PdbCommand cmd = m_commands.dequeue();
    response.cookie = cmd.cookie;
    qDebug() << "DEQUE: " << cmd.command << cmd.callbackName;
    if (cmd.callback) {
        //qDebug() << "EXECUTING CALLBACK " << cmd.callbackName
        //    << " RESPONSE: " << response.data;
        (this->*cmd.callback)(response);
    } else {
        qDebug() << "NO CALLBACK FOR RESPONSE: " << response.data;
hjk's avatar
hjk committed
650 651
    }
}
652
/*
hjk's avatar
hjk committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
void PdbEngine::handleResponse(const QByteArray &response0)
{
    QByteArray response = response0;
    qDebug() << "RESPONSE: '" << response << "'";
    if (response.startsWith("--Call--")) {
        qDebug() << "SKIPPING '--Call--' MARKER";
        response = response.mid(9);
    }
    if (response.startsWith("--Return--")) {
        qDebug() << "SKIPPING '--Return--' MARKER";
        response = response.mid(11);
    }
    if (response.startsWith("> ")) {
        int pos1 = response.indexOf('(');
        int pos2 = response.indexOf(')', pos1);
        if (pos1 != -1 && pos2 != -1) {
            int lineNumber = response.mid(pos1 + 1, pos2 - pos1 - 1).toInt();
            QByteArray fileName = response.mid(2, pos1 - 2);
671
            qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
672 673 674 675 676
                << response.mid(pos1 + 1, pos2 - pos1 - 1);
            StackFrame frame;
            frame.file = _(fileName);
            frame.line = lineNumber;
            if (frame.line > 0 && QFileInfo(frame.file).exists()) {
677
                gotoLocation(frame);
678
                notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
679 680 681 682 683 684
                return;
            }
        }
    }
    qDebug() << "COULD NOT PARSE RESPONSE: '" << response << "'";
}
685
*/
hjk's avatar
hjk committed
686

hjk's avatar
hjk committed
687 688 689 690 691
void PdbEngine::handleFirstCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

hjk's avatar
hjk committed
692 693 694
void PdbEngine::handleUpdateAll(const PdbResponse &response)
{
    Q_UNUSED(response);
695
    notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
696 697 698 699
    updateAll();
}

void PdbEngine::updateAll()
700 701 702 703 704 705
{
    postCommand("bt", CB(handleBacktrace));
    //updateLocals();
}

void PdbEngine::updateLocals()
hjk's avatar
hjk committed
706 707 708 709 710 711
{
    QByteArray watchers;
    //if (!m_toolTipExpression.isEmpty())
    //    watchers += m_toolTipExpression.toLatin1()
    //        + '#' + tooltipINameForExpression(m_toolTipExpression.toLatin1());

hjk's avatar
hjk committed
712
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
713 714 715 716 717 718
    QHash<QByteArray, int> watcherNames = handler->watcherNames();
    QHashIterator<QByteArray, int> it(watcherNames);
    while (it.hasNext()) {
        it.next();
        if (!watchers.isEmpty())
            watchers += "##";
719
        watchers += it.key() + "#watch." + QByteArray::number(it.value());
hjk's avatar
hjk committed
720 721 722
    }

    QByteArray options;
hjk's avatar
hjk committed
723
    if (boolSetting(UseDebuggingHelpers))
hjk's avatar
hjk committed
724
        options += "fancy,";
hjk's avatar
hjk committed
725
    if (boolSetting(AutoDerefPointers))
hjk's avatar
hjk committed
726 727 728 729 730 731
        options += "autoderef,";
    if (options.isEmpty())
        options += "defaults,";
    options.chop(1);

    postCommand("qdebug('" + options + "','"
732
//        + handler->expansionRequests() + "','"
hjk's avatar
hjk committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
        + handler->typeFormatRequests() + "','"
        + handler->individualFormatRequests() + "','"
        + watchers.toHex() + "')", CB(handleListLocals));
}

void PdbEngine::handleBacktrace(const PdbResponse &response)
{
    //qDebug() << " BACKTRACE: '" << response.data << "'";
    // "  /usr/lib/python2.6/bdb.py(368)run()"
    // "-> exec cmd in globals, locals"
    // "  <string>(1)<module>()"
    // "  /python/math.py(19)<module>()"
    // "-> main()"
    // "  /python/math.py(14)main()"
    // "-> print cube(3)"
    // "  /python/math.py(7)cube()"
    // "-> x = square(a)"
    // "> /python/math.py(2)square()"
    // "-> def square(a):"

    // Populate stack view.
754
    StackFrames stackFrames;
hjk's avatar
hjk committed
755 756 757 758 759 760 761 762 763 764
    int level = 0;
    int currentIndex = -1;
    foreach (const QByteArray &line, response.data.split('\n')) {
        //qDebug() << "  LINE: '" << line << "'";
        if (line.startsWith("> ") || line.startsWith("  ")) {
            int pos1 = line.indexOf('(');
            int pos2 = line.indexOf(')', pos1);
            if (pos1 != -1 && pos2 != -1) {
                int lineNumber = line.mid(pos1 + 1, pos2 - pos1 - 1).toInt();
                QByteArray fileName = line.mid(2, pos1 - 2);
765
                //qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
766 767 768 769 770
                //    << line.mid(pos1 + 1, pos2 - pos1 - 1);
                StackFrame frame;
                frame.file = _(fileName);
                frame.line = lineNumber;
                frame.function = _(line.mid(pos2 + 1));
hjk's avatar
hjk committed
771
                frame.usable = QFileInfo(frame.file).isReadable();
772
                if (frame.line > 0 && QFileInfo::exists(frame.file)) {
hjk's avatar
hjk committed
773 774 775 776 777 778 779 780 781 782
                    if (line.startsWith("> "))
                        currentIndex = level;
                    frame.level = level;
                    stackFrames.prepend(frame);
                    ++level;
                }
            }
        }
    }
    const int frameCount = stackFrames.size();
783 784
    for (int i = 0; i != frameCount; ++i)
        stackFrames[i].level = frameCount - stackFrames[i].level - 1;
785
    stackHandler()->setFrames(stackFrames);
hjk's avatar
hjk committed
786 787 788 789

    // Select current frame.
    if (currentIndex != -1) {
        currentIndex = frameCount - currentIndex - 1;
790
        stackHandler()->setCurrentIndex(currentIndex);
791
        gotoLocation(stackFrames.at(currentIndex));
hjk's avatar
hjk committed
792
    }
793 794

    updateLocals();
hjk's avatar
hjk committed
795 796 797 798 799 800 801 802 803 804 805 806
}

void PdbEngine::handleListLocals(const PdbResponse &response)
{
    //qDebug() << " LOCALS: '" << response.data << "'";
    QByteArray out = response.data.trimmed();

    GdbMi all;
    all.fromStringMultiple(out);
    //qDebug() << "ALL: " << all.toString();

    //GdbMi data = all.findChild("data");
807
    WatchHandler *handler = watchHandler();
808 809 810 811 812

    QSet<QByteArray> toDelete;
    foreach (WatchItem *item, handler->model()->treeLevelItems<WatchItem *>(2))
        toDelete.insert(item->d.iname);

hjk's avatar
hjk committed
813
    foreach (const GdbMi &child, all.children()) {
hjk's avatar
hjk committed
814
        WatchItem *item = new WatchItem(child);
815 816
        handler->insertItem(item);
        toDelete.remove(item->d.iname);
hjk's avatar
hjk committed
817
    }
818 819

    handler->purgeOutdatedItems(toDelete);
hjk's avatar
hjk committed
820 821
}

822
bool PdbEngine::hasCapability(unsigned cap) const
hjk's avatar
hjk committed
823
{
824
    return cap & (ReloadModuleCapability|BreakConditionCapability);
hjk's avatar
hjk committed
825 826
}

827
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
hjk's avatar
hjk committed
828
{
829
    return new PdbEngine(startParameters);
hjk's avatar
hjk committed
830 831 832 833
}

} // namespace Internal
} // namespace Debugger