pdbengine.cpp 25.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
hjk's avatar
hjk committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
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 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
hjk's avatar
hjk committed
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29 30 31

#include "pdbengine.h"

32 33 34 35 36 37 38 39
#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>
40

41 42 43 44 45 46 47
#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>
48

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

51
#include <texteditor/basetexteditor.h>
52
#include <coreplugin/idocument.h>
hjk's avatar
hjk committed
53 54
#include <coreplugin/icore.h>

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

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


#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
//
///////////////////////////////////////////////////////////////////////

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

PdbEngine::~PdbEngine()
{}

96
void PdbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
hjk's avatar
hjk committed
97
{
98 99
    if (!(languages & CppLanguage))
        return;
100 101
    QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
    //XSDEBUG("PdbEngine::executeDebuggerCommand:" << command);
hjk's avatar
hjk committed
102
    if (state() == DebuggerNotReady) {
103
        showMessage(_("PDB PROCESS NOT RUNNING, PLAIN CMD IGNORED: ") + command);
hjk's avatar
hjk committed
104 105
        return;
    }
106 107 108 109 110 111 112 113 114 115 116 117 118
    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
119
    m_pdbProc.write(command + '\n');
hjk's avatar
hjk committed
120 121 122 123 124 125 126 127
}

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

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

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

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

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

    connect(&m_pdbProc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(handlePdbError(QProcess::ProcessError)));
Robert Loehning's avatar
Robert Loehning committed
161 162
    connect(&m_pdbProc, SIGNAL(finished(int,QProcess::ExitStatus)),
        SLOT(handlePdbFinished(int,QProcess::ExitStatus)));
hjk's avatar
hjk committed
163 164 165 166 167
    connect(&m_pdbProc, SIGNAL(readyReadStandardOutput()),
        SLOT(readPdbStandardOutput()));
    connect(&m_pdbProc, SIGNAL(readyReadStandardError()),
        SLOT(readPdbStandardError()));

168 169 170
    connect(this, SIGNAL(outputReady(QByteArray)),
        SLOT(handleOutput2(QByteArray)), Qt::QueuedConnection);

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

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

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

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

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

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 216 217 218 219 220 221 222
    QString fileName = QFileInfo(startParameters().executable).absoluteFilePath();
    postDirectCommand("import sys");
    postDirectCommand("sys.argv.append('" + fileName.toLocal8Bit() + "')");
    postDirectCommand("execfile('/usr/bin/pdb')");
    postDirectCommand("execfile('" + dumperSourcePath + "pdumper.py')");
    attemptBreakpointSynchronization();
    notifyEngineRunAndInferiorStopOk();
    continueInferior();
hjk's avatar
hjk committed
223 224 225 226
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

329
bool PdbEngine::acceptsBreakpoint(BreakpointModelId id) const
hjk's avatar
hjk committed
330 331 332 333 334
{
    const QString fileName = breakHandler()->fileName(id);
    return fileName.endsWith(QLatin1String(".py"));
}

335
void PdbEngine::insertBreakpoint(BreakpointModelId id)
hjk's avatar
hjk committed
336
{
337
    BreakHandler *handler = breakHandler();
338
    QTC_CHECK(handler->state(id) == BreakpointInsertRequested);
hjk's avatar
hjk committed
339 340 341 342 343 344 345 346 347 348
    handler->notifyBreakpointInsertProceeding(id);

    QByteArray loc;
    if (handler->type(id) == BreakpointByFunction)
        loc = handler->functionName(id).toLatin1();
    else
        loc = handler->fileName(id).toLocal8Bit() + ':'
         + QByteArray::number(handler->lineNumber(id));

    postCommand("break " + loc, CB(handleBreakInsert), QVariant(id));
hjk's avatar
hjk committed
349 350 351 352 353 354
}

void PdbEngine::handleBreakInsert(const PdbResponse &response)
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
355
    BreakpointModelId id(response.cookie.toInt());
356
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
357 358 359 360
    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);
361
    int pos2 = response.data.lastIndexOf(':');
hjk's avatar
hjk committed
362 363
    QByteArray file = response.data.mid(pos1 + 4, pos2 - pos1 - 4);
    QByteArray line = response.data.mid(pos2 + 1);
hjk's avatar
hjk committed
364
    BreakpointResponse br;
365
    br.id = BreakpointResponseId(bpnr);
366 367
    br.fileName = _(file);
    br.lineNumber = line.toInt();
hjk's avatar
hjk committed
368
    handler->setResponse(id, br);
hjk's avatar
hjk committed
369 370
    QTC_CHECK(!handler->needsChange(id));
    handler->notifyBreakpointInsertOk(id);
hjk's avatar
hjk committed
371 372
}

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

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

void PdbEngine::loadAllSymbols()
{
}

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

void PdbEngine::handleListModules(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
404
    Modules modules;
hjk's avatar
hjk committed
405 406
    foreach (const GdbMi &item, out.children()) {
        Module module;
407 408
        module.moduleName = _(item["name"].data());
        QString path = _(item["value"].data());
hjk's avatar
hjk committed
409 410 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;
        modules.append(module);
    }
421
    modulesHandler()->setModules(modules);
hjk's avatar
hjk committed
422 423
}

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

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

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


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

455
bool PdbEngine::setToolTipExpression(TextEditor::BaseTextEditor *editor,
hjk's avatar
hjk committed
456
    const DebuggerToolTipContext &ctx)
hjk's avatar
hjk committed
457 458 459
{
    Q_UNUSED(editor)

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 465 466
    }
    // Check mime type and get expression (borrowing some C++ - functions)
    const QString javaPythonMimeType =
        QLatin1String("application/javascript");
467
    if (!editor->document() || editor->document()->mimeType() != javaPythonMimeType)
468
        return false;
hjk's avatar
hjk committed
469 470 471

    int line;
    int column;
472
    QString exp = cppExpressionAt(editor, ctx.position, &line, &column);
hjk's avatar
hjk committed
473 474 475 476 477 478 479 480 481 482 483 484 485

/*
    if (m_toolTipCache.contains(exp)) {
        const WatchData & data = m_toolTipCache[exp];
        q->watchHandler()->removeChildren(data.iname);
        insertData(data);
        return;
    }
*/

    QToolTip::hideText();
    if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')))  {
        QToolTip::hideText();
486
        return false;
hjk's avatar
hjk committed
487 488 489
    }

    if (!hasLetterOrNumber(exp)) {
490
        QToolTip::showText(m_toolTipPos, tr("\"%1\" contains no identifier").arg(exp));
491
        return true;
hjk's avatar
hjk committed
492 493 494 495
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
496
        return true;
hjk's avatar
hjk committed
497 498 499 500 501 502 503 504 505
    }

    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('[')))
506
        return false;
hjk's avatar
hjk committed
507 508 509

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
510
            tr("Cowardly refusing to evaluate expression \"%1\" "
hjk's avatar
hjk committed
511
               "with potential side effects").arg(exp));
512
        return true;
hjk's avatar
hjk committed
513 514 515
    }

#if 0
hjk's avatar
hjk committed
516
    //if (status() != InferiorStopOk)
hjk's avatar
hjk committed
517 518 519 520 521 522 523 524 525
    //    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
526
    return false;
hjk's avatar
hjk committed
527 528 529 530 531 532 533 534 535
}


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

536
void PdbEngine::assignValueInDebugger(const Internal::WatchData *, const QString &expression, const QVariant &value)
hjk's avatar
hjk committed
537 538 539
{
    Q_UNUSED(expression);
    Q_UNUSED(value);
540
    SDEBUG("ASSIGNING: " << (expression + QLatin1Char('=') + value.toString()));
hjk's avatar
hjk committed
541
#if 0
542
    m_scriptEngine->evaluate(expression + QLatin1Char('=') + value.toString());
hjk's avatar
hjk committed
543 544 545 546 547
    updateLocals();
#endif
}


548
void PdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
hjk's avatar
hjk committed
549 550
{
    Q_UNUSED(data);
hjk's avatar
hjk committed
551
    Q_UNUSED(flags);
hjk's avatar
hjk committed
552 553 554 555 556
    updateAll();
}

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
557
    qDebug() << "HANDLE PDB ERROR";
558
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
559 560 561 562 563 564 565 566
    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:
567
        //setState(EngineShutdownRequested, true);
hjk's avatar
hjk committed
568
        m_pdbProc.kill();
569
        showMessageBox(QMessageBox::Critical, tr("Pdb I/O Error"),
hjk's avatar
hjk committed
570 571 572 573 574 575 576 577 578 579
                       errorMessage(error));
        break;
    }
}

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

void PdbEngine::handlePdbFinished(int code, QProcess::ExitStatus type)
{
604
    qDebug() << "PDB FINISHED";
605
    showMessage(_("PDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
606
    notifyEngineSpontaneousShutdown();
hjk's avatar
hjk committed
607 608 609 610 611
}

void PdbEngine::readPdbStandardError()
{
    QByteArray err = m_pdbProc.readAllStandardError();
612 613 614 615
    qDebug() << "\nPDB STDERR" << err;
    //qWarning() << "Unexpected pdb stderr:" << err;
    //showMessage(_("Unexpected pdb stderr: " + err));
    //handleOutput(err);
hjk's avatar
hjk committed
616 617 618 619
}

void PdbEngine::readPdbStandardOutput()
{
620 621 622 623 624 625 626 627 628
    QByteArray out = m_pdbProc.readAllStandardOutput();
    qDebug() << "\nPDB STDOUT" << out;
    handleOutput(out);
}

void PdbEngine::handleOutput(const QByteArray &data)
{
    //qDebug() << "READ: " << data;
    m_inbuffer.append(data);
629
    qDebug() << "BUFFER FROM: '" << m_inbuffer << '\'';
630 631 632 633 634 635 636
    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
637
        m_inbuffer = m_inbuffer.mid(pos + 6);
638 639
        emit outputReady(response);
    }
640
    qDebug() << "BUFFER LEFT: '" << m_inbuffer << '\'';
641 642 643 644 645 646 647 648 649
    //m_inbuffer.clear();
}


void PdbEngine::handleOutput2(const QByteArray &data)
{
    PdbResponse response;
    response.data = data;
    showMessage(_(data));
650
    QTC_ASSERT(!m_commands.isEmpty(), qDebug() << "RESPONSE: " << data; return);
651 652 653 654 655 656 657 658 659
    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
660 661
    }
}
662
/*
hjk's avatar
hjk committed
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
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);
681
            qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
682 683 684 685 686
                << response.mid(pos1 + 1, pos2 - pos1 - 1);
            StackFrame frame;
            frame.file = _(fileName);
            frame.line = lineNumber;
            if (frame.line > 0 && QFileInfo(frame.file).exists()) {
687
                gotoLocation(frame);
688
                notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
689 690 691 692 693 694
                return;
            }
        }
    }
    qDebug() << "COULD NOT PARSE RESPONSE: '" << response << "'";
}
695
*/
hjk's avatar
hjk committed
696

hjk's avatar
hjk committed
697 698 699 700 701
void PdbEngine::handleFirstCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

hjk's avatar
hjk committed
702 703 704
void PdbEngine::handleUpdateAll(const PdbResponse &response)
{
    Q_UNUSED(response);
705
    notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
706 707 708 709
    updateAll();
}

void PdbEngine::updateAll()
710 711 712 713 714 715
{
    postCommand("bt", CB(handleBacktrace));
    //updateLocals();
}

void PdbEngine::updateLocals()
hjk's avatar
hjk committed
716 717 718 719 720 721
{
    QByteArray watchers;
    //if (!m_toolTipExpression.isEmpty())
    //    watchers += m_toolTipExpression.toLatin1()
    //        + '#' + tooltipINameForExpression(m_toolTipExpression.toLatin1());

hjk's avatar
hjk committed
722
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
723 724 725 726 727 728
    QHash<QByteArray, int> watcherNames = handler->watcherNames();
    QHashIterator<QByteArray, int> it(watcherNames);
    while (it.hasNext()) {
        it.next();
        if (!watchers.isEmpty())
            watchers += "##";
729
        watchers += it.key() + "#watch." + QByteArray::number(it.value());
hjk's avatar
hjk committed
730 731 732
    }

    QByteArray options;
hjk's avatar
hjk committed
733
    if (debuggerCore()->boolSetting(UseDebuggingHelpers))
hjk's avatar
hjk committed
734
        options += "fancy,";
hjk's avatar
hjk committed
735
    if (debuggerCore()->boolSetting(AutoDerefPointers))
hjk's avatar
hjk committed
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 763
        options += "autoderef,";
    if (options.isEmpty())
        options += "defaults,";
    options.chop(1);

    postCommand("qdebug('" + options + "','"
        + handler->expansionRequests() + "','"
        + 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.
764
    StackFrames stackFrames;
hjk's avatar
hjk committed
765 766 767 768 769 770 771 772 773 774
    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);
775
                //qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
776 777 778 779 780
                //    << 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
781
                frame.usable = QFileInfo(frame.file).isReadable();
hjk's avatar
hjk committed
782 783 784 785 786 787 788 789 790 791 792
                if (frame.line > 0 && QFileInfo(frame.file).exists()) {
                    if (line.startsWith("> "))
                        currentIndex = level;
                    frame.level = level;
                    stackFrames.prepend(frame);
                    ++level;
                }
            }
        }
    }
    const int frameCount = stackFrames.size();
793 794
    for (int i = 0; i != frameCount; ++i)
        stackFrames[i].level = frameCount - stackFrames[i].level - 1;
795
    stackHandler()->setFrames(stackFrames);
hjk's avatar
hjk committed
796 797 798 799

    // Select current frame.
    if (currentIndex != -1) {
        currentIndex = frameCount - currentIndex - 1;
800
        stackHandler()->setCurrentIndex(currentIndex);
801
        gotoLocation(stackFrames.at(currentIndex));
hjk's avatar
hjk committed
802
    }
803 804

    updateLocals();
hjk's avatar
hjk committed
805 806 807 808 809 810 811 812 813 814 815 816 817
}

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");
    QList<WatchData> list;
818
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
819 820
    foreach (const GdbMi &child, all.children()) {
        WatchData dummy;
821 822
        dummy.iname = child["iname"].data();
        dummy.name = _(child["name"].data());
hjk's avatar
hjk committed
823
        //qDebug() << "CHILD: " << child.toString();
824
        parseWatchData(handler->expandedINames(), dummy, child, &list);
hjk's avatar
hjk committed
825
    }
hjk's avatar
hjk committed
826
    handler->insertData(list);
hjk's avatar
hjk committed
827 828
}

829
bool PdbEngine::hasCapability(unsigned cap) const
hjk's avatar
hjk committed
830
{
831
    return cap & (ReloadModuleCapability|BreakConditionCapability);
hjk's avatar
hjk committed
832 833
}

834
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
hjk's avatar
hjk committed
835
{
836
    return new PdbEngine(startParameters);
hjk's avatar
hjk committed
837 838 839 840 841
}


} // namespace Internal
} // namespace Debugger