pdbengine.cpp 26.6 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
}

135 136 137 138 139 140 141 142
void PdbEngine::runCommand(const DebuggerCommand &cmd)
{
    QTC_ASSERT(m_pdbProc.state() == QProcess::Running, notifyEngineIll());
    QByteArray command = "theDumper." + cmd.function + "({" + cmd.args + "})";
    showMessage(_(command), LogInput);
    m_pdbProc.write(command + '\n');
}

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

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

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

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

162 163 164 165 166 167 168 169 170 171 172
    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);
173

Tobias Hunger's avatar
Tobias Hunger committed
174
    // We will stop immediately, so setup a proper callback.
175
    DebuggerCommand cmd;
176
    cmd.callback = CB(handleFirstCommand);
hjk's avatar
hjk committed
177 178
    m_commands.enqueue(cmd);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    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.
324
        handler->setCurrentIndex(frameIndex);
hjk's avatar
hjk committed
325 326 327
        //postCommand("-stack-select-frame " + QByteArray::number(frameIndex),
        //    CB(handleStackSelectFrame));
    }
328
    gotoLocation(handler->currentFrame());
hjk's avatar
hjk committed
329 330
}

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

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

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

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

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

357
void PdbEngine::handleBreakInsert(const DebuggerResponse &response, Breakpoint bp)
hjk's avatar
hjk committed
358 359 360
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
361 362
    QTC_ASSERT(response.logStreamOutput.startsWith("Breakpoint "), return);
    int pos1 = response.logStreamOutput.indexOf(" at ");
hjk's avatar
hjk committed
363
    QTC_ASSERT(pos1 != -1, return);
364 365 366 367
    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
368
    BreakpointResponse br;
369
    br.id = BreakpointResponseId(bpnr);
370 371
    br.fileName = _(file);
    br.lineNumber = line.toInt();
372 373
    if (!bp.isValid())
        bp = breakHandler()->findBreakpointByFileAndLine(br.fileName, br.lineNumber, false);
374 375 376
    bp.setResponse(br);
    QTC_CHECK(!bp.needsChange());
    bp.notifyBreakpointInsertOk();
hjk's avatar
hjk committed
377 378
}

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

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

void PdbEngine::loadAllSymbols()
{
}

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

404
void PdbEngine::handleListModules(const DebuggerResponse &response)
hjk's avatar
hjk committed
405 406
{
    GdbMi out;
407
    out.fromString(response.logStreamOutput.trimmed());
408 409
    ModulesHandler *handler = modulesHandler();
    handler->beginUpdateAll();
hjk's avatar
hjk committed
410 411
    foreach (const GdbMi &item, out.children()) {
        Module module;
412 413
        module.moduleName = _(item["name"].data());
        QString path = _(item["value"].data());
hjk's avatar
hjk committed
414 415 416 417 418 419 420 421 422 423
        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;
424
        handler->updateModule(module);
hjk's avatar
hjk committed
425
    }
426
    handler->endUpdateAll();
hjk's avatar
hjk committed
427 428
}

hjk's avatar
hjk committed
429
void PdbEngine::requestModuleSymbols(const QString &moduleName)
hjk's avatar
hjk committed
430
{
hjk's avatar
hjk committed
431
    postCommand("qdebug('listsymbols','" + moduleName.toLatin1() + "')",
432
                [this, moduleName](const DebuggerResponse &r) { handleListSymbols(r, moduleName); });
hjk's avatar
hjk committed
433 434
}

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

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


static WatchData m_toolTip;
static QPoint m_toolTipPos;

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

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

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

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

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

    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('[')))
497
        return false;
hjk's avatar
hjk committed
498 499 500

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

#if 0
hjk's avatar
hjk committed
507
    //if (status() != InferiorStopOk)
hjk's avatar
hjk committed
508 509 510 511 512 513 514 515 516
    //    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
517
    return false;
hjk's avatar
hjk committed
518 519 520 521 522 523 524 525 526
}


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

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


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

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
548
    qDebug() << "HANDLE PDB ERROR";
549
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
550 551 552 553 554 555 556 557
    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:
558
        //setState(EngineShutdownRequested, true);
hjk's avatar
hjk committed
559
        m_pdbProc.kill();
560 561
        Core::AsynchronousMessageBox::critical(tr("Pdb I/O Error"),
                                               errorMessage(error));
hjk's avatar
hjk committed
562 563 564 565 566 567 568 569 570
        break;
    }
}

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

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

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

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

void PdbEngine::handleOutput(const QByteArray &data)
{
    //qDebug() << "READ: " << data;
    m_inbuffer.append(data);
620
    qDebug() << "BUFFER FROM: '" << m_inbuffer << '\'';
621 622 623 624 625 626 627
    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
628
        m_inbuffer = m_inbuffer.mid(pos + 6);
629 630
        emit outputReady(response);
    }
631
    qDebug() << "BUFFER LEFT: '" << m_inbuffer << '\'';
632 633 634 635 636 637
    //m_inbuffer.clear();
}


void PdbEngine::handleOutput2(const QByteArray &data)
{
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    QByteArray lineContext;
    foreach (QByteArray line, data.split('\n')) {
//        line = line.trimmed();

        DebuggerResponse response;
        response.logStreamOutput = line;
        response.data.fromString(line);
        showMessage(_("LINE: " + line));

        if (line.startsWith("stack={")) {
            refreshStack(response.data);
            continue;
        }
        if (line.startsWith("data={")) {
            refreshLocals(response.data);
            continue;
        }
        if (line.startsWith("Breakpoint")) {
            handleBreakInsert(response, Breakpoint());
            continue;
        }

        if (line.startsWith("> /")) {
            lineContext = line;
            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);
                qDebug() << " " << pos1 << pos2 << lineNumber << fileName
                         << line.mid(pos1 + 1, pos2 - pos1 - 1);
                StackFrame frame;
                frame.file = _(fileName);
                frame.line = lineNumber;
                if (state() == InferiorRunOk) {
                    showMessage(QString::fromLatin1("STOPPED AT: %1:%2").arg(frame.file).arg(frame.line));
                    gotoLocation(frame);
                    notifyInferiorSpontaneousStop();
                    updateAll();
                    continue;
                }
            }
        }

        if (line.startsWith("-> ")) {
            // Current line
        }

        showMessage(_(" #### ... UNHANDLED"));
hjk's avatar
hjk committed
687
    }
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702


//    DebuggerResponse response;
//    response.logStreamOutput = data;
//    showMessage(_(data));
//    QTC_ASSERT(!m_commands.isEmpty(), qDebug() << "RESPONSE: " << data; return);
//    DebuggerCommand cmd = m_commands.dequeue();
//    qDebug() << "DEQUE: " << cmd.function;
//    if (cmd.callback) {
//        //qDebug() << "EXECUTING CALLBACK " << cmd.callbackName
//        //    << " RESPONSE: " << response.data;
//        cmd.callback(response);
//    } else {
//        qDebug() << "NO CALLBACK FOR RESPONSE: " << response.logStreamOutput;
//    }
hjk's avatar
hjk committed
703
}
704
/*
hjk's avatar
hjk committed
705 706 707 708 709 710 711 712 713 714 715 716
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);
    }
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
}
*/

void PdbEngine::refreshLocals(const GdbMi &vars)
{
    //const bool partial = response.cookie.toBool();
    WatchHandler *handler = watchHandler();
    handler->resetValueCache();

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

    foreach (const GdbMi &child, vars.children()) {
        WatchItem *item = new WatchItem(child);
        handler->insertItem(item);
        toDelete.remove(item->d.iname);
    }

    handler->purgeOutdatedItems(toDelete);

    DebuggerToolTipManager::updateEngine(this);
}

void PdbEngine::refreshStack(const GdbMi &stack)
{
    StackHandler *handler = stackHandler();
    StackFrames frames;
    foreach (const GdbMi &item, stack["frames"].children()) {
        StackFrame frame;
        frame.level = item["level"].toInt();
        frame.file = item["file"].toUtf8();
        frame.function = item["func"].toUtf8();
        frame.from = item["func"].toUtf8();
        frame.line = item["line"].toInt();
        frame.address = item["addr"].toAddress();
        GdbMi usable = item["usable"];
        if (usable.isValid())
            frame.usable = usable.data().toInt();
        else
            frame.usable = QFileInfo(frame.file).isReadable();
        if (item["language"].data() == "js"
                || frame.file.endsWith(QLatin1String(".js"))
                || frame.file.endsWith(QLatin1String(".qml"))) {
            frame.language = QmlLanguage;
            frame.fixQmlFrame(startParameters());
hjk's avatar
hjk committed
763
        }
764
        frames.append(frame);
hjk's avatar
hjk committed
765
    }
766 767 768 769 770 771 772 773
    bool canExpand = stack["hasmore"].toInt();
    //action(ExpandStack)->setEnabled(canExpand);
    handler->setFrames(frames, canExpand);

    int index = stackHandler()->firstUsableIndex();
    handler->setCurrentIndex(index);
    if (index >= 0 && index < handler->stackSize())
        gotoLocation(handler->frameAt(index));
hjk's avatar
hjk committed
774 775
}

776
void PdbEngine::handleFirstCommand(const DebuggerResponse &response)
hjk's avatar
hjk committed
777 778 779 780
{
    Q_UNUSED(response);
}

781
void PdbEngine::handleUpdateAll(const DebuggerResponse &response)
hjk's avatar
hjk committed
782 783
{
    Q_UNUSED(response);
784
    notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
785 786 787 788
    updateAll();
}

void PdbEngine::updateAll()
789
{
790 791 792
    postCommand("dir()");
    postCommand("theDumper.stackListFrames({})");
    updateLocals();
793 794 795
}

void PdbEngine::updateLocals()
hjk's avatar
hjk committed
796
{
797 798 799
    DebuggerCommand cmd("updateData");
    cmd.arg("nativeMixed", isNativeMixedActive());
    watchHandler()->appendFormatRequests(&cmd);
hjk's avatar
hjk committed
800

801 802 803 804 805 806 807 808 809
    const static bool alwaysVerbose = !qgetenv("QTC_DEBUGGER_PYTHON_VERBOSE").isEmpty();
    cmd.arg("passexceptions", alwaysVerbose);
    cmd.arg("fancy", boolSetting(UseDebuggingHelpers));
//    cmd.arg("partial", params.tryPartial);

    cmd.beginList("watchers");

    // Watchers
    QHashIterator<QByteArray, int> it(WatchHandler::watcherNames());
hjk's avatar
hjk committed
810 811
    while (it.hasNext()) {
        it.next();
812 813 814 815
        cmd.beginGroup();
        cmd.arg("iname", "watch." + QByteArray::number(it.value()));
        cmd.arg("exp", it.key().toHex());
        cmd.endGroup();
hjk's avatar
hjk committed
816 817
    }

818 819 820 821 822 823 824
    // Tooltips
    DebuggerToolTipContexts toolTips = DebuggerToolTipManager::pendingTooltips(this);
    foreach (const DebuggerToolTipContext &p, toolTips) {
        cmd.beginGroup();
        cmd.arg("iname", p.iname);
        cmd.arg("exp", p.expression.toLatin1().toHex());
        cmd.endGroup();
hjk's avatar
hjk committed
825
    }
826

827 828 829 830 831 832 833
    cmd.endList();

    //cmd.arg("resultvarname", m_resultVarName);
    //m_lastDebuggableCommand = cmd;
    //m_lastDebuggableCommand.args.replace("\"passexceptions\":0", "\"passexceptions\":1");

    runCommand(cmd);
hjk's avatar
hjk committed
834 835
}

836
void PdbEngine::handleListLocals(const DebuggerResponse &response)
hjk's avatar
hjk committed
837 838
{
    //qDebug() << " LOCALS: '" << response.data << "'";
839
    QByteArray out = response.logStreamOutput.trimmed();
hjk's avatar
hjk committed
840 841 842 843 844 845

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

    //GdbMi data = all.findChild("data");
846
    WatchHandler *handler = watchHandler();
847 848 849 850 851

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

hjk's avatar
hjk committed
852
    foreach (const GdbMi &child, all.children()) {
hjk's avatar
hjk committed
853
        WatchItem *item = new WatchItem(child);
854 855
        handler->insertItem(item);
        toDelete.remove(item->d.iname);
hjk's avatar
hjk committed
856
    }
857 858

    handler->purgeOutdatedItems(toDelete);
hjk's avatar
hjk committed
859 860
}

861
bool PdbEngine::hasCapability(unsigned cap) const
hjk's avatar
hjk committed
862
{
863
    return cap & (ReloadModuleCapability|BreakConditionCapability);
hjk's avatar
hjk committed
864 865
}

866
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
hjk's avatar
hjk committed
867
{
868
    return new PdbEngine(startParameters);
hjk's avatar
hjk committed
869 870 871 872
}

} // namespace Internal
} // namespace Debugger