tcfengine.cpp 15.7 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
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 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.
**
**************************************************************************/

#include "tcfengine.h"

32
#include "debuggerconstants.h"
hjk's avatar
hjk committed
33
#include "debuggerdialogs.h"
34 35 36
#include "debuggerstringutils.h"
#include "json.h"

hjk's avatar
hjk committed
37 38 39 40 41 42 43 44 45 46 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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
#include "breakhandler.h"
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"
#include <utils/qtcassert.h>

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

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

#include <QtNetwork/QTcpSocket>

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

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

//#define USE_CONGESTION_CONTROL

static QByteArray C(const QByteArray &ba1,
    const QByteArray &ba2 = QByteArray(),
    const QByteArray &ba3 = QByteArray(),
    const QByteArray &ba4 = QByteArray(),
    const QByteArray &ba5 = QByteArray())
{
    QByteArray result = ba1;
    if (!ba2.isEmpty()) { result += '\0'; result += ba2; }
    if (!ba3.isEmpty()) { result += '\0'; result += ba3; }
    if (!ba4.isEmpty()) { result += '\0'; result += ba4; }
    if (!ba5.isEmpty()) { result += '\0'; result += ba5; }
    return result;
}

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// TcfCommand
//
///////////////////////////////////////////////////////////////////////


QString TcfEngine::TcfCommand::toString() const
{
    return quoteUnprintableLatin1(command);
}


///////////////////////////////////////////////////////////////////////
//
// TcfEngine
//
///////////////////////////////////////////////////////////////////////

107 108
TcfEngine::TcfEngine(const DebuggerStartParameters &startParameters)
    : DebuggerEngine(startParameters)
hjk's avatar
hjk committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
{
    m_congestion = 0;
    m_inAir = 0;

    m_sendTimer.setSingleShot(true);
    m_sendTimer.setInterval(100); // ms
    connect(&m_sendTimer, SIGNAL(timeout()), this, SLOT(handleSendTimer()));

    m_socket = new QTcpSocket(this);
    connect(m_socket, SIGNAL(connected()), this, SLOT(socketConnected()));
    connect(m_socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),
        this, SLOT(socketError(QAbstractSocket::SocketError)));

    //void aboutToClose ()
    //void bytesWritten ( qint64 bytes )
    //void readChannelFinished ()
    connect(m_socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));

    //connect(m_socket, SIGNAL(hostFound())
    //connect(m_socket, SIGNAL(proxyAuthenticationRequired(QNetworkProxy, QAuthenticator *)))
    //connect(m_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
    //    thism SLOT(socketStateChanged(QAbstractSocket::SocketState)));
}

TcfEngine::~TcfEngine()
{
}

void TcfEngine::socketReadyRead()
{
    //XSDEBUG("TcfEngine::socketReadyRead()");
    m_inbuffer.append(m_socket->readAll());
    int pos = 0;
    while (1) {
        // the  "\3" is followed by either "\1" or "\2"
        int next = m_inbuffer.indexOf("\3", pos);
        //qDebug() << "pos: " << pos << "next: " << next;
        if (next == -1)
            break;
        handleResponse(m_inbuffer.mid(pos, next - pos));
        pos = next + 2; 
    }
    m_inbuffer.clear();
}

void TcfEngine::socketConnected()
{
    showStatusMessage("Socket connected.");
    m_socket->waitForConnected(2000);
    //sendCommand("Locator", "redirect", "ID");
}

void TcfEngine::socketDisconnected()
{
    XSDEBUG("FIXME:  TcfEngine::socketDisconnected()");
}

void TcfEngine::socketError(QAbstractSocket::SocketError)
{
    QString msg = tr("%1.").arg(m_socket->errorString());
    //QMessageBox::critical(q->mainWindow(), tr("Error"), msg);
    showStatusMessage(msg);
172
    exitDebugger();
hjk's avatar
hjk committed
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
}

void TcfEngine::executeDebuggerCommand(const QString &command)
{
    QByteArray cmd = command.toUtf8();
    cmd = cmd.mid(cmd.indexOf(' ') + 1);
    QByteArray null;
    null.append('\0');
    // FIXME: works for single-digit escapes only
    cmd.replace("\\0", null);
    cmd.replace("\\1", "\1");
    cmd.replace("\\3", "\3");
    TcfCommand tcf;
    tcf.command = cmd;
    enqueueCommand(tcf);
}

void TcfEngine::shutdown()
{
    m_congestion = 0;
    m_inAir = 0;
    m_services.clear();
    exitDebugger(); 
}

void TcfEngine::exitDebugger()
{
    SDEBUG("TcfEngine::exitDebugger()");
}

203
void TcfEngine::startEngine()
hjk's avatar
hjk committed
204
{
205
    QTC_ASSERT(state() == EngineStarting, qDebug() << state());
hjk's avatar
hjk committed
206 207
    setState(InferiorRunningRequested);
    showStatusMessage(tr("Running requested..."), 5000);
208
    const DebuggerStartParameters &sp = startParameters();
209 210 211
    const int pos = sp.remoteChannel.indexOf(QLatin1Char(':'));
    const QString host = sp.remoteChannel.left(pos);
    const quint16 port = sp.remoteChannel.mid(pos + 1).toInt();
hjk's avatar
hjk committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
    //QTimer::singleShot(0, this, SLOT(runInferior()));
    m_socket->connectToHost(host, port);
    emit startSuccessful();
}

void TcfEngine::continueInferior()
{
    SDEBUG("TcfEngine::continueInferior()");
}

void TcfEngine::runInferior()
{
}

void TcfEngine::interruptInferior()
{
    XSDEBUG("TcfEngine::interruptInferior()");
}

void TcfEngine::executeStep()
{
    //SDEBUG("TcfEngine::executeStep()");
}

void TcfEngine::executeStepI()
{
    //SDEBUG("TcfEngine::executeStepI()");
}

void TcfEngine::executeStepOut()
{
    //SDEBUG("TcfEngine::executeStepOut()");
}

void TcfEngine::executeNext()
{
    //SDEBUG("TcfEngine::nextExec()");
}

void TcfEngine::executeNextI()
{
    //SDEBUG("TcfEngine::executeNextI()");
}

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

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

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

void TcfEngine::activateFrame(int index)
{
    Q_UNUSED(index)
}

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

void TcfEngine::attemptBreakpointSynchronization()
{
}

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

void TcfEngine::loadAllSymbols()
{
}

void TcfEngine::reloadModules()
{
}

void TcfEngine::requestModuleSymbols(const QString &moduleName)
{
    Q_UNUSED(moduleName)
}


void TcfEngine::handleResponse(const QByteArray &response)
{
    static QTime lastTime;

313
    //showMessage(_("            "), currentTime(), LogTime);
hjk's avatar
hjk committed
314 315 316 317 318 319 320 321 322 323 324 325 326 327
    QList<QByteArray> parts = response.split('\0');
    if (parts.size() < 2 || !parts.last().isEmpty()) {
        SDEBUG("WRONG RESPONSE PACKET LAYOUT" << parts);
        //if (response.isEmpty())
            acknowledgeResult();
        return;
    }
    parts.removeLast(); // always empty
    QByteArray tag = parts.at(0);
    int n = parts.size();
    if (n == 2 && tag == "N") { // unidentified command
        int token = parts.at(1).toInt();
        TcfCommand tcf = m_cookieForToken[token];
        SDEBUG("COMMAND NOT RECOGNIZED FOR TOKEN" << token << tcf.toString());
328
        showMessage(QString::number(token) + "^"
329 330
               + "NOT RECOQNIZED: " + quoteUnprintableLatin1(response),
                LogOutput);
hjk's avatar
hjk committed
331 332 333 334 335 336 337 338 339
        acknowledgeResult();
    } else if (n == 2 && tag == "F") { // flow control
        m_congestion = parts.at(1).toInt();
        SDEBUG("CONGESTION: " << m_congestion);
    } else if (n == 4 && tag == "R") { // result data
        acknowledgeResult();
        int token = parts.at(1).toInt();
        QByteArray message = parts.at(2);
        JsonValue data(parts.at(3));
340
        showMessage(QString("%1^%2%3").arg(token)
hjk's avatar
hjk committed
341
            .arg(quoteUnprintableLatin1(response))
342
            .arg(QString::fromUtf8(data.toString())), LogOutput);
hjk's avatar
hjk committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
        TcfCommand tcf = m_cookieForToken[token];
        JsonValue result(data);
        SDEBUG("GOOD RESPONSE: " << quoteUnprintableLatin1(response));
        if (tcf.callback)
            (this->*(tcf.callback))(result, tcf.cookie);
    } else if (n == 3 && tag == "P") { // progress data (partial result)
        //int token = parts.at(1).toInt();
        QByteArray data = parts.at(2);
        SDEBUG(_("\nTCF PARTIAL:") << quoteUnprintableLatin1(response));
    } else if (n == 4 && tag == "E") { // an event
        QByteArray service = parts.at(1);
        QByteArray eventName = parts.at(2);
        JsonValue data(parts.at(3));
        if (eventName != "peerHeartBeat")
            SDEBUG(_("\nTCF EVENT:") << quoteUnprintableLatin1(response)
                << data.toString());
        if (service == "Locator" && eventName == "Hello") {
            m_services.clear();
            foreach (const JsonValue &service, data.children())
                m_services.append(service.data());
            QTimer::singleShot(0, this, SLOT(startDebugging()));
        }
    } else {
        SDEBUG("UNKNOWN RESPONSE PACKET:"
            << quoteUnprintableLatin1(response) << parts);
    }
}

void TcfEngine::startDebugging()
{
    //foreach (const QByteArray &service, m_services) {
    //    postCommand(CB(handleRunControlGetChildren),
    //        service, "getChildren", "\"\"");
    //}

    postCommand(C("Diagnostics", "getChildren", "\"\""),
        CB(handleRunControlGetChildren));
    postCommand(C("Streams", "getChildren", "\"\""));
    postCommand(C("Expressions", "getChildren", "\"\""));
    postCommand(C("SysMonitor", "getChildren", "\"\""));
    //postCommand(C("FileSystem", "getChildren", "\"\""));
    //postCommand(C("Processes", "getChildren", "\"\""));
    //postCommand(CB(handleRunControlGetChildren), "LineNumbers", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "Symbols", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "StackTrace", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "Registers", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "Memory", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "Breakpoints", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "RunControl", "getChildren");
    //postCommand(CB(handleRunControlGetChildren), "Locator", "getChildren");


    //postCommand(CB(handleRunControlSuspend),
    //    "RunControl", "suspend", "\"Thread1\"");
    //postCommand(CB(handleRunControlSuspend),
    //    "RunControl", "getContext", "\"P12318\"");

    //postCommand(C("Locator", "sync"), CB(handleRunControlGetChildren));
    //postCommand("Locator", "redirect", "ID");

    //postCommand(C("FileSystem", "open", "\"/bin/ls\"", "1", "2", "3"),
    //    CB(handleRunControlGetChildren));
    postCommand(C("FileSystem", "stat", "\"/bin/ls\""),
        CB(handleRunControlGetChildren));
}

void TcfEngine::postCommand(const QByteArray &cmd,
    TcfCommandCallback callback, const char *callbackName)
{
    static int token = 20;
    ++token;
    
    //const char marker_eom = -1;
    //const char marker_eos = -2;
    //const char marker_null = -3;

    QByteArray ba = "C";
    ba.append('\0');
    ba.append(QByteArray::number(token));
    ba.append('\0');
    ba.append(cmd);
    ba.append('\0');
    ba.append('\3');
    ba.append('\1');

    TcfCommand tcf;
    tcf.command = ba;
    tcf.callback = callback;
    tcf.callbackName = callbackName;
    tcf.token = token;

    m_cookieForToken[token] = tcf;

    enqueueCommand(tcf);
}

// Congestion control does not seem to work that way. Basically it's
// already too late when we get a flow control packet
void TcfEngine::enqueueCommand(const TcfCommand &cmd)
{
#ifdef USE_CONGESTION_CONTROL
    // congestion controled
    if (m_congestion <= 0 && m_sendQueue.isEmpty()) {
        //SDEBUG("DIRECT SEND" << cmd.toString());
        sendCommandNow(cmd);
    } else {
        SDEBUG("QUEUE " << cmd.toString());
        m_sendQueue.enqueue(cmd);
        m_sendTimer.start();
    }
#else
    // synchrounously
    if (m_inAir == 0)
        sendCommandNow(cmd);
    else
        m_sendQueue.enqueue(cmd);
#endif
}

void TcfEngine::handleSendTimer()
{
    QTC_ASSERT(!m_sendQueue.isEmpty(), return);

    if (m_congestion > 0) {
        // not ready...
        SDEBUG("WAITING FOR CONGESTION TO GO DOWN...");
        m_sendTimer.start();
    } else {
        // go!
        sendCommandNow(m_sendQueue.dequeue());
    }
}

void TcfEngine::sendCommandNow(const TcfCommand &cmd)
{
    ++m_inAir;
    int result = m_socket->write(cmd.command);
    Q_UNUSED(result)
    m_socket->flush();
482
    showMessage(QString::number(cmd.token) + " " + cmd.toString(), LogInput);
hjk's avatar
hjk committed
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 515 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 555 556 557
    SDEBUG("SEND " <<  cmd.toString()); //<< " " << QString::number(result));
}

void TcfEngine::acknowledgeResult()
{
#if !defined(USE_CONGESTION_CONTROL)
    QTC_ASSERT(m_inAir == 1, /**/);
    m_inAir = 0;
    if (!m_sendQueue.isEmpty())
        sendCommandNow(m_sendQueue.dequeue());
#endif
}

void TcfEngine::handleRunControlSuspend(const JsonValue &data, const QVariant &)
{
    SDEBUG("HANDLE RESULT" << data.toString());
}

void TcfEngine::handleRunControlGetChildren(const JsonValue &data, const QVariant &)
{
    SDEBUG("HANDLE RUN CONTROL GET CHILDREN" << data.toString());
}

void TcfEngine::handleSysMonitorGetChildren(const JsonValue &data, const QVariant &)
{
    SDEBUG("HANDLE RUN CONTROL GET CHILDREN" << data.toString());
}


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

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

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

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

void TcfEngine::assignValueInDebugger(const QString &expression,
    const QString &value)
{
    XSDEBUG("ASSIGNING: " << expression + '=' + value);
    updateLocals();
}

void TcfEngine::updateLocals()
{
}

void TcfEngine::updateWatchData(const WatchData &)
{
    //qq->watchHandler()->rebuildModel();
    showStatusMessage(tr("Stopped."), 5000);
}

void TcfEngine::updateSubItem(const WatchData &data0)
{
    Q_UNUSED(data0)
    QTC_ASSERT(false, return);
}

558
DebuggerEngine *createTcfEngine(const DebuggerStartParameters &sp)
hjk's avatar
hjk committed
559
{
560
    return new TcfEngine(sp);
hjk's avatar
hjk committed
561 562 563 564
}

} // namespace Internal
} // namespace Debugger