trkgdbadapter.cpp 61.2 KB
Newer Older
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
/**************************************************************************
**
** 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.
**
**************************************************************************/

hjk's avatar
hjk committed
30
#include "trkgdbadapter.h"
31
#include "trkoptions.h"
32
#include "debuggerstringutils.h"
hjk's avatar
hjk committed
33
#ifndef STANDALONE_RUNNER
34
#include "gdbengine.h"
hjk's avatar
hjk committed
35
#endif
hjk's avatar
hjk committed
36
37
38
#ifdef Q_OS_WIN
#  include <windows.h>
#else
39
40
41
#  include <sys/types.h>
#  include <unistd.h>
#endif
42

hjk's avatar
hjk committed
43
44
#include <utils/qtcassert.h>

45
46
47
#include <QtCore/QTimer>
#include <QtCore/QDir>

hjk's avatar
hjk committed
48
49
50
51
52
53
#define STRINGIFY_INTERNAL(x) #x
#define STRINGIFY(x) STRINGIFY_INTERNAL(x)
#define CB(callback) \
    static_cast<GdbEngine::AdapterCallback>(&TrkGdbAdapter::callback), \
    STRINGIFY(callback)

hjk's avatar
hjk committed
54
#define TrkCB(s) TrkCallback(this, &TrkGdbAdapter::s)
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


using namespace trk;

enum { KnownRegisters = RegisterPSGdb + 1};

static const char *registerNames[KnownRegisters] =
{
    "A1", "A2", "A3", "A4",
    0, 0, 0, 0,
    0, 0, 0, "AP",
    "IP", "SP", "LR", "PC",
    "PSTrk", 0, 0, 0,
    0, 0, 0, 0,
    0, "PSGdb"
};

static QByteArray dumpRegister(int n, uint value)
{
    QByteArray ba;
    ba += ' ';
    if (n < KnownRegisters && registerNames[n]) {
        ba += registerNames[n];
    } else {
        ba += '#';
        ba += QByteArray::number(n);
    }
    ba += "=" + hexxNumber(value);
    return ba;
}

namespace Debugger {
namespace Internal {

hjk's avatar
hjk committed
89
90
TrkGdbAdapter::TrkGdbAdapter(GdbEngine *engine, const TrkOptionsPtr &options) :
    AbstractGdbAdapter(engine),
91
92
93
94
95
96
    m_options(options),
    m_running(false),
    m_gdbAckMode(true),
    m_verbose(2),
    m_bufferedMemoryRead(true),
    m_waitCount(0)
97
{
hjk's avatar
hjk committed
98
99
    m_gdbServer = 0;
    m_gdbConnection = 0;
dt's avatar
dt committed
100
#ifdef Q_OS_WIN
101
    const DWORD portOffset = GetCurrentProcessId() % 100;
dt's avatar
dt committed
102
#else
103
    const uid_t portOffset = getuid();
dt's avatar
dt committed
104
#endif
105
    m_gdbServerName = _("127.0.0.1:%1").arg(2222 + portOffset);
106
    connect(&m_gdbProc, SIGNAL(readyReadStandardError()),
hjk's avatar
hjk committed
107
        this, SIGNAL(readyReadStandardError()));
108
    connect(&m_gdbProc, SIGNAL(readyReadStandardOutput()),
hjk's avatar
hjk committed
109
        this, SIGNAL(readyReadStandardOutput()));
hjk's avatar
hjk committed
110
111
112
113
114
115
116
117
    connect(&m_gdbProc, SIGNAL(error(QProcess::ProcessError)),
        this, SLOT(handleGdbError(QProcess::ProcessError)));
    connect(&m_gdbProc, SIGNAL(finished(int, QProcess::ExitStatus)),
        this, SLOT(handleGdbFinished(int, QProcess::ExitStatus)));
    connect(&m_gdbProc, SIGNAL(started()),
        this, SLOT(handleGdbStarted()));
    connect(&m_gdbProc, SIGNAL(stateChanged(QProcess::ProcessState)),
        this, SLOT(handleGdbStateChanged(QProcess::ProcessState)));
118
119
120
121
122

    connect(&m_rfcommProc, SIGNAL(readyReadStandardError()),
        this, SLOT(handleRfcommReadyReadStandardError()));
    connect(&m_rfcommProc, SIGNAL(readyReadStandardOutput()),
        this, SLOT(handleRfcommReadyReadStandardOutput()));
123
    connect(&m_rfcommProc, SIGNAL(error(QProcess::ProcessError)),
hjk's avatar
hjk committed
124
        this, SLOT(handleRfcommError(QProcess::ProcessError)));
125
    connect(&m_rfcommProc, SIGNAL(finished(int, QProcess::ExitStatus)),
hjk's avatar
hjk committed
126
        this, SLOT(handleRfcommFinished(int, QProcess::ExitStatus)));
127
    connect(&m_rfcommProc, SIGNAL(started()),
hjk's avatar
hjk committed
128
        this, SLOT(handleRfcommStarted()));
129
    connect(&m_rfcommProc, SIGNAL(stateChanged(QProcess::ProcessState)),
hjk's avatar
hjk committed
130
        this, SLOT(handleRfcommStateChanged(QProcess::ProcessState)));
131

hjk's avatar
hjk committed
132
133
134
135
136
    connect(&m_trkDevice, SIGNAL(messageReceived(trk::TrkResult)),
        this, SLOT(handleTrkResult(trk::TrkResult)));
    connect(&m_trkDevice, SIGNAL(error(QString)),
        this, SLOT(handleTrkError(QString)));

137
    m_trkDevice.setVerbose(m_verbose);
138
    m_trkDevice.setSerialFrame(m_options->mode != TrkOptions::BlueTooth);
139
140
141
142
143

    connect(&m_trkDevice, SIGNAL(logMessage(QString)),
        this, SLOT(trkLogMessage(QString)));
}

hjk's avatar
hjk committed
144
TrkGdbAdapter::~TrkGdbAdapter()
145
{
hjk's avatar
hjk committed
146
    delete m_gdbServer;
hjk's avatar
hjk committed
147
    logMessage("Shutting down.\n");
148
149
}

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
QString TrkGdbAdapter::overrideTrkDevice() const
{
    return m_overrideTrkDevice;
}

void TrkGdbAdapter::setOverrideTrkDevice(const QString &d)
{
    m_overrideTrkDevice = d;
}

QString TrkGdbAdapter::effectiveTrkDevice() const
{
    if (!m_overrideTrkDevice.isEmpty())
        return m_overrideTrkDevice;
    if (m_options->mode == TrkOptions::BlueTooth)
        return m_options->blueToothDevice;
    return m_options->serialPort;
}

hjk's avatar
hjk committed
169
void TrkGdbAdapter::trkLogMessage(const QString &msg)
170
171
172
173
{
    logMessage("TRK " + msg);
}

hjk's avatar
hjk committed
174
void TrkGdbAdapter::setGdbServerName(const QString &name)
175
176
177
178
{
    m_gdbServerName = name;
}

hjk's avatar
hjk committed
179
QString TrkGdbAdapter::gdbServerIP() const
180
181
182
183
184
185
186
{
    int pos = m_gdbServerName.indexOf(':');
    if (pos == -1)
        return m_gdbServerName;
    return m_gdbServerName.left(pos);
}

hjk's avatar
hjk committed
187
uint TrkGdbAdapter::gdbServerPort() const
188
189
190
191
192
193
194
{
    int pos = m_gdbServerName.indexOf(':');
    if (pos == -1)
        return 0;
    return m_gdbServerName.mid(pos + 1).toUInt();
}

hjk's avatar
hjk committed
195
QByteArray TrkGdbAdapter::trkContinueMessage()
196
197
198
199
200
201
202
{
    QByteArray ba;
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

203
QByteArray TrkGdbAdapter::trkReadRegistersMessage()
204
205
206
207
208
209
210
211
212
213
{
    QByteArray ba;
    appendByte(&ba, 0); // Register set, only 0 supported
    appendShort(&ba, 0);
    appendShort(&ba, RegisterCount - 1); // last register
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

214
215
216
217
218
219
220
221
222
223
224
225
QByteArray TrkGdbAdapter::trkWriteRegisterMessage(byte reg, uint value)
{
    QByteArray ba;
    appendByte(&ba, 0); // ?
    appendShort(&ba, reg);
    appendShort(&ba, reg);
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    appendInt(&ba, value);
    return ba;
}

hjk's avatar
hjk committed
226
QByteArray TrkGdbAdapter::trkReadMemoryMessage(uint addr, uint len)
227
228
{
    QByteArray ba;
229
    ba.reserve(11);
230
231
232
233
234
235
236
237
    appendByte(&ba, 0x08); // Options, FIXME: why?
    appendShort(&ba, len);
    appendInt(&ba, addr);
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

hjk's avatar
hjk committed
238
239
240
QByteArray TrkGdbAdapter::trkStepRangeMessage(byte option)
{
    QByteArray ba;
241
    ba.reserve(13);
hjk's avatar
hjk committed
242
    appendByte(&ba, option);
243
244
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // Start address
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // End address
hjk's avatar
hjk committed
245
246
247
248
249
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
QByteArray TrkGdbAdapter::trkDeleteProcessMessage()
{
    QByteArray ba;
    ba.reserve(6);
    appendByte(&ba, 0); // ?
    appendByte(&ba, 0); // Sub-command: Delete Process
    appendInt(&ba, m_session.pid);
    return ba;
}

QByteArray TrkGdbAdapter::trkInterruptMessage()
{
    QByteArray ba;
    ba.reserve(9);
    // Stop the thread (2) or the process (1) or the whole system (0).
    // We choose 2, as 1 does not seem to work.
    appendByte(&ba, 2);
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid); // threadID: 4 bytes Variable number of bytes.
    return ba;
}

hjk's avatar
hjk committed
272
void TrkGdbAdapter::startInferiorEarly()
273
{
hjk's avatar
hjk committed
274
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
275
    QString errorMessage;
276
277
    const QString device = effectiveTrkDevice();
    if (!m_trkDevice.open(device, &errorMessage)) {
278
279
280
281
282
283
284
        logMessage(_("Waiting on %1 (%2)").arg(device, errorMessage));
        if (errorMessage.contains(_("ermission denied"))) {
            static int direction = 0;
            direction = (direction + 1) % 4;
            showStatusMessage(_("Please start TRK on your device! %1")
                .arg(QChar("/|\\-"[direction])));
        }
285
        // Do not loop forever
286
        if (m_waitCount++ < (m_options->mode == TrkOptions::BlueTooth ? 60 : 5)) {
hjk's avatar
hjk committed
287
            QTimer::singleShot(1000, this, SLOT(startInferiorEarly()));
288
        } else {
289
            QString msg = _("Failed to connect to %1 after "
hjk's avatar
hjk committed
290
291
292
                "%2 attempts").arg(device).arg(m_waitCount);
            logMessage(msg);
            emit adapterStartFailed(msg);
293
        }
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
        return;
    }

    m_trkDevice.sendTrkInitialPing();
    sendTrkMessage(0x01); // Connect
    sendTrkMessage(0x05, TrkCB(handleSupportMask));
    sendTrkMessage(0x06, TrkCB(handleCpuType));
    sendTrkMessage(0x04, TrkCB(handleTrkVersions)); // Versions
    //sendTrkMessage(0x09); // Unrecognized command
    //sendTrkMessage(0x4a, 0,
    //    "10 " + formatString("C:\\data\\usingdlls.sisx")); // Open File
    //sendTrkMessage(0x4B, 0, "00 00 00 01 73 1C 3A C8"); // Close File

    QByteArray ba;
    appendByte(&ba, 0); // ?
    appendByte(&ba, 0); // ?
    appendByte(&ba, 0); // ?

312
    appendString(&ba, m_remoteExecutable.toLatin1(), TargetByteOrder);
313
314
315
316
    sendTrkMessage(0x40, TrkCB(handleCreateProcess), ba); // Create Item
    //sendTrkMessage(TRK_WRITE_QUEUE_NOOP_CODE, TrkCB(startGdbServer));
}

hjk's avatar
hjk committed
317
void TrkGdbAdapter::logMessage(const QString &msg)
318
{
hjk's avatar
hjk committed
319
320
    if (m_verbose) {
#ifdef STANDALONE_RUNNER
hjk's avatar
hjk committed
321
        emit output(msg);
hjk's avatar
hjk committed
322
323
324
325
#else
        m_engine->debugMessage(msg);
#endif
    }
326
327
328
329
330
}

//
// Gdb
//
hjk's avatar
hjk committed
331
void TrkGdbAdapter::handleGdbConnection()
332
333
{
    logMessage("HANDLING GDB CONNECTION");
hjk's avatar
hjk committed
334
335
336
    QTC_ASSERT(m_gdbConnection == 0, /**/);
    m_gdbConnection = m_gdbServer->nextPendingConnection();
    QTC_ASSERT(m_gdbConnection, return);
337
338
339
340
341
342
343
344
345
346
347
    connect(m_gdbConnection, SIGNAL(disconnected()),
            m_gdbConnection, SLOT(deleteLater()));
    connect(m_gdbConnection, SIGNAL(readyRead()),
            this, SLOT(readGdbServerCommand()));
}

static inline QString msgGdbPacket(const QString &p)
{
    return QLatin1String("gdb:                              ") + p;
}

hjk's avatar
hjk committed
348
void TrkGdbAdapter::readGdbServerCommand()
349
{
hjk's avatar
hjk committed
350
    QTC_ASSERT(m_gdbConnection, return);
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
    QByteArray packet = m_gdbConnection->readAll();
    m_gdbReadBuffer.append(packet);

    logMessage("gdb: -> " + QString::fromAscii(packet));
    if (packet != m_gdbReadBuffer)
        logMessage("buffer: " + m_gdbReadBuffer);

    QByteArray &ba = m_gdbReadBuffer;
    while (ba.size()) {
        char code = ba.at(0);
        ba = ba.mid(1);

        if (code == '+') {
            //logMessage("ACK");
            continue;
        }

        if (code == '-') {
            logMessage("NAK: Retransmission requested");
            continue;
        }

        if (code == char(0x03)) {
            logMessage("INTERRUPT RECEIVED");
            interruptInferior();
            continue;
        }

        if (code != '$') {
            logMessage("Broken package (2) " + quoteUnprintableLatin1(ba)
                + hexNumber(code));
            continue;
        }

        int pos = ba.indexOf('#');
        if (pos == -1) {
            logMessage("Invalid checksum format in "
                + quoteUnprintableLatin1(ba));
            continue;
        }

        bool ok = false;
        uint checkSum = ba.mid(pos + 1, 2).toUInt(&ok, 16);
        if (!ok) {
            logMessage("Invalid checksum format 2 in "
                + quoteUnprintableLatin1(ba));
            return;
        }

        //logMessage(QString("Packet checksum: %1").arg(checkSum));
        byte sum = 0;
        for (int i = 0; i < pos; ++i)
            sum += ba.at(i);

        if (sum != checkSum) {
            logMessage(QString("ERROR: Packet checksum wrong: %1 %2 in "
                + quoteUnprintableLatin1(ba)).arg(checkSum).arg(sum));
        }

        QByteArray cmd = ba.left(pos);
        ba.remove(0, pos + 3);
        handleGdbServerCommand(cmd);
    }
}

hjk's avatar
hjk committed
416
bool TrkGdbAdapter::sendGdbServerPacket(const QByteArray &packet, bool doFlush)
417
418
{
    if (!m_gdbConnection) {
419
420
        logMessage(_("Cannot write to gdb: No connection (%1)")
            .arg(_(packet)));
421
422
423
        return false;
    }
    if (m_gdbConnection->state() != QAbstractSocket::ConnectedState) {
424
425
        logMessage(_("Cannot write to gdb: Not connected (%1)")
            .arg(_(packet)));
426
427
428
        return false;
    }
    if (m_gdbConnection->write(packet) == -1) {
429
430
        logMessage(_("Cannot write to gdb: %1 (%2)")
            .arg(m_gdbConnection->errorString()).arg(_(packet)));
431
432
433
434
435
436
437
        return false;
    }
    if (doFlush)
        m_gdbConnection->flush();
    return true;
}

hjk's avatar
hjk committed
438
void TrkGdbAdapter::sendGdbServerAck()
439
440
441
442
443
444
445
446
{
    if (!m_gdbAckMode)
        return;
    QByteArray packet = "+";
    logMessage("gdb: <- " + packet);
    sendGdbServerPacket(packet, false);
}

hjk's avatar
hjk committed
447
void TrkGdbAdapter::sendGdbServerMessage(const QByteArray &msg, const QByteArray &logNote)
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
{
    byte sum = 0;
    for (int i = 0; i != msg.size(); ++i)
        sum += msg.at(i);

    char checkSum[30];
    qsnprintf(checkSum, sizeof(checkSum) - 1, "%02x ", sum);

    //logMessage(QString("Packet checksum: %1").arg(sum));

    QByteArray packet;
    packet.append("$");
    packet.append(msg);
    packet.append('#');
    packet.append(checkSum);
    int pad = qMax(0, 24 - packet.size());
    logMessage("gdb: <- " + packet + QByteArray(pad, ' ') + logNote);
    sendGdbServerPacket(packet, true);
}

hjk's avatar
hjk committed
468
void TrkGdbAdapter::sendGdbServerMessageAfterTrkResponse(const QByteArray &msg,
469
470
471
472
473
474
    const QByteArray &logNote)
{
    QByteArray ba = msg + char(1) + logNote;
    sendTrkMessage(TRK_WRITE_QUEUE_NOOP_CODE, TrkCB(reportToGdb), "", ba); // Answer gdb
}

hjk's avatar
hjk committed
475
void TrkGdbAdapter::reportToGdb(const TrkResult &result)
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
{
    QByteArray message = result.cookie.toByteArray();
    QByteArray note;
    int pos = message.lastIndexOf(char(1)); // HACK
    if (pos != -1) {
        note = message.mid(pos + 1);
        message = message.left(pos);
    }
    message.replace("@CODESEG@", hexNumber(m_session.codeseg));
    message.replace("@DATASEG@", hexNumber(m_session.dataseg));
    message.replace("@PID@", hexNumber(m_session.pid));
    message.replace("@TID@", hexNumber(m_session.tid));
    sendGdbServerMessage(message, note);
}

hjk's avatar
hjk committed
491
QByteArray TrkGdbAdapter::trkBreakpointMessage(uint addr, uint len, bool armMode)
492
493
494
495
496
497
498
499
500
501
502
503
{
    QByteArray ba;
    appendByte(&ba, 0x82);  // unused option
    appendByte(&ba, armMode /*bp.mode == ArmMode*/ ? 0x00 : 0x01);
    appendInt(&ba, addr);
    appendInt(&ba, len);
    appendInt(&ba, 0x00000001);
    appendInt(&ba, m_session.pid);
    appendInt(&ba, 0xFFFFFFFF);
    return ba;
}

hjk's avatar
hjk committed
504
void TrkGdbAdapter::handleGdbServerCommand(const QByteArray &cmd)
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
{
    // http://sourceware.org/gdb/current/onlinedocs/gdb_34.html
    if (0) {}

    else if (cmd == "!") {
        sendGdbServerAck();
        //sendGdbServerMessage("", "extended mode not enabled");
        sendGdbServerMessage("OK", "extended mode enabled");
    }

    else if (cmd.startsWith("?")) {
        logMessage(msgGdbPacket(QLatin1String("Query halted")));
        // Indicate the reason the target halted.
        // The reply is the same as for step and continue.
        sendGdbServerAck();
        // The command below will trigger fetching a stack trace while
        // the process does not seem to be fully functional. Most notably
        // the PC points to a 0x9..., which is not in "our" range
        //sendGdbServerMessage("T05library:r;", "target halted (library load)");
        //sendGdbServerMessage("S05", "target halted (trap)");
        sendGdbServerMessage("S00", "target halted (trap)");
        //sendGdbServerMessage("O" + QByteArray("Starting...").toHex());
    }

    else if (cmd == "c") {
        logMessage(msgGdbPacket(QLatin1String("Continue")));
        sendGdbServerAck();
        QByteArray ba;
        appendByte(&ba, 0); // options
        appendInt(&ba, 0); // start address
        appendInt(&ba, 0); // end address
        appendInt(&ba, m_session.pid);
        appendInt(&ba, m_session.tid);
        sendTrkMessage(0x18, TrkCallback(), ba);
    }

    else if (cmd.startsWith("C")) {
        logMessage(msgGdbPacket(QLatin1String("Continue with signal")));
        // C sig[;addr] Continue with signal sig (hex signal number)
        //Reply: See section D.3 Stop Reply Packets, for the reply specifications.
        sendGdbServerAck();
        bool ok = false;
        uint signalNumber = cmd.mid(1).toInt(&ok, 16);
        QByteArray ba;
        appendInt(&ba, m_session.pid);
        appendInt(&ba, m_session.tid);
hjk's avatar
hjk committed
551
        sendTrkMessage(0x18, TrkCB(handleSignalContinue), ba, signalNumber);
552
553
554
555
556
557
558
559
560
    }

    else if (cmd.startsWith("D")) {
        sendGdbServerAck();
        sendGdbServerMessage("OK", "shutting down");
    }

    else if (cmd == "g") {
        // Read general registers.
hjk's avatar
hjk committed
561
        logMessage(msgGdbPacket(QLatin1String("Read registers")));
562
        sendGdbServerAck();
hjk's avatar
hjk committed
563
        reportRegisters();
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
    }

    else if (cmd.startsWith("Hc")) {
        logMessage(msgGdbPacket(QLatin1String("Set thread & continue")));
        // Set thread for subsequent operations (`m', `M', `g', `G', et.al.).
        // for step and continue operations
        //$Hc-1#09
        sendGdbServerAck();
        sendGdbServerMessage("OK", "Set current thread for step & continue");
    }

    else if (cmd.startsWith("Hg")) {
        logMessage(msgGdbPacket(QLatin1String("Set thread")));
        // Set thread for subsequent operations (`m', `M', `g', `G', et.al.).
        // for 'other operations.  0 - any thread
        //$Hg0#df
        sendGdbServerAck();
        m_session.currentThread = cmd.mid(2).toInt(0, 16);
        sendGdbServerMessage("OK", "Set current thread "
            + QByteArray::number(m_session.currentThread));
    }

hjk's avatar
hjk committed
586
587
    else if (cmd == "k" || cmd.startsWith("vKill")) {
        // Kill inferior process
588
        logMessage(msgGdbPacket(QLatin1String("kill")));
hjk's avatar
hjk committed
589
        sendTrkMessage(0x41, TrkCB(handleDeleteProcess),
590
            trkDeleteProcessMessage(), "Delete process"); 
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
    }

    else if (cmd.startsWith("m")) {
        logMessage(msgGdbPacket(QLatin1String("Read memory")));
        // m addr,length
        sendGdbServerAck();
        uint addr = 0, len = 0;
        do {
            const int pos = cmd.indexOf(',');
            if (pos == -1)
                break;
            bool ok;
            addr = cmd.mid(1, pos - 1).toUInt(&ok, 16);
            if (!ok)
                break;
            len = cmd.mid(pos + 1).toUInt(&ok, 16);
            if (!ok)
                break;
        } while (false);
        if (len) {
            readMemory(addr, len);
        } else {
            sendGdbServerMessage("E20", "Error " + cmd);
        }
    }
616

617
618
619
620
621
622
623
624
625
626
    else if (cmd.startsWith("p")) {
        logMessage(msgGdbPacket(QLatin1String("read register")));
        // 0xf == current instruction pointer?
        //sendGdbServerMessage("0000", "current IP");
        sendGdbServerAck();
        bool ok = false;
        const uint registerNumber = cmd.mid(1).toInt(&ok, 16);
        QByteArray logMsg = "Read Register";
        if (registerNumber == RegisterPSGdb) {
            QByteArray ba;
hjk's avatar
hjk committed
627
            appendInt(&ba, m_snapshot.registers[RegisterPSTrk], LittleEndian);
628
629
            logMsg += dumpRegister(registerNumber, m_snapshot.registers[RegisterPSTrk]);
            sendGdbServerMessage(ba.toHex(), logMsg);
hjk's avatar
hjk committed
630
        } else if (registerNumber < 16) {
631
            QByteArray ba;
hjk's avatar
hjk committed
632
            appendInt(&ba, m_snapshot.registers[registerNumber], LittleEndian);
633
634
635
            logMsg += dumpRegister(registerNumber, m_snapshot.registers[registerNumber]);
            sendGdbServerMessage(ba.toHex(), logMsg);
        } else {
hjk's avatar
hjk committed
636
637
638
            sendGdbServerMessage("0000", "read single unknown register #"
                + QByteArray::number(registerNumber));
            //sendGdbServerMessage("E01", "read single unknown register");
639
640
641
        }
    }

642
643
644
645
646
647
648
649
650
651
    else if (cmd.startsWith("P")) {
        logMessage(msgGdbPacket(QLatin1String("write register")));
        // $Pe=70f96678#d3
        sendGdbServerAck();
        int pos = cmd.indexOf('=');
        QByteArray regName = cmd.mid(1, pos - 1);
        QByteArray valueName = cmd.mid(pos + 1);
        bool ok = false;
        const uint registerNumber = regName.toInt(&ok, 16);
        const uint value = swapEndian(valueName.toInt(&ok, 16));
652
653
        // FIXME: Assume all goes well.
        m_snapshot.registers[registerNumber] = value;
654
655
656
657
658
        QByteArray ba = trkWriteRegisterMessage(registerNumber, value);
        sendTrkMessage(0x13, TrkCB(handleWriteRegister), ba, "Write register");
        // Note that App TRK refuses to write registers 13 and 14
    }

659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    else if (cmd == "qAttached") {
        //$qAttached#8f
        // 1: attached to an existing process
        // 0: created a new process
        sendGdbServerAck();
        sendGdbServerMessage("0", "new process created");
        //sendGdbServerMessage("1", "attached to existing process");
        //sendGdbServerMessage("E01", "new process created");
    }

    else if (cmd.startsWith("qC")) {
        logMessage(msgGdbPacket(QLatin1String("query thread id")));
        // Return the current thread ID
        //$qC#b4
        sendGdbServerAck();
        sendGdbServerMessageAfterTrkResponse("QC@TID@");
    }

    else if (cmd.startsWith("qSupported")) {
        //$qSupported#37
        //$qSupported:multiprocess+#c6
        //logMessage("Handling 'qSupported'");
        sendGdbServerAck();
hjk's avatar
hjk committed
682
683
684
685
686
687
688
689
690
691
692
693
694
        sendGdbServerMessage(
            "PacketSize=7cf;"
            "QPassSignals+;"
            "qXfer:libraries:read+;"
            //"qXfer:auxv:read+;"
            "qXfer:features:read+");
    }

    else if (cmd == "qfDllInfo") {
        // happens with  gdb 6.4.50.20060226-cvs / CodeSourcery
        // never made it into FSF gdb?
        sendGdbServerAck();
        sendGdbServerMessage("", "FIXME: nothing?");
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
    }

    else if (cmd == "qPacketInfo") {
        // happens with  gdb 6.4.50.20060226-cvs / CodeSourcery
        // deprecated by qSupported?
        sendGdbServerAck();
        sendGdbServerMessage("", "FIXME: nothing?");
    }

    else if (cmd == "qOffsets") {
        sendGdbServerAck();
        sendGdbServerMessageAfterTrkResponse("TextSeg=@CODESEG@;DataSeg=@DATASEG@");
    }

    else if (cmd == "qSymbol::") {
        if (m_verbose)
            logMessage(msgGdbPacket(QLatin1String("notify can handle symbol lookup")));
        // Notify the target that GDB is prepared to serve symbol lookup requests.
        sendGdbServerAck();
        if (1)
            sendGdbServerMessage("OK", "no further symbols needed");
        else
hjk's avatar
hjk committed
717
718
            sendGdbServerMessage("qSymbol:" + QByteArray("_Z7E32Mainv").toHex(),
                "ask for more");
719
720
721
722
723
724
725
726
    }

    else if (cmd.startsWith("qXfer:features:read:target.xml:")) {
        //  $qXfer:features:read:target.xml:0,7ca#46...Ack
        sendGdbServerAck();
        sendGdbServerMessage("l<target><architecture>symbianelf</architecture></target>");
    }

727
728
729
730
731
732
733
734
735
736
737
    else if (cmd.startsWith("qXfer:libraries:read")) {
        sendGdbServerAck();
        /*
            <library-list>
              <library name="/lib/libc.so.6">
                <segment address="0x10000000"/>
              </library>
            </library-list>
i        */
    }

738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
    else if (cmd == "QStartNoAckMode") {
        //$qSupported#37
        //logMessage("Handling 'QStartNoAckMode'");
        sendGdbServerAck();
        sendGdbServerMessage("OK", "ack no-ack mode");
        m_gdbAckMode = false;
    }

    else if (cmd.startsWith("QPassSignals")) {
        // list of signals to pass directly to inferior
        // $QPassSignals:e;10;14;17;1a;1b;1c;21;24;25;4c;#8f
        // happens only if "QPassSignals+;" is qSupported
        sendGdbServerAck();
        // FIXME: use the parameters
        sendGdbServerMessage("OK", "passing signals accepted");
    }

    else if (cmd == "s" || cmd.startsWith("vCont;s")) {
        logMessage(msgGdbPacket(QLatin1String("Step range")));
        logMessage("  from " + hexxNumber(m_snapshot.registers[RegisterPC]));
        sendGdbServerAck();
        m_running = true;
hjk's avatar
hjk committed
760
761
        QByteArray ba = trkStepRangeMessage(0x01);  // options "step into"
        sendTrkMessage(0x19, TrkCB(handleStepInto), ba, "Step range");
762
763
764
765
766
767
    }

    else if (cmd == "vCont?") {
        // actions supported by the vCont packet
        sendGdbServerAck();
        //sendGdbServerMessage("OK"); // we don't support vCont.
768
        sendGdbServerMessage("vCont;c;C;s;S");
769
770
771
772
773
774
775
776
777
778
779
    }

    else if (cmd == "vCont;c") {
        // vCont[;action[:thread-id]]...'
        sendGdbServerAck();
        m_running = true;
        sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
    }

    else if (cmd.startsWith("Z0,") || cmd.startsWith("Z1,")) {
        // Insert breakpoint
hjk's avatar
hjk committed
780
        sendGdbServerAck();
781
782
783
784
785
786
787
        logMessage(msgGdbPacket(QLatin1String("Insert breakpoint")));
        // $Z0,786a4ccc,4#99
        const int pos = cmd.lastIndexOf(',');
        bool ok = false;
        const uint addr = cmd.mid(3, pos - 3).toInt(&ok, 16);
        const uint len = cmd.mid(pos + 1).toInt(&ok, 16);
        //qDebug() << "ADDR: " << hexNumber(addr) << " LEN: " << len;
788
        logMessage(_("Inserting breakpoint at 0x%1, %2")
789
            .arg(addr, 0, 16).arg(len));
790
        const QByteArray ba = trkBreakpointMessage(addr, len, len == 4);
791
792
793
794
795
        sendTrkMessage(0x1B, TrkCB(handleAndReportSetBreakpoint), ba, addr);
    }

    else if (cmd.startsWith("z0,") || cmd.startsWith("z1,")) {
        // Remove breakpoint
hjk's avatar
hjk committed
796
        sendGdbServerAck();
797
798
799
800
801
802
803
804
        logMessage(msgGdbPacket(QLatin1String("Remove breakpoint")));
        // $z0,786a4ccc,4#99
        const int pos = cmd.lastIndexOf(',');
        bool ok = false;
        const uint addr = cmd.mid(3, pos - 3).toInt(&ok, 16);
        const uint len = cmd.mid(pos + 1).toInt(&ok, 16);
        const uint bp = m_session.addressToBP[addr];
        if (bp == 0) {
805
            logMessage(_("NO RECORDED BP AT 0x%1, %2")
806
                .arg(addr, 0, 16).arg(len));
hjk's avatar
hjk committed
807
            sendGdbServerMessage("E00");
808
809
810
        } else {
            m_session.addressToBP.remove(addr);
            QByteArray ba;
811
            appendInt(&ba, bp);
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
            sendTrkMessage(0x1C, TrkCB(handleClearBreakpoint), ba, addr);
        }
    }

    else if (cmd.startsWith("qPart:") || cmd.startsWith("qXfer:"))  {
        QByteArray data  = cmd.mid(1 + cmd.indexOf(':'));
        // "qPart:auxv:read::0,147": Read OS auxiliary data (see info aux)
        bool handled = false;
        if (data.startsWith("auxv:read::")) {
            const int offsetPos = data.lastIndexOf(':') + 1;
            const int commaPos = data.lastIndexOf(',');
            if (commaPos != -1) {                
                bool ok1 = false, ok2 = false;
                const int offset = data.mid(offsetPos,  commaPos - offsetPos)
                    .toInt(&ok1, 16);
                const int length = data.mid(commaPos + 1).toInt(&ok2, 16);
                if (ok1 && ok2) {
829
                    const QString msg = _("Read of OS auxilary "
830
                        "vector (%1, %2) not implemented.").arg(offset).arg(length);
hjk's avatar
hjk committed
831
                    logMessage(msgGdbPacket(msg));
832
833
834
835
836
837
838
839
                    sendGdbServerMessage("E20", msg.toLatin1());
                    handled = true;
                }
            }
        } // auxv read
        if (!handled) {
            const QString msg = QLatin1String("FIXME unknown 'XFER'-request: ")
                + QString::fromAscii(cmd);
hjk's avatar
hjk committed
840
            logMessage(msgGdbPacket(msg));
841
842
843
844
845
846
847
848
849
            sendGdbServerMessage("E20", msg.toLatin1());
        }
    } // qPart/qXfer
    else {
        logMessage(msgGdbPacket(QLatin1String("FIXME unknown: ")
            + QString::fromAscii(cmd)));
    }
}

hjk's avatar
hjk committed
850
void TrkGdbAdapter::executeCommand(const QString &msg)
851
852
853
854
855
{
    if (msg == "EI") {
        sendGdbMessage("-exec-interrupt");
    } else if (msg == "C") {
        sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
hjk's avatar
hjk committed
856
857
858
859
    } else if (msg == "S") {
        sendTrkMessage(0x19, TrkCallback(), trkStepRangeMessage(0x01), "STEP");
    } else if (msg == "N") {
        sendTrkMessage(0x19, TrkCallback(), trkStepRangeMessage(0x11), "NEXT");
860
861
862
863
864
865
866
867
    } else if (msg == "I") {
        interruptInferior();
    } else {
        logMessage("EXECUTING GDB COMMAND " + msg);
        sendGdbMessage(msg);
    }
}

hjk's avatar
hjk committed
868
void TrkGdbAdapter::sendTrkMessage(byte code, TrkCallback callback,
869
870
871
872
873
    const QByteArray &data, const QVariant &cookie)
{
    m_trkDevice.sendTrkMessage(code, callback, data, cookie);
}

hjk's avatar
hjk committed
874
void TrkGdbAdapter::sendTrkAck(byte token)
875
{
876
    //logMessage(QString("SENDING ACKNOWLEDGEMENT FOR TOKEN %1").arg(int(token)));
877
878
879
    m_trkDevice.sendTrkAck(token);
}

hjk's avatar
hjk committed
880
void TrkGdbAdapter::handleTrkError(const QString &msg)
881
882
883
884
{
    logMessage("## TRK ERROR: " + msg);
}

hjk's avatar
hjk committed
885
void TrkGdbAdapter::handleTrkResult(const TrkResult &result)
886
887
888
889
890
891
892
893
{
    if (result.isDebugOutput) {
        sendTrkAck(result.token);
        logMessage(QLatin1String("APPLICATION OUTPUT: ") +
            QString::fromAscii(result.data));
        sendGdbServerMessage("O" + result.data.toHex());
        return;
    }
894
    //logMessage("READ TRK " + result.toString());
895
896
897
898
899
900
901
902
903
    QByteArray prefix = "READ BUF:                                       ";
    QByteArray str = result.toString().toUtf8();
    switch (result.code) {
        case 0x80: // ACK
            break;
        case 0xff: { // NAK. This mostly means transmission error, not command failed.
            QString logMsg;
            QTextStream(&logMsg) << prefix << "NAK: for token=" << result.token
                << " ERROR: " << errorMessage(result.data.at(0)) << ' ' << str;
hjk's avatar
hjk committed
904
            logMessage(logMsg);
905
906
907
908
909
910
911
912
            break;
        }
        case 0x90: { // Notified Stopped
            // 90 01   78 6a 40 40   00 00 07 23   00 00 07 24  00 00
            const char *data = result.data.data();
            const uint addr = extractInt(data);
            const uint pid = extractInt(data + 4);
            const uint tid = extractInt(data + 8);
913
            logMessage(prefix + _("NOTE: PID %1/TID %2 "
914
915
916
917
918
919
920
921
922
923
924
                "STOPPED at 0x%3").arg(pid).arg(tid).arg(addr, 0, 16));
            sendTrkAck(result.token);
            if (addr) {
                // Todo: Do not send off GdbMessages if a synced gdb
                // query is pending, queue instead
                if (m_running) {
                    m_running = false;
                }
            } else {
                logMessage(QLatin1String("Ignoring stop at 0"));
            }
hjk's avatar
hjk committed
925
926
927
928
929
            // We almost always need register values, so get them
            // now before informing gdb about the stop. In theory
            //sendGdbServerMessage("S05", "Target stopped");
            sendTrkMessage(0x12,
                TrkCB(handleAndReportReadRegistersAfterStop),
930
                trkReadRegistersMessage());
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
            break;
        }
        case 0x91: { // Notify Exception (obsolete)
            logMessage(prefix + "NOTE: EXCEPTION  " + str);
            sendTrkAck(result.token);
            break;
        }
        case 0x92: { //
            logMessage(prefix + "NOTE: INTERNAL ERROR: " + str);
            sendTrkAck(result.token);
            break;
        }

        // target->host OS notification
        case 0xa0: { // Notify Created
            const char *data = result.data.data();
            const byte error = result.data.at(0);
            // type: 1 byte; for dll item, this value is 2.
            const byte type = result.data.at(1);
            const uint pid = extractInt(data + 2);
            const uint tid = extractInt(data + 6);
            const uint codeseg = extractInt(data + 10);
            const uint dataseg = extractInt(data + 14);
            const uint len = extractShort(data + 18);
            const QByteArray name = result.data.mid(20, len); // library name
            m_session.modules += QString::fromAscii(name);
            QString logMsg;
            QTextStream str(&logMsg);
            str << prefix << " NOTE: LIBRARY LOAD: token=" << result.token;
            if (error)
                str << " ERROR: " << int(error);
            str << " TYPE: " << int(type) << " PID: " << pid << " TID:   " <<  tid;
            str << " CODE: " << hexxNumber(codeseg);
            str << " DATA: " << hexxNumber(dataseg);
            str << " NAME: '" << name << '\'';
966
967
968
969
970
            Library lib;
            lib.name = name;
            lib.codeseg = codeseg;
            lib.dataseg = dataseg;
            m_session.libraries.append(lib);
971
            logMessage(logMsg);
972
973
974
975
            // This lets gdb trigger a register update etc.
            // With CS gdb 6.4 we get a non-standard $qfDllInfo#7f+ request
            // afterwards, so don't use it for now.
            //sendGdbServerMessage("T05library:;");
976
977
978
979
980
981
982
983
984
985
986
            sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
            break;
        }
        case 0xa1: { // NotifyDeleted
            const ushort itemType = extractByte(result.data.data() + 1);
            const ushort len = result.data.size() > 12
                ? extractShort(result.data.data() + 10) : ushort(0);
            const QString name = len
                ? QString::fromAscii(result.data.mid(12, len)) : QString();
            if (!name.isEmpty())
                m_session.modules.removeAll(name);
987
            logMessage(_("%1 %2 UNLOAD: %3")
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
                .arg(QString::fromAscii(prefix))
                .arg(itemType ? QLatin1String("LIB") : QLatin1String("PROCESS"))
                .arg(name));
            sendTrkAck(result.token);
            if (itemType == 0) {
                sendGdbServerMessage("W00", "Process exited");
                //sendTrkMessage(0x02, TrkCB(handleDisconnect));
            }
            break;
        }
        case 0xa2: { // NotifyProcessorStarted
            logMessage(prefix + "NOTE: PROCESSOR STARTED: " + str);
            sendTrkAck(result.token);
            break;
        }
        case 0xa6: { // NotifyProcessorStandby
            logMessage(prefix + "NOTE: PROCESSOR STANDBY: " + str);
            sendTrkAck(result.token);
            break;
        }
        case 0xa7: { // NotifyProcessorReset
            logMessage(prefix + "NOTE: PROCESSOR RESET: " + str);
            sendTrkAck(result.token);
            break;
        }
        default: {
            logMessage(prefix + "INVALID: " + str);
            break;
        }
    }
}

hjk's avatar
hjk committed
1020
void TrkGdbAdapter::handleCpuType(const TrkResult &result)
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
{
    //---TRK------------------------------------------------------
    //  Command: 0x80 Acknowledge
    //    Error: 0x00
    // [80 03 00  04 00 00 04 00 00 00]
    m_session.cpuMajor = result.data[1];
    m_session.cpuMinor = result.data[2];
    m_session.bigEndian = result.data[3];
    m_session.defaultTypeSize = result.data[4];
    m_session.fpTypeSize = result.data[5];
    m_session.extended1TypeSize = result.data[6];
    //m_session.extended2TypeSize = result.data[6];
    QString logMsg;
    QTextStream(&logMsg) << "HANDLE CPU TYPE: CPU=" << m_session.cpuMajor << '.'
        << m_session.cpuMinor << " bigEndian=" << m_session.bigEndian
        << " defaultTypeSize=" << m_session.defaultTypeSize
        << " fpTypeSize=" << m_session.fpTypeSize
        << " extended1TypeSize=" <<  m_session.extended1TypeSize;
    logMessage(logMsg);
}

hjk's avatar
hjk committed
1042
void TrkGdbAdapter::handleCreateProcess(const TrkResult &result)
1043
{
hjk's avatar
hjk committed
1044
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
1045
1046
1047
    //  40 00 00]
    //logMessage("       RESULT: " + result.toString());
    // [80 08 00   00 00 01 B5   00 00 01 B6   78 67 40 00   00 40 00 00]
hjk's avatar
hjk committed
1048
1049
1050
1051
1052
1053
1054
1055
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        QString msg = _("Cannot start executable \"%1\" on the device:\n%2")
            .arg(m_remoteExecutable).arg(result.errorString());
        //m_trkDevice.close();
        emit adapterStartFailed(msg);
        return;
    }
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
    const char *data = result.data.data();
    m_session.pid = extractInt(data + 1);
    m_session.tid = extractInt(data + 5);
    m_session.codeseg = extractInt(data + 9);
    m_session.dataseg = extractInt(data + 13);

    logMessage("PID: " + hexxNumber(m_session.pid));
    logMessage("TID: " + hexxNumber(m_session.tid));
    logMessage("COD: " + hexxNumber(m_session.codeseg));
    logMessage("DAT: " + hexxNumber(m_session.dataseg));

    QByteArray ba;
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);

    startGdb();
}

hjk's avatar
hjk committed
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
void TrkGdbAdapter::handleDeleteProcess(const TrkResult &result)
{
    Q_UNUSED(result);
    logMessage("TRK Process killed");
    //sendTrkMessage(0x01, TrkCB(handleDeleteProcess2)); // Ping
    sendTrkMessage(0x02, TrkCB(handleDeleteProcess2)); // Disconnect
}

void TrkGdbAdapter::handleDeleteProcess2(const TrkResult &result)
{
    Q_UNUSED(result);
    logMessage("process killed");
    sendGdbServerAck();
    sendGdbServerMessage("", "process killed");
}

hjk's avatar
hjk committed
1090
void TrkGdbAdapter::handleReadRegisters(const TrkResult &result)
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
{
    logMessage("       RESULT: " + result.toString());
    // [80 0B 00   00 00 00 00   C9 24 FF BC   00 00 00 00   00
    //  60 00 00   00 00 00 00   78 67 79 70   00 00 00 00   00...]
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        return;
    }
    const char *data = result.data.data() + 1; // Skip ok byte
    for (int i = 0; i < RegisterCount; ++i)
        m_snapshot.registers[i] = extractInt(data + 4 * i);
} 

1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
void TrkGdbAdapter::handleWriteRegister(const TrkResult &result)
{
    logMessage("       RESULT: " + result.toString() + result.cookie.toString());
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        sendGdbServerMessage("E01");
        return;
    }
    sendGdbServerMessage("OK");
} 

hjk's avatar
hjk committed
1115
void TrkGdbAdapter::reportRegisters()
1116
1117
1118
{
    QByteArray ba;
    for (int i = 0; i < 16; ++i) {
hjk's avatar
hjk committed
1119
        const uint reg = swapEndian(m_snapshot.registers[i]);
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
        ba += hexNumber(reg, 8);
    }
    QByteArray logMsg = "REGISTER CONTENTS: ";
    if (m_verbose > 1) {
        for (int i = 0; i < RegisterCount; ++i) {
            logMsg += dumpRegister(i, m_snapshot.registers[i]);
            logMsg += ' ';
        }
    }
    sendGdbServerMessage(ba, logMsg);
}

hjk's avatar
hjk committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
static void appendRegister(QByteArray *ba, uint regno, uint value)
{
    ba->append(hexNumber(regno, 2));
    ba->append(':');
    ba->append(hexNumber(swapEndian(value), 8));
    ba->append(';');
}

void TrkGdbAdapter::handleAndReportReadRegistersAfterStop(const TrkResult &result)
{
    handleReadRegisters(result);
    QByteArray ba = "T05";
    for (int i = 0; i < 16; ++i)
        appendRegister(&ba, i, m_snapshot.registers[i]);
hjk's avatar
hjk committed
1146
    // FIXME: those are not understood by gdb 6.4
hjk's avatar
hjk committed
1147
1148
1149
    //for (int i = 16; i < 25; ++i)
    //    appendRegister(&ba, i, 0x0);
    appendRegister(&ba, RegisterPSGdb, m_snapshot.registers[RegisterPSTrk]);
1150
    //qDebug() << "TrkGdbAdapter::handleAndReportReadRegistersAfterStop" << ba;
hjk's avatar
hjk committed
1151
1152
1153
    sendGdbServerMessage(ba, "Registers");
}

hjk's avatar
hjk committed
1154
static QString msgMemoryReadError(int code, uint addr, uint len = 0)
1155
1156
{
    const QString lenS = len ? QString::number(len) : QLatin1String("<unknown>");
1157
    return _("Memory read error %1 at: 0x%2 %3")
1158
1159
1160
        .arg(code).arg(addr, 0 ,16).arg(lenS);
}

hjk's avatar
hjk committed
1161
void TrkGdbAdapter::handleReadMemoryBuffered(const TrkResult &result)
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
{
    if (extractShort(result.data.data() + 1) + 3 != result.data.size())
        logMessage("\n BAD MEMORY RESULT: " + result.data.toHex() + "\n");
    const uint blockaddr = result.cookie.toUInt();
    if (const int errorCode = result.errorCode()) {
        logMessage(msgMemoryReadError(errorCode, blockaddr));
        return;
    }
    const QByteArray ba = result.data.mid(3);
    m_snapshot.memory.insert(blockaddr, ba);
}

// Format log message for memory access with some smartness about registers
hjk's avatar
hjk committed
1175
QByteArray TrkGdbAdapter::memoryReadLogMessage(uint addr, uint len, const QByteArray &ba) const
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
{
    QByteArray logMsg = "memory contents";
    if (m_verbose > 1) {
        logMsg += " addr: " + hexxNumber(addr);
        // indicate dereferencing of registers
        if (len == 4) {
            if (addr == m_snapshot.registers[RegisterPC]) {
                logMsg += "[PC]";
            } else if (addr == m_snapshot.registers[RegisterPSTrk]) {
                logMsg += "[PSTrk]";
            } else if (addr == m_snapshot.registers[RegisterSP]) {
                logMsg += "[SP]";
            } else if (addr == m_snapshot.registers[RegisterLR]) {
                logMsg += "[LR]";
            } else if (addr > m_snapshot.registers[RegisterSP] &&
                    (addr - m_snapshot.registers[RegisterSP]) < 10240) {
                logMsg += "[SP+"; // Stack area ...stack seems to be top-down
                logMsg += QByteArray::number(addr - m_snapshot.registers[RegisterSP]);
                logMsg += ']';
            }
        }
        logMsg += " length ";
        logMsg += QByteArray::number(len);
        logMsg += " :";
        logMsg += stringFromArray(ba, 16).toAscii();
    }
    return logMsg;
}

hjk's avatar
hjk committed
1205
void TrkGdbAdapter::reportReadMemoryBuffered(const TrkResult &result)
1206
1207
1208
1209
{
    const qulonglong cookie = result.cookie.toULongLong();
    const uint addr = cookie >> 32;
    const uint len = uint(cookie);
1210
1211
    reportReadMemoryBuffered(addr, len);
}
1212

1213
1214
void TrkGdbAdapter::reportReadMemoryBuffered(uint addr, uint len)
{
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
    // Gdb accepts less memory according to documentation.
    // Send E on complete failure.
    QByteArray ba;
    uint blockaddr = (addr / MemoryChunkSize) * MemoryChunkSize;
    for (; blockaddr < addr + len; blockaddr += MemoryChunkSize) {
        const Snapshot::Memory::const_iterator it = m_snapshot.memory.constFind(blockaddr);
        if (it == m_snapshot.memory.constEnd())
            break;
        ba.append(it.value());
    }
    const int previousChunkOverlap = addr % MemoryChunkSize;
    if (previousChunkOverlap != 0 && ba.size() > previousChunkOverlap)
        ba.remove(0, previousChunkOverlap);
    if (ba.size() > int(len))
        ba.truncate(len);

    if (ba.isEmpty()) {
        ba = "E20";
        sendGdbServerMessage(ba, msgMemoryReadError(32, addr, len).toLatin1());
    } else {
        sendGdbServerMessage(ba.toHex(), memoryReadLogMessage(addr, len, ba));
    }
}

hjk's avatar
hjk committed
1239
void TrkGdbAdapter::handleReadMemoryUnbuffered(const TrkResult &result)
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
{
    //logMessage("UNBUFFERED MEMORY READ: " + stringFromArray(result.data));
    const uint blockaddr = result.cookie.toUInt();
    if (extractShort(result.data.data() + 1) + 3 != result.data.size())
        logMessage("\n BAD MEMORY RESULT: " + result.data.toHex() + "\n");
    if (const int errorCode = result.errorCode()) {
        const QByteArray ba = "E20";
        sendGdbServerMessage(ba, msgMemoryReadError(32, blockaddr).toLatin1());
    } else {
        const QByteArray ba = result.data.mid(3);
        sendGdbServerMessage(ba.toHex(), memoryReadLogMessage(blockaddr, ba.size(), ba));
    }
}

hjk's avatar
hjk committed
1254
void TrkGdbAdapter::handleStepInto(const TrkResult &result)
1255
{
1256
    m_snapshot.reset();
1257
    if (result.errorCode()) {
1258
        logMessage("ERROR: " + result.errorString() + " in handleStepInto");
hjk's avatar
hjk committed
1259
1260
1261
        // Try fallback with Step Over
        QByteArray ba = trkStepRangeMessage(0x11);  // options "step over"
        sendTrkMessage(0x19, TrkCB(handleStepInto2), ba, "Step range");
1262
1263
        return;
    }
hjk's avatar
hjk committed
1264
    // The gdb server response is triggered later by the Stop Reply packet
hjk's avatar
hjk committed
1265
1266
1267
1268
1269
1270
    logMessage("STEP INTO FINISHED ");
}

void TrkGdbAdapter::handleStepInto2(const TrkResult &result)
{
    if (result.errorCode()) {
1271
        logMessage("ERROR: " + result.errorString() + " in handleStepInto2");
hjk's avatar
hjk committed
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
        // Try fallback with Continue
        sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
        //sendGdbServerMessage("S05", "Stepping finished");
        return;
    }
    logMessage("STEP INTO FINISHED (FALLBACK)");
}

void TrkGdbAdapter::handleStepOver(const TrkResult &result)
{
1282
    m_snapshot.reset();
hjk's avatar
hjk committed
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString() + "in handleStepOver");
        // Try fallback with Step Into
        QByteArray ba = trkStepRangeMessage(0x01);  // options "step into"
        sendTrkMessage(0x19, TrkCB(handleStepOver), ba, "Step range");
        return;
    }
    logMessage("STEP OVER FINISHED ");
}

void TrkGdbAdapter::handleStepOver2(const TrkResult &result)
{
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString() + "in handleStepOver2");
        // Try fallback with Continue
        sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
        //sendGdbServerMessage("S05", "Stepping finished");
        return;
    }
    logMessage("STEP OVER FINISHED (FALLBACK)");
1303
1304
}

hjk's avatar
hjk committed
1305
void TrkGdbAdapter::handleAndReportSetBreakpoint(const TrkResult &result)
1306
1307
1308
1309
1310
{
    //---TRK------------------------------------------------------
    //  Command: 0x80 Acknowledge
    //    Error: 0x00
    // [80 09 00 00 00 00 0A]
1311
1312
1313
1314
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        return;
    }
hjk's avatar
hjk committed
1315
    uint bpnr = extractInt(result.data.data() + 1);
1316
1317
1318
1319
1320
1321
1322
1323
    uint addr = result.cookie.toUInt();
    m_session.addressToBP[addr] = bpnr;
    logMessage("SET BREAKPOINT " + hexxNumber(bpnr) + " "
         + stringFromArray(result.data.data()));
    sendGdbServerMessage("OK");
    //sendGdbServerMessage("OK");
}

hjk's avatar
hjk committed
1324
void TrkGdbAdapter::handleClearBreakpoint(const TrkResult &result)
1325
1326
1327
1328
1329
1330
1331
1332
1333
{
    logMessage("CLEAR BREAKPOINT ");
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        //return;
    } 
    sendGdbServerMessage("OK");
}

hjk's avatar
hjk committed
1334
void TrkGdbAdapter::handleSignalContinue(const TrkResult &result)
1335
1336
1337
1338
1339
1340
1341
1342
{
    int signalNumber = result.cookie.toInt();
    logMessage("   HANDLE SIGNAL CONTINUE: " + stringFromArray(result.data));
    logMessage("NUMBER" + QString::number(signalNumber));
    sendGdbServerMessage("O" + QByteArray("Console output").toHex());
    sendGdbServerMessage("W81"); // "Process exited with result 1
}

hjk's avatar
hjk committed
1343
void TrkGdbAdapter::handleSupportMask(const TrkResult &result)
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
{
    const char *data = result.data.data();
    QByteArray str;
    for (int i = 0; i < 32; ++i) {
        //str.append("  [" + formatByte(data[i]) + "]: ");
        for (int j = 0; j < 8; ++j)
        if (data[i] & (1 << j))
            str.append(QByteArray::number(i * 8 + j, 16));
    }
    logMessage("SUPPORTED: " + str);
 }

hjk's avatar
hjk committed
1356
void TrkGdbAdapter::handleTrkVersions(const TrkResult &result)
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
{
    QString logMsg;
    QTextStream str(&logMsg);
    str << "Versions: ";
    if (result.data.size() >= 5) {
        str << "Trk version " << int(result.data.at(1)) << '.'
            << int(result.data.at(2))
            << ", Protocol version " << int(result.data.at(3))
             << '.' << int(result.data.at(4));
    }
    logMessage(logMsg);
}

hjk's avatar
hjk committed
1370
void TrkGdbAdapter::handleDisconnect(const TrkResult & /*result*/)
1371
{
hjk's avatar
hjk committed
1372
    logMessage(QLatin1String("Trk disconnected"));
1373
1374
}

hjk's avatar
hjk committed
1375
void TrkGdbAdapter::readMemory(uint addr, uint len)
1376
1377
1378
1379
1380
{
    Q_ASSERT(len < (2 << 16));

    // We try to get medium-sized chunks of data from the device
    if (m_verbose > 2)
1381
        logMessage(_("readMemory %1 bytes from 0x%2 blocksize=%3")
1382
1383
1384
            .arg(len).arg(addr, 0, 16).arg(MemoryChunkSize));

    if (m_bufferedMemoryRead) {
1385
        uint requests = 0;
1386
1387
1388
1389
        uint blockaddr = (addr / MemoryChunkSize) * MemoryChunkSize;
        for (; blockaddr < addr + len; blockaddr += MemoryChunkSize) {
            if (!m_snapshot.memory.contains(blockaddr)) {
                if (m_verbose)
1390
                    logMessage(_("Requesting buffered "
1391
1392
1393
1394
1395
                        "memory %1 bytes from 0x%2")
                    .arg(MemoryChunkSize).arg(blockaddr, 0, 16));
                sendTrkMessage(0x10, TrkCB(handleReadMemoryBuffered),
                    trkReadMemoryMessage(blockaddr, MemoryChunkSize),
                    QVariant(blockaddr));
1396
                requests++;
1397
1398
            }
        }
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
        // If requests have been sent: Sync
        if (requests) {
            const qulonglong cookie = (qulonglong(addr) << 32) + len;
            sendTrkMessage(TRK_WRITE_QUEUE_NOOP_CODE, TrkCB(reportReadMemoryBuffered),
                QByteArray(), cookie);
        } else {
            // Everything is already buffered: invoke callback directly
            reportReadMemoryBuffered(addr, len);
        }
    } else { // Unbuffered, direct requests
1409
        if (m_verbose)
1410
            logMessage(_("Requesting unbuffered memory %1 "
1411
1412
1413
1414
1415
1416
                "bytes from 0x%2").arg(len).arg(addr, 0, 16));
        sendTrkMessage(0x10, TrkCB(handleReadMemoryUnbuffered),
           trkReadMemoryMessage(addr, len), QVariant(addr));
    }
}

hjk's avatar
hjk committed
1417
void TrkGdbAdapter::interruptInferior()
1418
{
hjk's avatar
hjk committed
1419
    QTC_ASSERT(state() == AdapterStarted, qDebug() << state());
1420
    qDebug() << "TRYING TO INTERRUPT INFERIOR";
1421
    sendTrkMessage(0x1a, TrkCallback(), trkInterruptMessage(), "Interrupting...");
1422
1423
}

hjk's avatar
hjk committed
1424
void TrkGdbAdapter::handleGdbError(QProcess::ProcessError error)
1425
{
1426
1427
    logMessage(QString("GDB: Process Error %1: %2")
        .arg(error).arg(m_gdbProc.errorString()));
1428
1429
}

hjk's avatar
hjk committed
1430
void TrkGdbAdapter::handleGdbFinished(int exitCode, QProcess::ExitStatus exitStatus)
1431
{
1432
1433
    logMessage(QString("GDB: ProcessFinished %1 %2")
        .arg(exitCode).arg(exitStatus));
hjk's avatar
hjk committed
1434
    setState(DebuggerNotReady);
1435
    emit adapterShutDown();
1436
1437
}

hjk's avatar
hjk committed
1438
void TrkGdbAdapter::handleGdbStarted()
1439
{
hjk's avatar
hjk committed
1440
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
hjk's avatar
hjk committed
1441
    logMessage(QString("GDB: Process Started"));
hjk's avatar
hjk committed
1442
    setState(AdapterStarted);
hjk's avatar
hjk committed
1443
    emit adapterStarted();
1444
1445
}

hjk's avatar
hjk committed
1446
void TrkGdbAdapter::handleGdbStateChanged(QProcess::ProcessState newState)
1447
{
hjk's avatar
hjk committed
1448
    logMessage(_("GDB: Process State %1").arg(newState));
1449
1450
}

1451
void TrkGdbAdapter::startAdapter()
1452
{
1453
    // Retrieve parameters
1454
    const DebuggerStartParameters &parameters = startParameters();
1455
1456
1457
    setOverrideTrkDevice(parameters.remoteChannel);
    m_remoteExecutable = parameters.executable;
    m_symbolFile = parameters.symbolFileName;
1458
    // FIXME: testing hack, remove!
1459
1460
1461
    if (parameters.processArgs.at(0) == _("@sym@")) {
        m_remoteExecutable = parameters.processArgs.at(1);
        m_symbolFile = parameters.processArgs.at(2);
1462