pdbengine.cpp 25.6 KB
Newer Older
hjk's avatar
hjk committed
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
hjk's avatar
hjk committed
6 7 8
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
con's avatar
con committed
9
** No Commercial Usage
hjk's avatar
hjk committed
10
**
con's avatar
con committed
11 12 13 14
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
hjk's avatar
hjk committed
15 16 17 18 19 20 21 22 23 24
**
** 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.
**
con's avatar
con committed
25 26 27 28 29 30
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
hjk's avatar
hjk committed
31 32 33 34 35 36 37
**
**************************************************************************/

#define QT_NO_CAST_FROM_ASCII

#include "pdbengine.h"

Friedemann Kleint's avatar
Friedemann Kleint committed
38
#include "debuggerstartparameters.h"
hjk's avatar
hjk committed
39
#include "debuggeractions.h"
hjk's avatar
hjk committed
40
#include "debuggercore.h"
hjk's avatar
hjk committed
41
#include "debuggerdialogs.h"
42 43
#include "debuggerplugin.h"
#include "debuggerstringutils.h"
44
#include "debuggertooltipmanager.h"
45

hjk's avatar
hjk committed
46 47 48 49 50 51
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"
52

hjk's avatar
hjk committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
#include "../gdb/gdbmi.h"

#include <utils/qtcassert.h>

#include <texteditor/itexteditor.h>
#include <coreplugin/ifile.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/QMessageBox>
70
#include <QtGui/QToolTip>
hjk's avatar
hjk committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92


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

93 94
PdbEngine::PdbEngine(const DebuggerStartParameters &startParameters)
    : DebuggerEngine(startParameters)
Friedemann Kleint's avatar
Friedemann Kleint committed
95 96 97
{
    setObjectName(QLatin1String("PdbEngine"));
}
hjk's avatar
hjk committed
98 99 100 101 102 103

PdbEngine::~PdbEngine()
{}

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

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

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

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

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

160
    m_pdb = _("python");
161
    showMessage(_("STARTING PDB ") + m_pdb);
hjk's avatar
hjk committed
162 163 164 165 166 167 168 169 170 171

    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()));

172 173 174
    connect(this, SIGNAL(outputReady(QByteArray)),
        SLOT(handleOutput2(QByteArray)), Qt::QueuedConnection);

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

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

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

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

201 202 203 204 205 206 207 208 209 210
    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
211 212
}

hjk's avatar
hjk committed
213
void PdbEngine::runEngine()
hjk's avatar
hjk committed
214
{
215
    QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
hjk's avatar
hjk committed
216
    showStatusMessage(tr("Running requested..."), 5000);
217 218 219 220 221 222 223 224 225 226
    const QByteArray dumperSourcePath =
        Core::ICore::instance()->resourcePath().toLocal8Bit() + "/gdbmacros/";
    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
227 228 229 230
}

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

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

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

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

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

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

void PdbEngine::continueInferior()
{
276
    resetLocation();
277 278
    notifyInferiorRunRequested();
    notifyInferiorRunOk();
hjk's avatar
hjk committed
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    // 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)
{
305
    resetLocation();
hjk's avatar
hjk committed
306
    if (state() != InferiorStopOk && state() != InferiorUnrunnable)
hjk's avatar
hjk committed
307 308
        return;

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

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

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

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

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

hjk's avatar
hjk committed
335 336 337 338 339 340 341
bool PdbEngine::acceptsBreakpoint(BreakpointId id) const
{
    const QString fileName = breakHandler()->fileName(id);
    return fileName.endsWith(QLatin1String(".py"));
}

void PdbEngine::insertBreakpoint(BreakpointId id)
hjk's avatar
hjk committed
342
{
343
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
344 345 346 347 348 349 350 351 352 353 354
    QTC_ASSERT(handler->state(id) == BreakpointInsertRequested, /**/);
    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
355 356 357 358 359 360
}

void PdbEngine::handleBreakInsert(const PdbResponse &response)
{
    //qDebug() << "BP RESPONSE: " << response.data;
    // "Breakpoint 1 at /pdb/math.py:10"
hjk's avatar
hjk committed
361
    BreakpointId id(response.cookie.toInt());
362
    BreakHandler *handler = breakHandler();
hjk's avatar
hjk committed
363 364 365 366 367 368 369
    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);
hjk's avatar
hjk committed
370
    BreakpointResponse br;
371 372 373
    br.number = bpnr.toInt();
    br.fileName = _(file);
    br.lineNumber = line.toInt();
hjk's avatar
hjk committed
374
    handler->setResponse(id, br);
hjk's avatar
hjk committed
375 376
}

hjk's avatar
hjk committed
377 378 379 380 381 382 383 384 385 386 387 388 389
void PdbEngine::removeBreakpoint(BreakpointId id)
{
    BreakHandler *handler = breakHandler();
    QTC_ASSERT(handler->state(id) == BreakpointRemoveRequested, /**/);
    handler->notifyBreakpointRemoveProceeding(id);
    BreakpointResponse br = handler->response(id);
    showMessage(_("DELETING BP %1 IN %2").arg(br.number)
        .arg(handler->fileName(id)));
    postCommand("clear " + QByteArray::number(br.number));
    // Pretend it succeeds without waiting for response.
    handler->notifyBreakpointRemoveOk(id);
}

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 405 406 407
}

void PdbEngine::handleListModules(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
408
    Modules modules;
hjk's avatar
hjk committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    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);
    }
425
    modulesHandler()->setModules(modules);
hjk's avatar
hjk committed
426 427
}

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

hjk's avatar
hjk committed
434 435 436 437
void PdbEngine::handleListSymbols(const PdbResponse &response)
{
    GdbMi out;
    out.fromString(response.data.trimmed());
438
    Symbols symbols;
hjk's avatar
hjk committed
439 440 441 442 443 444
    QString moduleName = response.cookie.toString();
    foreach (const GdbMi &item, out.children()) {
        Symbol symbol;
        symbol.name = _(item.findChild("name").data());
        symbols.append(symbol);
    }
hjk's avatar
hjk committed
445
   debuggerCore()->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 458

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


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

459
bool PdbEngine::setToolTipExpression(const QPoint &mousePos,
460
    TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
hjk's avatar
hjk committed
461 462 463 464
{
    Q_UNUSED(mousePos)
    Q_UNUSED(editor)

hjk's avatar
hjk committed
465
    if (state() != InferiorStopOk) {
hjk's avatar
hjk committed
466
        //SDEBUG("SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED");
467
        return false;
hjk's avatar
hjk committed
468 469 470 471 472
    }
    // Check mime type and get expression (borrowing some C++ - functions)
    const QString javaPythonMimeType =
        QLatin1String("application/javascript");
    if (!editor->file() || editor->file()->mimeType() != javaPythonMimeType)
473
        return false;
hjk's avatar
hjk committed
474 475 476

    int line;
    int column;
477
    QString exp = cppExpressionAt(editor, ctx.position, &line, &column);
hjk's avatar
hjk committed
478 479 480 481 482 483 484 485 486 487 488 489 490

/*
    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();
491
        return false;
hjk's avatar
hjk committed
492 493 494 495
    }

    if (!hasLetterOrNumber(exp)) {
        QToolTip::showText(m_toolTipPos, tr("'%1' contains no identifier").arg(exp));
496
        return true;
hjk's avatar
hjk committed
497 498 499 500
    }

    if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
        QToolTip::showText(m_toolTipPos, tr("String literal %1").arg(exp));
501
        return true;
hjk's avatar
hjk committed
502 503 504 505 506 507 508 509 510
    }

    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('[')))
511
        return false;
hjk's avatar
hjk committed
512 513 514 515 516

    if (hasSideEffects(exp)) {
        QToolTip::showText(m_toolTipPos,
            tr("Cowardly refusing to evaluate expression '%1' "
               "with potential side effects").arg(exp));
517
        return true;
hjk's avatar
hjk committed
518 519 520
    }

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


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

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


553
void PdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
hjk's avatar
hjk committed
554 555
{
    Q_UNUSED(data);
hjk's avatar
hjk committed
556
    Q_UNUSED(flags);
hjk's avatar
hjk committed
557 558 559 560 561
    updateAll();
}

void PdbEngine::handlePdbError(QProcess::ProcessError error)
{
562
    qDebug() << "HANDLE PDB ERROR";
563
    showMessage(_("HANDLE PDB ERROR"));
hjk's avatar
hjk committed
564 565 566 567 568 569 570 571
    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:
572
        //setState(EngineShutdownRequested, true);
hjk's avatar
hjk committed
573
        m_pdbProc.kill();
574
        showMessageBox(QMessageBox::Critical, tr("Pdb I/O Error"),
hjk's avatar
hjk committed
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 601 602 603 604 605 606 607 608
                       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)
{
609
    qDebug() << "PDB FINISHED";
610
    showMessage(_("PDB PROCESS FINISHED, status %1, code %2").arg(type).arg(code));
611
    notifyEngineSpontaneousShutdown();
hjk's avatar
hjk committed
612 613 614 615 616
}

void PdbEngine::readPdbStandardError()
{
    QByteArray err = m_pdbProc.readAllStandardError();
617 618 619 620
    qDebug() << "\nPDB STDERR" << err;
    //qWarning() << "Unexpected pdb stderr:" << err;
    //showMessage(_("Unexpected pdb stderr: " + err));
    //handleOutput(err);
hjk's avatar
hjk committed
621 622 623 624
}

void PdbEngine::readPdbStandardOutput()
{
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
    QByteArray out = m_pdbProc.readAllStandardOutput();
    qDebug() << "\nPDB STDOUT" << out;
    handleOutput(out);
}

void PdbEngine::handleOutput(const QByteArray &data)
{
    //qDebug() << "READ: " << data;
    m_inbuffer.append(data);
    qDebug() << "BUFFER FROM: '" << m_inbuffer << "'";
    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
642
        m_inbuffer = m_inbuffer.mid(pos + 6);
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
        emit outputReady(response);
    }
    qDebug() << "BUFFER LEFT: '" << m_inbuffer << "'";
    //m_inbuffer.clear();
}


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

hjk's avatar
hjk committed
702 703 704 705 706
void PdbEngine::handleFirstCommand(const PdbResponse &response)
{
    Q_UNUSED(response);
}

hjk's avatar
hjk committed
707 708 709
void PdbEngine::handleUpdateAll(const PdbResponse &response)
{
    Q_UNUSED(response);
710
    notifyInferiorSpontaneousStop();
hjk's avatar
hjk committed
711 712 713 714
    updateAll();
}

void PdbEngine::updateAll()
715 716 717 718 719 720
{
    postCommand("bt", CB(handleBacktrace));
    //updateLocals();
}

void PdbEngine::updateLocals()
hjk's avatar
hjk committed
721
{
722
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
723 724 725 726 727 728 729 730 731 732 733 734

    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 += "##";
735
        watchers += it.key() + "#watch." + QByteArray::number(it.value());
hjk's avatar
hjk committed
736 737 738
    }

    QByteArray options;
hjk's avatar
hjk committed
739
    if (debuggerCore()->boolSetting(UseDebuggingHelpers))
hjk's avatar
hjk committed
740
        options += "fancy,";
hjk's avatar
hjk committed
741
    if (debuggerCore()->boolSetting(AutoDerefPointers))
hjk's avatar
hjk committed
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
        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.
770
    StackFrames stackFrames;
hjk's avatar
hjk committed
771 772 773 774 775 776 777 778 779 780
    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);
781
                //qDebug() << " " << pos1 << pos2 << lineNumber << fileName
hjk's avatar
hjk committed
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
                //    << 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();
798 799
    for (int i = 0; i != frameCount; ++i)
        stackFrames[i].level = frameCount - stackFrames[i].level - 1;
800
    stackHandler()->setFrames(stackFrames);
hjk's avatar
hjk committed
801 802 803 804

    // Select current frame.
    if (currentIndex != -1) {
        currentIndex = frameCount - currentIndex - 1;
805
        stackHandler()->setCurrentIndex(currentIndex);
806
        gotoLocation(stackFrames.at(currentIndex));
hjk's avatar
hjk committed
807
    }
808 809

    updateLocals();
hjk's avatar
hjk committed
810 811 812 813 814 815 816 817 818 819 820 821 822
}

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;
823
    WatchHandler *handler = watchHandler();
hjk's avatar
hjk committed
824 825 826 827 828
    foreach (const GdbMi &child, all.children()) {
        WatchData dummy;
        dummy.iname = child.findChild("iname").data();
        dummy.name = _(child.findChild("name").data());
        //qDebug() << "CHILD: " << child.toString();
829
        parseWatchData(handler->expandedINames(), dummy, child, &list);
hjk's avatar
hjk committed
830
    }
831
    handler->insertBulkData(list);
hjk's avatar
hjk committed
832 833
}

hjk's avatar
hjk committed
834 835
unsigned PdbEngine::debuggerCapabilities() const
{
836
    return ReloadModuleCapability|BreakConditionCapability;
hjk's avatar
hjk committed
837 838
}

839
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
hjk's avatar
hjk committed
840
{
841
    return new PdbEngine(startParameters);
hjk's avatar
hjk committed
842 843 844 845 846
}


} // namespace Internal
} // namespace Debugger