pdbengine.cpp 25.4 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


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


77
#define CB(callback) [this](const DebuggerResponse &r) { callback(r); }
hjk's avatar
hjk committed
78 79 80 81 82 83 84 85 86 87

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
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
    postCommand(command.toLatin1(), CB(handleExecuteDebuggerCommand));
}

111
void PdbEngine::handleExecuteDebuggerCommand(const DebuggerResponse &response)
112 113 114 115 116 117 118 119
{
    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
void PdbEngine::postCommand(const QByteArray &command, DebuggerCommand::Callback callback)
hjk's avatar
hjk committed
124
{
125
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
126 127
    DebuggerCommand cmd;
    cmd.function = command;
hjk's avatar
hjk committed
128 129
    cmd.callback = callback;
    m_commands.enqueue(cmd);
130 131 132
    qDebug() << "ENQUEUE: " << cmd.function;
    showMessage(_(cmd.function), LogInput);
    m_pdbProc.write(cmd.function + '\n');
hjk's avatar
hjk committed
133 134
}

hjk's avatar
hjk committed
135
void PdbEngine::shutdownInferior()
hjk's avatar
hjk committed
136
{
hjk's avatar
hjk committed
137 138
    QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
    notifyInferiorShutdownOk();
hjk's avatar
hjk committed
139 140
}

hjk's avatar
hjk committed
141
void PdbEngine::shutdownEngine()
hjk's avatar
hjk committed
142
{
hjk's avatar
hjk committed
143
    QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
hjk's avatar
hjk committed
144 145 146
    m_pdbProc.kill();
}

hjk's avatar
hjk committed
147
void PdbEngine::setupEngine()
hjk's avatar
hjk committed
148
{
hjk's avatar
hjk committed
149
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
hjk's avatar
hjk committed
150

151
    m_pdb = _("python");
152
    showMessage(_("STARTING PDB ") + m_pdb);
hjk's avatar
hjk committed
153

154 155 156 157 158 159 160 161 162 163 164
    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);
165

Tobias Hunger's avatar
Tobias Hunger committed
166
    // We will stop immediately, so setup a proper callback.
167
    DebuggerCommand cmd;
168
    cmd.callback = CB(handleFirstCommand);
hjk's avatar
hjk committed
169 170
    m_commands.enqueue(cmd);

171
    m_pdbProc.start(m_pdb, QStringList() << _("-i"));
hjk's avatar
hjk committed
172 173

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

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

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

204 205 206 207 208
QString PdbEngine::mainPythonFile() const
{
    return QFileInfo(startParameters().processArgs).absoluteFilePath();
}

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

void PdbEngine::interruptInferior()
{
226
    notifyInferiorStopOk();
hjk's avatar
hjk committed
227 228 229 230
}

void PdbEngine::executeStep()
{
231
    resetLocation();
232 233
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
234 235 236 237 238
    postCommand("step", CB(handleUpdateAll));
}

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

void PdbEngine::executeStepOut()
{
247
    resetLocation();
248 249
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
250 251 252 253 254
    postCommand("finish", CB(handleUpdateAll));
}

void PdbEngine::executeNext()
{
255
    resetLocation();
256 257
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
258 259 260 261 262
    postCommand("next", CB(handleUpdateAll));
}

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

void PdbEngine::continueInferior()
{
271
    resetLocation();
272 273
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
274 275 276 277
    // Callback will be triggered e.g. when breakpoint is hit.
    postCommand("continue", CB(handleUpdateAll));
}

278
void PdbEngine::executeRunToLine(const ContextData &data)
hjk's avatar
hjk committed
279
{
280
    Q_UNUSED(data)
hjk's avatar
hjk committed
281 282 283 284 285 286 287 288 289
    SDEBUG("FIXME:  PdbEngine::runToLineExec()");
}

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

290
void PdbEngine::executeJumpToLine(const ContextData &data)
hjk's avatar
hjk committed
291
{
292
    Q_UNUSED(data)
hjk's avatar
hjk committed
293 294 295 296 297
    XSDEBUG("FIXME:  PdbEngine::jumpToLineExec()");
}

void PdbEngine::activateFrame(int frameIndex)
{
298
    resetLocation();
hjk's avatar
hjk committed
299
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
hjk's avatar
hjk committed
300 301
        return;

302 303
    StackHandler *handler = stackHandler();
    int oldIndex = handler->currentIndex();
hjk's avatar
hjk committed
304

305
    //if (frameIndex == handler->stackSize()) {
hjk's avatar
hjk committed
306 307 308 309
    //    reloadFullStack();
    //    return;
    //}

310
    QTC_ASSERT(frameIndex < handler->stackSize(), return);
hjk's avatar
hjk committed
311 312 313 314 315

    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.
316
        handler->setCurrentIndex(frameIndex);
hjk's avatar
hjk committed
317 318 319
        //postCommand("-stack-select-frame " + QByteArray::number(frameIndex),
        //    CB(handleStackSelectFrame));
    }
320
    gotoLocation(handler->currentFrame());
hjk's avatar
hjk committed
321 322
}

hjk's avatar
hjk committed
323
void PdbEngine::selectThread(ThreadId threadId)
hjk's avatar
hjk committed
324
{
hjk's avatar
hjk committed
325
    Q_UNUSED(threadId)
hjk's avatar
hjk committed
326 327
}

328
bool PdbEngine::acceptsBreakpoint(Breakpoint bp) const
hjk's avatar
hjk committed
329
{
330
    const QString fileName = bp.fileName();
hjk's avatar
hjk committed
331 332 333
    return fileName.endsWith(QLatin1String(".py"));
}

334
void PdbEngine::insertBreakpoint(Breakpoint bp)
hjk's avatar
hjk committed
335
{
336 337
    QTC_CHECK(bp.state() == BreakpointInsertRequested);
    bp.notifyBreakpointInsertProceeding();
hjk's avatar
hjk committed
338 339

    QByteArray loc;
340 341
    if (bp.type() == BreakpointByFunction)
        loc = bp.functionName().toLatin1();
hjk's avatar
hjk committed
342
    else
343 344
        loc = bp.fileName().toLocal8Bit() + ':'
         + QByteArray::number(bp.lineNumber());
hjk's avatar
hjk committed
345

346
    postCommand("break " + loc, [this, bp](const DebuggerResponse &r) { handleBreakInsert(r, bp); });
hjk's avatar
hjk committed
347 348
}

349
void PdbEngine::handleBreakInsert(const DebuggerResponse &response, Breakpoint bp)
hjk's avatar
hjk committed
350 351 352
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
353 354
    QTC_ASSERT(response.logStreamOutput.startsWith("Breakpoint "), return);
    int pos1 = response.logStreamOutput.indexOf(" at ");
hjk's avatar
hjk committed
355
    QTC_ASSERT(pos1 != -1, return);
356 357 358 359
    QByteArray bpnr = response.logStreamOutput.mid(11, pos1 - 11);
    int pos2 = response.logStreamOutput.lastIndexOf(':');
    QByteArray file = response.logStreamOutput.mid(pos1 + 4, pos2 - pos1 - 4);
    QByteArray line = response.logStreamOutput.mid(pos2 + 1);
hjk's avatar
hjk committed
360
    BreakpointResponse br;
361
    br.id = BreakpointResponseId(bpnr);
362 363
    br.fileName = _(file);
    br.lineNumber = line.toInt();
364 365 366
    bp.setResponse(br);
    QTC_CHECK(!bp.needsChange());
    bp.notifyBreakpointInsertOk();
hjk's avatar
hjk committed
367 368
}

369
void PdbEngine::removeBreakpoint(Breakpoint bp)
hjk's avatar
hjk committed
370
{
371 372 373 374
    QTC_CHECK(bp.state() == BreakpointRemoveRequested);
    bp.notifyBreakpointRemoveProceeding();
    BreakpointResponse br = bp.response();
    showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString()).arg(bp.fileName()));
375
    postCommand("clear " + br.id.toByteArray());
hjk's avatar
hjk committed
376
    // Pretend it succeeds without waiting for response.
377
    bp.notifyBreakpointRemoveOk();
hjk's avatar
hjk committed
378 379
}

hjk's avatar
hjk committed
380 381 382 383 384 385 386 387 388 389 390
void PdbEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void PdbEngine::loadAllSymbols()
{
}

void PdbEngine::reloadModules()
{
391
    //postCommand("qdebug('listmodules')", CB(handleListModules));
hjk's avatar
hjk committed
392 393
}

394
void PdbEngine::handleListModules(const DebuggerResponse &response)
hjk's avatar
hjk committed
395 396
{
    GdbMi out;
397
    out.fromString(response.logStreamOutput.trimmed());
398 399
    ModulesHandler *handler = modulesHandler();
    handler->beginUpdateAll();
hjk's avatar
hjk committed
400 401
    foreach (const GdbMi &item, out.children()) {
        Module module;
402 403
        module.moduleName = _(item["name"].data());
        QString path = _(item["value"].data());
hjk's avatar
hjk committed
404 405 406 407 408 409 410 411 412 413
        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;
414
        handler->updateModule(module);
hjk's avatar
hjk committed
415
    }
416
    handler->endUpdateAll();
hjk's avatar
hjk committed
417 418
}

hjk's avatar
hjk committed
419
void PdbEngine::requestModuleSymbols(const QString &moduleName)
hjk's avatar
hjk committed
420
{
hjk's avatar
hjk committed
421
    postCommand("qdebug('listsymbols','" + moduleName.toLatin1() + "')",
422
                [this, moduleName](const DebuggerResponse &r) { handleListSymbols(r, moduleName); });
hjk's avatar
hjk committed
423 424
}

425
void PdbEngine::handleListSymbols(const DebuggerResponse &response, const QString &moduleName)
hjk's avatar
hjk committed
426 427
{
    GdbMi out;
428
    out.fromString(response.logStreamOutput.trimmed());
429
    Symbols symbols;
hjk's avatar
hjk committed
430 431
    foreach (const GdbMi &item, out.children()) {
        Symbol symbol;
432
        symbol.name = _(item["name"].data());
hjk's avatar
hjk committed
433 434
        symbols.append(symbol);
    }
435
    Internal::showModuleSymbols(moduleName, symbols);
hjk's avatar
hjk committed
436
}
hjk's avatar
hjk committed
437 438 439 440 441 442 443 444 445 446 447 448

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


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

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

    int line;
    int column;
463
    QString exp = cppExpressionAt(editorWidget, ctx.position, &line, &column);
hjk's avatar
hjk committed
464 465 466 467

    QToolTip::hideText();
    if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')))  {
        QToolTip::hideText();
468
        return false;
hjk's avatar
hjk committed
469 470 471
    }

    if (!hasLetterOrNumber(exp)) {
472
        QToolTip::showText(m_toolTipPos, tr("\"%1\" contains no identifier").arg(exp));
473
        return true;
hjk's avatar
hjk committed
474 475 476 477
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
478
        return true;
hjk's avatar
hjk committed
479 480 481 482 483 484 485 486 487
    }

    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('[')))
488
        return false;
hjk's avatar
hjk committed
489 490 491

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
492
            tr("Cowardly refusing to evaluate expression \"%1\" "
hjk's avatar
hjk committed
493
               "with potential side effects").arg(exp));
494
        return true;
hjk's avatar
hjk committed
495 496 497
    }

#if 0
hjk's avatar
hjk committed
498
    //if (status() != InferiorStopOk)
hjk's avatar
hjk committed
499 500 501 502 503 504 505 506 507
    //    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
508
    return false;
hjk's avatar
hjk committed
509 510 511 512 513 514 515 516 517
}


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

518
void PdbEngine::assignValueInDebugger(const Internal::WatchData *, const QString &expression, const QVariant &value)
hjk's avatar
hjk committed
519 520 521
{
    Q_UNUSED(expression);
    Q_UNUSED(value);
522
    SDEBUG("ASSIGNING: " << (expression + QLatin1Char('=') + value.toString()));
hjk's avatar
hjk committed
523
#if 0
524
    m_scriptEngine->evaluate(expression + QLatin1Char('=') + value.toString());
hjk's avatar
hjk committed
525 526 527 528 529
    updateLocals();
#endif
}


530
void PdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
hjk's avatar
hjk committed
531 532
{
    Q_UNUSED(data);
hjk's avatar
hjk committed
533
    Q_UNUSED(flags);
hjk's avatar
hjk committed
534 535 536 537 538
    updateAll();
}

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
539
    qDebug() << "HANDLE PDB ERROR";
540
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
541 542 543 544 545 546 547 548
    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:
549
        //setState(EngineShutdownRequested, true);
hjk's avatar
hjk committed
550
        m_pdbProc.kill();
551 552
        Core::AsynchronousMessageBox::critical(tr("Pdb I/O Error"),
                                               errorMessage(error));
hjk's avatar
hjk committed
553 554 555 556 557 558 559 560 561
        break;
    }
}

QString PdbEngine::errorMessage(QProcess::ProcessError error) const
{
    switch (error) {
        case QProcess::FailedToStart:
            return tr("The Pdb process failed to start. Either the "
562
                "invoked program \"%1\" is missing, or you may have insufficient "
hjk's avatar
hjk committed
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
                "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:
580
            return tr("An unknown error in the Pdb process occurred.") + QLatin1Char(' ');
hjk's avatar
hjk committed
581 582 583 584 585
    }
}

void PdbEngine::handlePdbFinished(int code, QProcess::ExitStatus type)
{
586
    qDebug() << "PDB FINISHED";
587
    showMessage(_("PDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
588
    notifyEngineSpontaneousShutdown();
hjk's avatar
hjk committed
589 590 591 592 593
}

void PdbEngine::readPdbStandardError()
{
    QByteArray err = m_pdbProc.readAllStandardError();
594 595 596 597
    qDebug() << "\nPDB STDERR" << err;
    //qWarning() << "Unexpected pdb stderr:" << err;
    //showMessage(_("Unexpected pdb stderr: " + err));
    //handleOutput(err);
hjk's avatar
hjk committed
598 599 600 601
}

void PdbEngine::readPdbStandardOutput()
{
602 603 604 605 606 607 608 609 610
    QByteArray out = m_pdbProc.readAllStandardOutput();
    qDebug() << "\nPDB STDOUT" << out;
    handleOutput(out);
}

void PdbEngine::handleOutput(const QByteArray &data)
{
    //qDebug() << "READ: " << data;
    m_inbuffer.append(data);
611
    qDebug() << "BUFFER FROM: '" << m_inbuffer << '\'';
612 613 614 615 616 617 618
    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
619
        m_inbuffer = m_inbuffer.mid(pos + 6);
620 621
        emit outputReady(response);
    }
622
    qDebug() << "BUFFER LEFT: '" << m_inbuffer << '\'';
623 624 625 626 627 628
    //m_inbuffer.clear();
}


void PdbEngine::handleOutput2(const QByteArray &data)
{
629 630
    DebuggerResponse response;
    response.logStreamOutput = data;
631
    showMessage(_(data));
632
    QTC_ASSERT(!m_commands.isEmpty(), qDebug() << "RESPONSE: " << data; return);
633 634
    DebuggerCommand cmd = m_commands.dequeue();
    qDebug() << "DEQUE: " << cmd.function;
635 636 637
    if (cmd.callback) {
        //qDebug() << "EXECUTING CALLBACK " << cmd.callbackName
        //    << " RESPONSE: " << response.data;
638
        cmd.callback(response);
639
    } else {
640
        qDebug() << "NO CALLBACK FOR RESPONSE: " << response.logStreamOutput;
hjk's avatar
hjk committed
641 642
    }
}
643
/*
hjk's avatar
hjk committed
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
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);
662
            qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
663 664 665 666 667
                << response.mid(pos1 + 1, pos2 - pos1 - 1);
            StackFrame frame;
            frame.file = _(fileName);
            frame.line = lineNumber;
            if (frame.line > 0 && QFileInfo(frame.file).exists()) {
668
                gotoLocation(frame);
669
                notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
670 671 672 673 674 675
                return;
            }
        }
    }
    qDebug() << "COULD NOT PARSE RESPONSE: '" << response << "'";
}
676
*/
hjk's avatar
hjk committed
677

678
void PdbEngine::handleFirstCommand(const DebuggerResponse &response)
hjk's avatar
hjk committed
679 680 681 682
{
    Q_UNUSED(response);
}

683
void PdbEngine::handleUpdateAll(const DebuggerResponse &response)
hjk's avatar
hjk committed
684 685
{
    Q_UNUSED(response);
686
    notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
687 688 689 690
    updateAll();
}

void PdbEngine::updateAll()
691 692 693 694 695 696
{
    postCommand("bt", CB(handleBacktrace));
    //updateLocals();
}

void PdbEngine::updateLocals()
hjk's avatar
hjk committed
697 698 699 700 701 702
{
    QByteArray watchers;
    //if (!m_toolTipExpression.isEmpty())
    //    watchers += m_toolTipExpression.toLatin1()
    //        + '#' + tooltipINameForExpression(m_toolTipExpression.toLatin1());

hjk's avatar
hjk committed
703
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
704 705 706 707 708 709
    QHash<QByteArray, int> watcherNames = handler->watcherNames();
    QHashIterator<QByteArray, int> it(watcherNames);
    while (it.hasNext()) {
        it.next();
        if (!watchers.isEmpty())
            watchers += "##";
710
        watchers += it.key() + "#watch." + QByteArray::number(it.value());
hjk's avatar
hjk committed
711 712 713
    }

    QByteArray options;
hjk's avatar
hjk committed
714
    if (boolSetting(UseDebuggingHelpers))
hjk's avatar
hjk committed
715
        options += "fancy,";
hjk's avatar
hjk committed
716
    if (boolSetting(AutoDerefPointers))
hjk's avatar
hjk committed
717 718 719 720 721 722
        options += "autoderef,";
    if (options.isEmpty())
        options += "defaults,";
    options.chop(1);

    postCommand("qdebug('" + options + "','"
723
//        + handler->expansionRequests() + "','"
hjk's avatar
hjk committed
724 725 726 727 728
        + handler->typeFormatRequests() + "','"
        + handler->individualFormatRequests() + "','"
        + watchers.toHex() + "')", CB(handleListLocals));
}

729
void PdbEngine::handleBacktrace(const DebuggerResponse &response)
hjk's avatar
hjk committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
{
    //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.
745
    StackFrames stackFrames;
hjk's avatar
hjk committed
746 747
    int level = 0;
    int currentIndex = -1;
748
    foreach (const QByteArray &line, response.logStreamOutput.split('\n')) {
hjk's avatar
hjk committed
749 750 751 752 753 754 755
        //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);
756
                //qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
757 758 759 760 761
                //    << 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
762
                frame.usable = QFileInfo(frame.file).isReadable();
763
                if (frame.line > 0 && QFileInfo::exists(frame.file)) {
hjk's avatar
hjk committed
764 765 766 767 768 769 770 771 772 773
                    if (line.startsWith("> "))
                        currentIndex = level;
                    frame.level = level;
                    stackFrames.prepend(frame);
                    ++level;
                }
            }
        }
    }
    const int frameCount = stackFrames.size();
774 775
    for (int i = 0; i != frameCount; ++i)
        stackFrames[i].level = frameCount - stackFrames[i].level - 1;
776
    stackHandler()->setFrames(stackFrames);
hjk's avatar
hjk committed
777 778 779 780

    // Select current frame.
    if (currentIndex != -1) {
        currentIndex = frameCount - currentIndex - 1;
781
        stackHandler()->setCurrentIndex(currentIndex);
782
        gotoLocation(stackFrames.at(currentIndex));
hjk's avatar
hjk committed
783
    }
784 785

    updateLocals();
hjk's avatar
hjk committed
786 787
}

788
void PdbEngine::handleListLocals(const DebuggerResponse &response)
hjk's avatar
hjk committed
789 790
{
    //qDebug() << " LOCALS: '" << response.data << "'";
791
    QByteArray out = response.logStreamOutput.trimmed();
hjk's avatar
hjk committed
792 793 794 795 796 797

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

    //GdbMi data = all.findChild("data");
798
    WatchHandler *handler = watchHandler();
799 800 801 802 803

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

hjk's avatar
hjk committed
804
    foreach (const GdbMi &child, all.children()) {
hjk's avatar
hjk committed
805
        WatchItem *item = new WatchItem(child);
806 807
        handler->insertItem(item);
        toDelete.remove(item->d.iname);
hjk's avatar
hjk committed
808
    }
809 810

    handler->purgeOutdatedItems(toDelete);
hjk's avatar
hjk committed
811 812
}

813
bool PdbEngine::hasCapability(unsigned cap) const
hjk's avatar
hjk committed
814
{
815
    return cap & (ReloadModuleCapability|BreakConditionCapability);
hjk's avatar
hjk committed
816 817
}

818
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
hjk's avatar
hjk committed
819
{
820
    return new PdbEngine(startParameters);
hjk's avatar
hjk committed
821 822 823 824
}

} // namespace Internal
} // namespace Debugger