pdbengine.cpp 25 KB
Newer Older
hjk's avatar
hjk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#define QT_NO_CAST_FROM_ASCII

#include "pdbengine.h"

#include "debuggeractions.h"
35
#include "debuggerconstants.h"
hjk's avatar
hjk committed
36
#include "debuggerdialogs.h"
37 38 39
#include "debuggerplugin.h"
#include "debuggerstringutils.h"

hjk's avatar
hjk committed
40 41 42 43 44 45
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"
46

hjk's avatar
hjk committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
#include "../gdb/gdbmi.h"

#include <utils/qtcassert.h>

#include <texteditor/itexteditor.h>
#include <coreplugin/ifile.h>
//#include <coreplugin/scriptmanager/scriptmanager.h>
#include <coreplugin/icore.h>

#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QTimer>
#include <QtCore/QVariant>

#include <QtGui/QApplication>
#include <QtGui/QToolTip>
#include <QtGui/QMessageBox>


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


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

namespace Debugger {
namespace Internal {

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

88 89
PdbEngine::PdbEngine(const DebuggerStartParameters &startParameters)
    : DebuggerEngine(startParameters)
hjk's avatar
hjk committed
90 91 92 93 94 95 96 97 98
{}

PdbEngine::~PdbEngine()
{}

void PdbEngine::executeDebuggerCommand(const QString &command)
{
    XSDEBUG("PdbEngine::executeDebuggerCommand:" << command);
    if (state() == DebuggerNotReady) {
99
        showMessage(_("PDB PROCESS NOT RUNNING, PLAIN CMD IGNORED: ") + command);
hjk's avatar
hjk committed
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
        return;
    }
    m_pdbProc.write(command.toLatin1() + "\n");
}

void PdbEngine::postCommand(const QByteArray &command,
//                 PdbCommandFlags flags,
                 PdbCommandCallback callback,
                 const char *callbackName,
                 const QVariant &cookie)
{
    PdbCommand cmd;
    cmd.command = command;
    cmd.callback = callback;
    cmd.callbackName = callbackName;
    cmd.cookie = cookie;
    m_commands.enqueue(cmd);
117
    showMessage(_(cmd.command), LogInput);
hjk's avatar
hjk committed
118 119 120
    m_pdbProc.write(cmd.command + "\n");
}

hjk's avatar
hjk committed
121
void PdbEngine::shutdownInferior()
hjk's avatar
hjk committed
122
{
hjk's avatar
hjk committed
123 124
    QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
    notifyInferiorShutdownOk();
hjk's avatar
hjk committed
125 126
}

hjk's avatar
hjk committed
127
void PdbEngine::shutdownEngine()
hjk's avatar
hjk committed
128
{
hjk's avatar
hjk committed
129 130
    QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
    SDEBUG("PdbEngine::shutdownEngine()");
hjk's avatar
hjk committed
131 132 133 134
    m_pdbProc.kill();
    //if (m_scriptEngine->isEvaluating())
    //    m_scriptEngine->abortEvaluation();
    //m_scriptEngine->setAgent(0);
hjk's avatar
hjk committed
135
    notifyEngineShutdownOk();
hjk's avatar
hjk committed
136 137
}

hjk's avatar
hjk committed
138
void PdbEngine::setupEngine()
hjk's avatar
hjk committed
139
{
hjk's avatar
hjk committed
140
    QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
hjk's avatar
hjk committed
141

142
    m_scriptFileName = QFileInfo(startParameters().executable).absoluteFilePath();
hjk's avatar
hjk committed
143 144
    QFile scriptFile(m_scriptFileName);
    if (!scriptFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
145 146
        //showMessage("STARTING " +m_scriptFileName + "FAILED");
        showMessage(QString::fromLatin1("Cannot open %1: %2").
147
                   arg(m_scriptFileName, scriptFile.errorString()), LogError);
148
        notifyEngineSetupFailed();
hjk's avatar
hjk committed
149 150 151 152 153
        return;
    }
    m_pdbProc.disconnect(); // From any previous runs

    m_pdb = _("/usr/bin/python");
154
    showMessage(_("STARTING PDB ") + m_pdb);
hjk's avatar
hjk committed
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    QStringList gdbArgs;
    gdbArgs += _("-i");
    gdbArgs += _("/usr/bin/pdb");
    gdbArgs += m_scriptFileName;
    //gdbArgs += args;

    connect(&m_pdbProc, SIGNAL(error(QProcess::ProcessError)),
        SLOT(handlePdbError(QProcess::ProcessError)));
    connect(&m_pdbProc, SIGNAL(finished(int, QProcess::ExitStatus)),
        SLOT(handlePdbFinished(int, QProcess::ExitStatus)));
    connect(&m_pdbProc, SIGNAL(readyReadStandardOutput()),
        SLOT(readPdbStandardOutput()));
    connect(&m_pdbProc, SIGNAL(readyReadStandardError()),
        SLOT(readPdbStandardError()));

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

    m_pdbProc.start(m_pdb, gdbArgs);
hjk's avatar
hjk committed
176
    //qDebug() << "STARTING:" << m_pdb << gdbArgs;
hjk's avatar
hjk committed
177 178 179 180

    if (!m_pdbProc.waitForStarted()) {
        const QString msg = tr("Unable to start pdb '%1': %2")
            .arg(m_pdb, m_pdbProc.errorString());
181
        setState(EngineSetupFailed);
182
        showMessage(_("ADAPTER START FAILED"));
hjk's avatar
hjk committed
183 184 185 186
        if (!msg.isEmpty()) {
            const QString title = tr("Adapter start failed");
            Core::ICore::instance()->showWarningWithOptions(title, msg);
        }
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
    attemptBreakpointSynchronization();

198
    showMessage(_("PDB STARTED, INITIALIZING IT"));
hjk's avatar
hjk committed
199 200 201 202 203 204
    const QByteArray dumperSourcePath =
        Core::ICore::instance()->resourcePath().toLocal8Bit() + "/gdbmacros/";
    postCommand("execfile('" + dumperSourcePath + "pdumper.py')",
        CB(handleLoadDumper));
}

hjk's avatar
hjk committed
205
void PdbEngine::runEngine()
hjk's avatar
hjk committed
206
{
hjk's avatar
hjk committed
207 208 209
    showStatusMessage(tr("Running requested..."), 5000);
    SDEBUG("PdbEngine::runEngine()");
    continueInferior();
hjk's avatar
hjk committed
210 211 212 213
}

void PdbEngine::interruptInferior()
{
hjk's avatar
hjk committed
214
    setState(InferiorStopOk);
hjk's avatar
hjk committed
215 216 217 218
}

void PdbEngine::executeStep()
{
219
    resetLocation();
hjk's avatar
hjk committed
220 221
    setState(InferiorRunRequested);
    setState(InferiorRunOk);
hjk's avatar
hjk committed
222 223 224 225 226
    postCommand("step", CB(handleUpdateAll));
}

void PdbEngine::executeStepI()
{
227
    resetLocation();
hjk's avatar
hjk committed
228 229
    setState(InferiorRunRequested);
    setState(InferiorRunOk);
hjk's avatar
hjk committed
230 231 232 233 234
    postCommand("step", CB(handleUpdateAll));
}

void PdbEngine::executeStepOut()
{
235
    resetLocation();
hjk's avatar
hjk committed
236 237
    setState(InferiorRunRequested);
    setState(InferiorRunOk);
hjk's avatar
hjk committed
238 239 240 241 242
    postCommand("finish", CB(handleUpdateAll));
}

void PdbEngine::executeNext()
{
243
    resetLocation();
hjk's avatar
hjk committed
244 245
    setState(InferiorRunRequested);
    setState(InferiorRunOk);
hjk's avatar
hjk committed
246 247 248 249 250
    postCommand("next", CB(handleUpdateAll));
}

void PdbEngine::executeNextI()
{
251
    resetLocation();
hjk's avatar
hjk committed
252 253
    setState(InferiorRunRequested);
    setState(InferiorRunOk);
hjk's avatar
hjk committed
254 255 256 257 258
    postCommand("next", CB(handleUpdateAll));
}

void PdbEngine::continueInferior()
{
259
    resetLocation();
hjk's avatar
hjk committed
260 261
    setState(InferiorRunRequested);
    setState(InferiorRunOk);
hjk's avatar
hjk committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
    // Callback will be triggered e.g. when breakpoint is hit.
    postCommand("continue", CB(handleUpdateAll));
}

void PdbEngine::executeRunToLine(const QString &fileName, int lineNumber)
{
    Q_UNUSED(fileName)
    Q_UNUSED(lineNumber)
    SDEBUG("FIXME:  PdbEngine::runToLineExec()");
}

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

void PdbEngine::executeJumpToLine(const QString &fileName, int lineNumber)
{
    Q_UNUSED(fileName)
    Q_UNUSED(lineNumber)
    XSDEBUG("FIXME:  PdbEngine::jumpToLineExec()");
}

void PdbEngine::activateFrame(int frameIndex)
{
288
    resetLocation();
hjk's avatar
hjk committed
289
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
hjk's avatar
hjk committed
290 291
        return;

292 293
    StackHandler *handler = stackHandler();
    int oldIndex = handler->currentIndex();
hjk's avatar
hjk committed
294

295
    //if (frameIndex == handler->stackSize()) {
hjk's avatar
hjk committed
296 297 298 299
    //    reloadFullStack();
    //    return;
    //}

300
    QTC_ASSERT(frameIndex < handler->stackSize(), return);
hjk's avatar
hjk committed
301 302 303 304 305

    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.
306
        handler->setCurrentIndex(frameIndex);
hjk's avatar
hjk committed
307 308 309
        //postCommand("-stack-select-frame " + QByteArray::number(frameIndex),
        //    CB(handleStackSelectFrame));
    }
310
    gotoLocation(handler->currentFrame(), true);
hjk's avatar
hjk committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
}

void PdbEngine::selectThread(int index)
{
    Q_UNUSED(index)
}

static QByteArray breakpointLocation(const BreakpointData *data)
{
    if (!data->funcName.isEmpty())
        return data->funcName.toLatin1();
    // In this case, data->funcName is something like '*0xdeadbeef'
    if (data->lineNumber.toInt() == 0)
        return data->funcName.toLatin1();
    //QString loc = data->useFullPath ? data->fileName : breakLocation(data->fileName);
    // The argument is simply a C-quoted version of the argument to the
    // non-MI "break" command, including the "original" quoting it wants.
    //return "\"\\\"" + GdbMi::escapeCString(data->fileName).toLocal8Bit() + "\\\":"
    //    + data->lineNumber + '"';
    return data->fileName.toLocal8Bit() + ":" + data->lineNumber;
}

void PdbEngine::attemptBreakpointSynchronization()
{
335
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    //qDebug() << "ATTEMPT BP SYNC";
    bool updateNeeded = false;
    for (int index = 0; index != handler->size(); ++index) {
        BreakpointData *data = handler->at(index);
        if (data->pending) {
            data->pending = false; // FIXME
            updateNeeded = true;
            QByteArray loc = breakpointLocation(data);
            postCommand("break " + loc, CB(handleBreakInsert), QVariant(index));
        }
/*
        if (data->bpNumber.isEmpty()) {
            data->bpNumber = QByteArray::number(index + 1);
            updateNeeded = true;
        }
        if (!data->fileName.isEmpty() && data->markerFileName().isEmpty()) {
            data->setMarkerFileName(data->fileName);
            data->setMarkerLineNumber(data->lineNumber.toInt());
            updateNeeded = true;
        }
*/
    }
    //if (updateNeeded)
    //    handler->updateMarkers();
}

void PdbEngine::handleBreakInsert(const PdbResponse &response)
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
    int index = response.cookie.toInt();
367
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
    BreakpointData *data = handler->at(index);
    QTC_ASSERT(data, return);
    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);
    int pos2 = response.data.lastIndexOf(":");
    QByteArray file = response.data.mid(pos1 + 4, pos2 - pos1 - 4);
    QByteArray line = response.data.mid(pos2 + 1);
    data->bpNumber = bpnr;
    data->bpFileName = _(file);
    data->bpLineNumber = line;
    handler->updateMarkers();
}

void PdbEngine::loadSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}

void PdbEngine::loadAllSymbols()
{
}

void PdbEngine::reloadModules()
{
hjk's avatar
hjk committed
394 395 396 397 398 399 400
    postCommand("qdebug('listmodules')", CB(handleListModules));
}

void PdbEngine::handleListModules(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
401
    Modules modules;
hjk's avatar
hjk committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    foreach (const GdbMi &item, out.children()) {
        Module module;
        module.moduleName = _(item.findChild("name").data());
        QString path = _(item.findChild("value").data());
        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);
    }
418
    modulesHandler()->setModules(modules);
hjk's avatar
hjk committed
419 420
}

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

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

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


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

void PdbEngine::setToolTipExpression(const QPoint &mousePos,
    TextEditor::ITextEditor *editor, int cursorPos)
{
    Q_UNUSED(mousePos)
    Q_UNUSED(editor)
    Q_UNUSED(cursorPos)

hjk's avatar
hjk committed
459
    if (state() != InferiorStopOk) {
hjk's avatar
hjk committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        //SDEBUG("SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED");
        return;
    }
    // Check mime type and get expression (borrowing some C++ - functions)
    const QString javaPythonMimeType =
        QLatin1String("application/javascript");
    if (!editor->file() || editor->file()->mimeType() != javaPythonMimeType)
        return;

    int line;
    int column;
    QString exp = cppExpressionAt(editor, cursorPos, &line, &column);

/*
    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();
        return;
    }

    if (!hasLetterOrNumber(exp)) {
        QToolTip::showText(m_toolTipPos, tr("'%1' contains no identifier").arg(exp));
        return;
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
        return;
    }

    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('[')))
        return;

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
            tr("Cowardly refusing to evaluate expression '%1' "
               "with potential side effects").arg(exp));
        return;
    }

#if 0
hjk's avatar
hjk committed
515
    //if (status() != InferiorStopOk)
hjk's avatar
hjk committed
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    //    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
}


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

void PdbEngine::assignValueInDebugger(const QString &expression,
    const QString &value)
{
    Q_UNUSED(expression);
    Q_UNUSED(value);
    SDEBUG("ASSIGNING: " << (expression + QLatin1Char('=') + value));
#if 0
    m_scriptEngine->evaluate(expression + QLatin1Char('=') + value);
    updateLocals();
#endif
}


void PdbEngine::updateWatchData(const WatchData &data)
{
    Q_UNUSED(data);
    updateAll();
}

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
555
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
556 557 558 559 560 561 562 563 564
    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:
        m_pdbProc.kill();
hjk's avatar
hjk committed
565
        setState(EngineShutdownRequested, true);
566
        plugin()->showMessageBox(QMessageBox::Critical, tr("Pdb I/O Error"),
hjk's avatar
hjk committed
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
                       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 "
                "invoked program '%1' is missing, or you may have insufficient "
                "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:
            return tr("An unknown error in the Pdb process occurred. ");
    }
}

void PdbEngine::handlePdbFinished(int code, QProcess::ExitStatus type)
{
601
    showMessage(_("PDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
hjk's avatar
hjk committed
602 603 604 605 606 607 608 609 610
    //shutdown();
    //initializeVariables();
    setState(DebuggerNotReady, true);
}

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

void PdbEngine::readPdbStandardOutput()
{
    m_inbuffer.append(m_pdbProc.readAllStandardOutput());
    //qDebug() << "BUFFER FROM: '" << m_inbuffer << "'";
    int pos = 1;
    while ((pos = m_inbuffer.indexOf("(Pdb)")) != -1) {
        PdbResponse response;
        response.data = m_inbuffer.left(pos).trimmed();
622
        showMessage(_(response.data));
hjk's avatar
hjk committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 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
        m_inbuffer = m_inbuffer.mid(pos + 6);
        QTC_ASSERT(!m_commands.isEmpty(),
            qDebug() << "RESPONSE: " << response.data; return)
        PdbCommand cmd = m_commands.dequeue();
        response.cookie = cmd.cookie;
        if (cmd.callback) {
            //qDebug() << "EXECUTING CALLBACK " << cmd.callbackName
            //    << " RESPONSE: " << response.data;
            (this->*cmd.callback)(response);
        } else {
            qDebug() << "NO CALLBACK FOR RESPONSE: " << response.data;
        }
    }
    //qDebug() << "BUFFER LEFT: '" << m_inbuffer << "'";
}

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);
            qDebug() << " " << pos1 << pos2 << lineNumber << fileName 
                << response.mid(pos1 + 1, pos2 - pos1 - 1);
            StackFrame frame;
            frame.file = _(fileName);
            frame.line = lineNumber;
            if (frame.line > 0 && QFileInfo(frame.file).exists()) {
663
                gotoLocation(frame, true);
hjk's avatar
hjk committed
664 665
                setState(InferiorStopRequested);
                setState(InferiorStopOk);
hjk's avatar
hjk committed
666 667 668 669 670 671 672
                return;
            }
        }
    }
    qDebug() << "COULD NOT PARSE RESPONSE: '" << response << "'";
}

hjk's avatar
hjk committed
673 674 675 676 677
void PdbEngine::handleFirstCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

hjk's avatar
hjk committed
678 679 680
void PdbEngine::handleUpdateAll(const PdbResponse &response)
{
    Q_UNUSED(response);
hjk's avatar
hjk committed
681 682
    setState(InferiorStopRequested);
    setState(InferiorStopOk);
hjk's avatar
hjk committed
683 684 685 686 687
    updateAll();
}

void PdbEngine::updateAll()
{
688
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739

    QByteArray watchers;
    //if (!m_toolTipExpression.isEmpty())
    //    watchers += m_toolTipExpression.toLatin1()
    //        + '#' + tooltipINameForExpression(m_toolTipExpression.toLatin1());

    QHash<QByteArray, int> watcherNames = handler->watcherNames();
    QHashIterator<QByteArray, int> it(watcherNames);
    while (it.hasNext()) {
        it.next();
        if (!watchers.isEmpty())
            watchers += "##";
        if (it.key() == WatchHandler::watcherEditPlaceHolder().toLatin1())
            watchers += "<Edit>#watch." + QByteArray::number(it.value());
        else
            watchers += it.key() + "#watch." + QByteArray::number(it.value());
    }

    QByteArray options;
    if (theDebuggerBoolSetting(UseDebuggingHelpers))
        options += "fancy,";
    if (theDebuggerBoolSetting(AutoDerefPointers))
        options += "autoderef,";
    if (options.isEmpty())
        options += "defaults,";
    options.chop(1);

    postCommand("bt", CB(handleBacktrace));
    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.
740
    StackFrames stackFrames;
hjk's avatar
hjk committed
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
    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);
                //qDebug() << " " << pos1 << pos2 << lineNumber << fileName 
                //    << line.mid(pos1 + 1, pos2 - pos1 - 1);
                StackFrame frame;
                frame.file = _(fileName);
                frame.line = lineNumber;
                frame.function = _(line.mid(pos2 + 1));
                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();
    for (int i = 0; i != frameCount; ++i) 
        stackFrames[i].level = frameCount - stackFrames[i].level - 1; 
770
    stackHandler()->setFrames(stackFrames);
hjk's avatar
hjk committed
771 772 773 774

    // Select current frame.
    if (currentIndex != -1) {
        currentIndex = frameCount - currentIndex - 1;
775 776
        stackHandler()->setCurrentIndex(currentIndex);
        gotoLocation(stackFrames.at(currentIndex), true);
hjk's avatar
hjk committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790
    }
}

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;
791
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
792 793 794 795 796
    foreach (const GdbMi &child, all.children()) {
        WatchData dummy;
        dummy.iname = child.findChild("iname").data();
        dummy.name = _(child.findChild("name").data());
        //qDebug() << "CHILD: " << child.toString();
797
        parseWatchData(handler->expandedINames(), dummy, child, &list);
hjk's avatar
hjk committed
798
    }
799
    handler->insertBulkData(list);
hjk's avatar
hjk committed
800 801 802 803 804 805
}

void PdbEngine::handleLoadDumper(const PdbResponse &response)
{
    Q_UNUSED(response);
    //qDebug() << " DUMPERS LOADED '" << response.data << "'";
hjk's avatar
hjk committed
806 807
    //continueInferior();
    notifyInferiorSetupOk();
hjk's avatar
hjk committed
808 809
}

hjk's avatar
hjk committed
810 811 812 813 814
unsigned PdbEngine::debuggerCapabilities() const
{
    return ReloadModuleCapability;
}

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


} // namespace Internal
} // namespace Debugger