trkgdbadapter.cpp 68.7 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 "trkoptionspage.h"
33
#include "debuggerstringutils.h"
hjk's avatar
hjk committed
34
#ifndef STANDALONE_RUNNER
35
#include "gdbengine.h"
hjk's avatar
hjk committed
36
#endif
hjk's avatar
hjk committed
37
38
39
#ifdef Q_OS_WIN
#  include <windows.h>
#else
40
41
42
#  include <sys/types.h>
#  include <unistd.h>
#endif
43

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

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

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

hjk's avatar
hjk committed
53
#define TrkCB(s) TrkCallback(this, &TrkGdbAdapter::s)
54

55
56
57
58
59
60
61
//#define DEBUG_MEMORY  1
#if DEBUG_MEMORY
#   define MEMORY_DEBUG(s) qDebug() << s
#else
#   define MEMORY_DEBUG(s)
#endif
#define MEMORY_DEBUGX(s) qDebug() << s
62
63
64

using namespace trk;

65
66
67
namespace Debugger {
namespace Internal {

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
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;
}

95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
QDebug operator<<(QDebug d, MemoryRange range)
{
    return d << QString("[%1,%2] (size %3) ")
        .arg(range.from, 0, 16).arg(range.to, 0, 16).arg(range.size());
}

///////////////////////////////////////////////////////////////////////////
//
// MemoryRange
//
///////////////////////////////////////////////////////////////////////////

bool MemoryRange::intersects(const MemoryRange &other) const
{
    Q_UNUSED(other);
    return false; // FIXME
}

void MemoryRange::operator-=(const MemoryRange &other)
{
    if (from == 0 && to == 0)
        return;
    MEMORY_DEBUG("      SUB: "  << *this << " - " << other);
    if (other.from <= from && to <= other.to) {
        from = to = 0;
        return;
    }
    if (other.from <= from && other.to <= to) {
        from = qMax(from, other.to);
        return;
    }
    if (from <= other.from && to <= other.to) {
        to = qMin(other.from, to);
        return;
    }
    // This would split the range.
    QTC_ASSERT(false, qDebug() << "Memory::operator-() not handled for: "
        << *this << " - " << other);
}

///////////////////////////////////////////////////////////////////////////
//
// Snapshot
//
///////////////////////////////////////////////////////////////////////////

void Snapshot::reset()
{
    memory.clear();
    for (int i = 0; i < RegisterCount; ++i)
        registers[i] = 0;
    wantedMemory = MemoryRange();
}

void Snapshot::insertMemory(const MemoryRange &range, const QByteArray &ba)
{
    QTC_ASSERT(range.size() == ba.size(),
        qDebug() << "RANGE: " << range << " BA SIZE: " << ba.size(); return);
    
    MEMORY_DEBUG("INSERT: " << range);
    // Try to combine with existing chunk.
    Snapshot::Memory::iterator it = memory.begin();
    Snapshot::Memory::iterator et = memory.end();
    for ( ; it != et; ++it) {
        if (range.from == it.key().to) {
            MEMORY_DEBUG("COMBINING " << it.key() << " AND " << range);
            QByteArray data = *it;
            data.append(ba);
            memory.remove(it.key());
            memory.insert(MemoryRange(it.key().from, range.to), data);
            MEMORY_DEBUG(" TO  " << MemoryRange(it.key().from, range.to));
            return;
        }
        if (it.key().from == range.to) {
            MEMORY_DEBUG("COMBINING " << range << " AND " << it.key());
            QByteArray data = ba;
            data.append(*it);
            memory.remove(it.key());
            memory.insert(MemoryRange(range.from, it.key().to), data);
            MEMORY_DEBUG(" TO  " << MemoryRange(range.from, it.key().to));
            return;
        }
    }

    // Not combinable, add chunk.
    memory.insert(range, ba);
}

///////////////////////////////////////////////////////////////////////////
//
// TrkGdbAdapter
//
///////////////////////////////////////////////////////////////////////////
188

hjk's avatar
hjk committed
189
190
TrkGdbAdapter::TrkGdbAdapter(GdbEngine *engine, const TrkOptionsPtr &options) :
    AbstractGdbAdapter(engine),
191
192
193
194
    m_options(options),
    m_running(false),
    m_gdbAckMode(true),
    m_verbose(2),
195
    m_bufferedMemoryRead(true),
196
    m_waitCount(0)
197
{
hjk's avatar
hjk committed
198
199
    m_gdbServer = 0;
    m_gdbConnection = 0;
dt's avatar
dt committed
200
#ifdef Q_OS_WIN
201
    const DWORD portOffset = GetCurrentProcessId() % 100;
dt's avatar
dt committed
202
#else
203
    const uid_t portOffset = getuid();
dt's avatar
dt committed
204
#endif
205
    m_gdbServerName = _("127.0.0.1:%1").arg(2222 + portOffset);
206
207

    commonInit();
hjk's avatar
hjk committed
208
209
    connect(&m_gdbProc, SIGNAL(stateChanged(QProcess::ProcessState)),
        this, SLOT(handleGdbStateChanged(QProcess::ProcessState)));
210
211
212
213
214

    connect(&m_rfcommProc, SIGNAL(readyReadStandardError()),
        this, SLOT(handleRfcommReadyReadStandardError()));
    connect(&m_rfcommProc, SIGNAL(readyReadStandardOutput()),
        this, SLOT(handleRfcommReadyReadStandardOutput()));
215
    connect(&m_rfcommProc, SIGNAL(error(QProcess::ProcessError)),
hjk's avatar
hjk committed
216
        this, SLOT(handleRfcommError(QProcess::ProcessError)));
217
    connect(&m_rfcommProc, SIGNAL(finished(int, QProcess::ExitStatus)),
hjk's avatar
hjk committed
218
        this, SLOT(handleRfcommFinished(int, QProcess::ExitStatus)));
219
    connect(&m_rfcommProc, SIGNAL(started()),
hjk's avatar
hjk committed
220
        this, SLOT(handleRfcommStarted()));
221
    connect(&m_rfcommProc, SIGNAL(stateChanged(QProcess::ProcessState)),
hjk's avatar
hjk committed
222
        this, SLOT(handleRfcommStateChanged(QProcess::ProcessState)));
223

hjk's avatar
hjk committed
224
225
226
227
228
    connect(&m_trkDevice, SIGNAL(messageReceived(trk::TrkResult)),
        this, SLOT(handleTrkResult(trk::TrkResult)));
    connect(&m_trkDevice, SIGNAL(error(QString)),
        this, SLOT(handleTrkError(QString)));

229
    m_trkDevice.setVerbose(m_verbose);
230
    m_trkDevice.setSerialFrame(m_options->mode != TrkOptions::BlueTooth);
231
232
233
234
235

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

hjk's avatar
hjk committed
236
TrkGdbAdapter::~TrkGdbAdapter()
237
{
Friedemann Kleint's avatar
Friedemann Kleint committed
238
    cleanup();
hjk's avatar
hjk committed
239
    logMessage("Shutting down.\n");
240
241
}

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
261
void TrkGdbAdapter::trkLogMessage(const QString &msg)
262
263
264
265
{
    logMessage("TRK " + msg);
}

hjk's avatar
hjk committed
266
void TrkGdbAdapter::setGdbServerName(const QString &name)
267
268
269
270
{
    m_gdbServerName = name;
}

hjk's avatar
hjk committed
271
QString TrkGdbAdapter::gdbServerIP() const
272
273
274
275
276
277
278
{
    int pos = m_gdbServerName.indexOf(':');
    if (pos == -1)
        return m_gdbServerName;
    return m_gdbServerName.left(pos);
}

hjk's avatar
hjk committed
279
uint TrkGdbAdapter::gdbServerPort() const
280
281
282
283
284
285
286
{
    int pos = m_gdbServerName.indexOf(':');
    if (pos == -1)
        return 0;
    return m_gdbServerName.mid(pos + 1).toUInt();
}

hjk's avatar
hjk committed
287
QByteArray TrkGdbAdapter::trkContinueMessage()
288
289
290
291
292
293
294
{
    QByteArray ba;
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

295
QByteArray TrkGdbAdapter::trkReadRegistersMessage()
296
297
298
299
300
301
302
303
304
305
{
    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;
}

306
307
308
309
310
311
312
313
314
315
316
317
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;
}

318
QByteArray TrkGdbAdapter::trkReadMemoryMessage(uint from, uint len)
319
320
{
    QByteArray ba;
321
    ba.reserve(11);
322
323
    appendByte(&ba, 0x08); // Options, FIXME: why?
    appendShort(&ba, len);
324
    appendInt(&ba, from);
325
326
327
328
329
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

330
331
332
333
334
QByteArray TrkGdbAdapter::trkReadMemoryMessage(const MemoryRange &range)
{
    return trkReadMemoryMessage(range.from, range.size());
}

hjk's avatar
hjk committed
335
336
337
338
339
340
341
342
343
344
345
346
347
QByteArray TrkGdbAdapter::trkWriteMemoryMessage(uint addr, const QByteArray &data)
{
    QByteArray ba;
    ba.reserve(11 + data.size());
    appendByte(&ba, 0x08); // Options, FIXME: why?
    appendShort(&ba, data.size());
    appendInt(&ba, addr);
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    ba.append(data);
    return ba;
}

hjk's avatar
hjk committed
348
349
350
QByteArray TrkGdbAdapter::trkStepRangeMessage(byte option)
{
    QByteArray ba;
hjk's avatar
hjk committed
351
    ba.reserve(17);
hjk's avatar
hjk committed
352
    appendByte(&ba, option);
hjk's avatar
hjk committed
353
    qDebug() << "STEP ON " << hexxNumber(m_snapshot.registers[RegisterPC]);
354
355
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // Start address
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // End address
hjk's avatar
hjk committed
356
357
358
359
360
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
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;
}

Friedemann Kleint's avatar
Friedemann Kleint committed
383
384
385
386
387
388
389
390
void TrkGdbAdapter::emitDelayedAdapterStartFailed(const QString &msg)
{
    m_adapterFailMessage = msg;
    QTimer::singleShot(0, this, SLOT(slotEmitDelayedAdapterStartFailed()));
}

void TrkGdbAdapter::slotEmitDelayedAdapterStartFailed()
{
391
    emit adapterStartFailed(m_adapterFailMessage, TrkOptionsPage::settingsId());
Friedemann Kleint's avatar
Friedemann Kleint committed
392
393
}

394
395
396
397
398
399
400
401
402
403
404
void TrkGdbAdapter::emitDelayedInferiorStartFailed(const QString &msg)
{
    m_adapterFailMessage = msg;
    QTimer::singleShot(0, this, SLOT(slotEmitDelayedInferiorStartFailed()));
}

void TrkGdbAdapter::slotEmitDelayedInferiorStartFailed()
{
    emit inferiorStartFailed(m_adapterFailMessage);
}

405
void TrkGdbAdapter::waitForTrkConnect()
406
{
hjk's avatar
hjk committed
407
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
408
    QString errorMessage;
409
410
    const QString device = effectiveTrkDevice();
    if (!m_trkDevice.open(device, &errorMessage)) {
411
412
413
414
415
        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")
416
                .arg(QChar("/-\\|"[direction])));
417
        }
418
        // Do not loop forever
419
        if (m_waitCount++ < (m_options->mode == TrkOptions::BlueTooth ? 60 : 5)) {
420
            QTimer::singleShot(1000, this, SLOT(waitForTrkConnect()));
421
        } else {
422
            QString msg = _("Failed to connect to %1 after "
hjk's avatar
hjk committed
423
424
                "%2 attempts").arg(device).arg(m_waitCount);
            logMessage(msg);
425
            emit adapterStartFailed(msg, TrkOptionsPage::settingsId());
426
        }
427
428
429
430
431
432
433
434
435
436
437
438
439
        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

440
    maybeAdapterStarted();
441
442
}

hjk's avatar
hjk committed
443
void TrkGdbAdapter::logMessage(const QString &msg)
444
{
hjk's avatar
hjk committed
445
446
    if (m_verbose) {
#ifdef STANDALONE_RUNNER
hjk's avatar
hjk committed
447
        emit output(msg);
hjk's avatar
hjk committed
448
449
450
451
#else
        m_engine->debugMessage(msg);
#endif
    }
452
453
454
455
456
}

//
// Gdb
//
hjk's avatar
hjk committed
457
void TrkGdbAdapter::handleGdbConnection()
458
459
{
    logMessage("HANDLING GDB CONNECTION");
hjk's avatar
hjk committed
460
461
462
    QTC_ASSERT(m_gdbConnection == 0, /**/);
    m_gdbConnection = m_gdbServer->nextPendingConnection();
    QTC_ASSERT(m_gdbConnection, return);
463
464
465
466
467
468
469
470
471
472
473
    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
474
void TrkGdbAdapter::readGdbServerCommand()
475
{
hjk's avatar
hjk committed
476
    QTC_ASSERT(m_gdbConnection, return);
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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
    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
542
bool TrkGdbAdapter::sendGdbServerPacket(const QByteArray &packet, bool doFlush)
543
544
{
    if (!m_gdbConnection) {
545
546
        logMessage(_("Cannot write to gdb: No connection (%1)")
            .arg(_(packet)));
547
548
549
        return false;
    }
    if (m_gdbConnection->state() != QAbstractSocket::ConnectedState) {
550
551
        logMessage(_("Cannot write to gdb: Not connected (%1)")
            .arg(_(packet)));
552
553
554
        return false;
    }
    if (m_gdbConnection->write(packet) == -1) {
555
556
        logMessage(_("Cannot write to gdb: %1 (%2)")
            .arg(m_gdbConnection->errorString()).arg(_(packet)));
557
558
559
560
561
562
563
        return false;
    }
    if (doFlush)
        m_gdbConnection->flush();
    return true;
}

hjk's avatar
hjk committed
564
void TrkGdbAdapter::sendGdbServerAck()
565
566
567
568
569
570
571
572
{
    if (!m_gdbAckMode)
        return;
    QByteArray packet = "+";
    logMessage("gdb: <- " + packet);
    sendGdbServerPacket(packet, false);
}

hjk's avatar
hjk committed
573
void TrkGdbAdapter::sendGdbServerMessage(const QByteArray &msg, const QByteArray &logNote)
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
{
    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
594
void TrkGdbAdapter::sendGdbServerMessageAfterTrkResponse(const QByteArray &msg,
595
596
597
598
599
600
    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
601
void TrkGdbAdapter::reportToGdb(const TrkResult &result)
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
{
    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
617
QByteArray TrkGdbAdapter::trkBreakpointMessage(uint addr, uint len, bool armMode)
618
619
620
621
622
623
624
625
626
627
628
629
{
    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
630
void TrkGdbAdapter::handleGdbServerCommand(const QByteArray &cmd)
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
{
    // 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
677
        sendTrkMessage(0x18, TrkCB(handleSignalContinue), ba, signalNumber);
678
679
680
681
682
683
684
685
686
    }

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

    else if (cmd == "g") {
        // Read general registers.
hjk's avatar
hjk committed
687
        logMessage(msgGdbPacket(QLatin1String("Read registers")));
688
        sendGdbServerAck();
hjk's avatar
hjk committed
689
        reportRegisters();
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
    }

    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
712
713
    else if (cmd == "k" || cmd.startsWith("vKill")) {
        // Kill inferior process
714
        logMessage(msgGdbPacket(QLatin1String("kill")));
hjk's avatar
hjk committed
715
        sendTrkMessage(0x41, TrkCB(handleDeleteProcess),
716
            trkDeleteProcessMessage(), "Delete process"); 
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    }

    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) {
737
            readMemory(addr, len, m_bufferedMemoryRead);
738
739
740
741
        } else {
            sendGdbServerMessage("E20", "Error " + cmd);
        }
    }
742

743
744
745
746
747
748
749
750
751
752
    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
753
            appendInt(&ba, m_snapshot.registers[RegisterPSTrk], LittleEndian);
754
755
            logMsg += dumpRegister(registerNumber, m_snapshot.registers[RegisterPSTrk]);
            sendGdbServerMessage(ba.toHex(), logMsg);
hjk's avatar
hjk committed
756
        } else if (registerNumber < 16) {
757
            QByteArray ba;
hjk's avatar
hjk committed
758
            appendInt(&ba, m_snapshot.registers[registerNumber], LittleEndian);
759
760
761
            logMsg += dumpRegister(registerNumber, m_snapshot.registers[registerNumber]);
            sendGdbServerMessage(ba.toHex(), logMsg);
        } else {
hjk's avatar
hjk committed
762
763
764
            sendGdbServerMessage("0000", "read single unknown register #"
                + QByteArray::number(registerNumber));
            //sendGdbServerMessage("E01", "read single unknown register");
765
766
767
        }
    }

768
769
770
771
772
773
774
775
776
777
    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));
778
779
        // FIXME: Assume all goes well.
        m_snapshot.registers[registerNumber] = value;
780
781
782
783
784
        QByteArray ba = trkWriteRegisterMessage(registerNumber, value);
        sendTrkMessage(0x13, TrkCB(handleWriteRegister), ba, "Write register");
        // Note that App TRK refuses to write registers 13 and 14
    }

785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
    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
808
809
810
811
812
813
814
815
816
817
818
819
820
        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?");
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
    }

    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
843
844
            sendGdbServerMessage("qSymbol:" + QByteArray("_Z7E32Mainv").toHex(),
                "ask for more");
845
846
847
848
849
850
851
852
    }

    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>");
    }

853
854
855
856
857
858
859
860
861
862
863
    else if (cmd.startsWith("qXfer:libraries:read")) {
        sendGdbServerAck();
        /*
            <library-list>
              <library name="/lib/libc.so.6">
                <segment address="0x10000000"/>
              </library>
            </library-list>
i        */
    }

864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    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
886
887
        QByteArray ba = trkStepRangeMessage(0x01);  // options "step into"
        sendTrkMessage(0x19, TrkCB(handleStepInto), ba, "Step range");
888
889
890
891
892
893
    }

    else if (cmd == "vCont?") {
        // actions supported by the vCont packet
        sendGdbServerAck();
        //sendGdbServerMessage("OK"); // we don't support vCont.
894
        sendGdbServerMessage("vCont;c;C;s;S");
895
896
897
898
899
900
901
902
903
904
905
    }

    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
906
        sendGdbServerAck();
907
908
909
910
911
912
913
        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;
914
        logMessage(_("Inserting breakpoint at 0x%1, %2")
915
            .arg(addr, 0, 16).arg(len));
916
        const QByteArray ba = trkBreakpointMessage(addr, len, len == 4);
917
918
919
920
921
        sendTrkMessage(0x1B, TrkCB(handleAndReportSetBreakpoint), ba, addr);
    }

    else if (cmd.startsWith("z0,") || cmd.startsWith("z1,")) {
        // Remove breakpoint
hjk's avatar
hjk committed
922
        sendGdbServerAck();
923
924
925
926
927
928
929
930
        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) {
931
            logMessage(_("NO RECORDED BP AT 0x%1, %2")
932
                .arg(addr, 0, 16).arg(len));
hjk's avatar
hjk committed
933
            sendGdbServerMessage("E00");
934
935
936
        } else {
            m_session.addressToBP.remove(addr);
            QByteArray ba;
937
            appendInt(&ba, bp);
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
            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) {
955
                    const QString msg = _("Read of OS auxilary "
956
                        "vector (%1, %2) not implemented.").arg(offset).arg(length);
hjk's avatar
hjk committed
957
                    logMessage(msgGdbPacket(msg));
958
959
960
961
962
963
964
965
                    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
966
            logMessage(msgGdbPacket(msg));
967
968
969
970
971
972
973
974
975
            sendGdbServerMessage("E20", msg.toLatin1());
        }
    } // qPart/qXfer
    else {
        logMessage(msgGdbPacket(QLatin1String("FIXME unknown: ")
            + QString::fromAscii(cmd)));
    }
}

hjk's avatar
hjk committed
976
void TrkGdbAdapter::sendTrkMessage(byte code, TrkCallback callback,
977
978
979
980
981
    const QByteArray &data, const QVariant &cookie)
{
    m_trkDevice.sendTrkMessage(code, callback, data, cookie);
}

hjk's avatar
hjk committed
982
void TrkGdbAdapter::sendTrkAck(byte token)
983
{
984
    //logMessage(QString("SENDING ACKNOWLEDGEMENT FOR TOKEN %1").arg(int(token)));
985
986
987
    m_trkDevice.sendTrkAck(token);
}

hjk's avatar
hjk committed
988
void TrkGdbAdapter::handleTrkError(const QString &msg)
989
990
991
992
{
    logMessage("## TRK ERROR: " + msg);
}

hjk's avatar
hjk committed
993
void TrkGdbAdapter::handleTrkResult(const TrkResult &result)
994
995
996
997
998
999
1000
1001
{
    if (result.isDebugOutput) {
        sendTrkAck(result.token);
        logMessage(QLatin1String("APPLICATION OUTPUT: ") +
            QString::fromAscii(result.data));
        sendGdbServerMessage("O" + result.data.toHex());
        return;
    }
1002
    //logMessage("READ TRK " + result.toString());
1003
1004
1005
1006
1007
1008
1009
1010
1011
    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
1012
            logMessage(logMsg);
1013
1014
1015
1016
1017
1018
1019
1020
            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);
1021
            logMessage(prefix + _("NOTE: PID %1/TID %2 "
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
                "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
1033
1034
1035
1036
1037
            // 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),
1038
                trkReadRegistersMessage());
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
            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 << '\'';
1074
1075
1076
1077
1078
            Library lib;
            lib.name = name;
            lib.codeseg = codeseg;
            lib.dataseg = dataseg;
            m_session.libraries.append(lib);
1079
            logMessage(logMsg);
1080
1081
1082
1083
            // 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:;");
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
            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);
1095
            logMessage(_("%1 %2 UNLOAD: %3")
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
                .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
1128
void TrkGdbAdapter::handleCpuType(const TrkResult &result)
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
{
    //---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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
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
1166
void TrkGdbAdapter::handleReadRegisters(const TrkResult &result)
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
{
    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);
} 

1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
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
1191
void TrkGdbAdapter::reportRegisters()
1192
1193
1194
{
    QByteArray ba;
    for (int i = 0; i < 16; ++i) {
hjk's avatar
hjk committed
1195
        const uint reg = swapEndian(m_snapshot.registers[i]);
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
        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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
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
1222
    // FIXME: those are not understood by gdb 6.4
hjk's avatar
hjk committed
1223
1224
1225
    //for (int i = 16; i < 25; ++i)
    //    appendRegister(&ba, i, 0x0);
    appendRegister(&ba, RegisterPSGdb, m_snapshot.registers[RegisterPSTrk]);
1226
    //qDebug() << "TrkGdbAdapter::handleAndReportReadRegistersAfterStop" << ba;
hjk's avatar
hjk committed
1227
1228
1229
    sendGdbServerMessage(ba, "Registers");
}

hjk's avatar
hjk committed
1230
static QString msgMemoryReadError(int code, uint addr, uint len = 0)
1231
1232
{
    const QString lenS = len ? QString::number(len) : QLatin1String("<unknown>");
1233
    return _("Memory read error %1 at: 0x%2 %3")
1234
1235
1236
1237
        .arg(code).arg(addr, 0 ,16).arg(lenS);
}

// Format log message for memory access with some smartness about registers
1238
QByteArray TrkGdbAdapter::memoryReadLogMessage(uint addr, const QByteArray &ba) const
1239
1240
1241
1242
1243
{
    QByteArray logMsg = "memory contents";
    if (m_verbose > 1) {
        logMsg += " addr: " + hexxNumber(addr);
        // indicate dereferencing of registers
1244
        if (ba.size() == 4) {
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
            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 ";
1261
        logMsg += QByteArray::number(ba.size());
1262
1263
1264
1265
1266
1267
        logMsg += " :";
        logMsg += stringFromArray(ba, 16).toAscii();
    }
    return logMsg;
}

1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
void TrkGdbAdapter::handleReadMemoryBuffered(const TrkResult &result)
{
    if (extractShort(result.data.data() + 1) + 3 != result.data.size())
        logMessage("\n BAD MEMORY RESULT: " + result.data.toHex() + "\n");
    const MemoryRange range = result.cookie.value<MemoryRange>();
    if (const int errorCode = result.errorCode()) {
        logMessage(_("TEMPORARY: ") + msgMemoryReadError(errorCode, range.from));
        logMessage(_("RETRYING UNBUFFERED"));
        // FIXME: This does not handle large requests properly.
        sendTrkMessage(0x10, TrkCB(handleReadMemoryUnbuffered),
            trkReadMemoryMessage(range), QVariant::fromValue(range));
        return;
    }
    const QByteArray ba = result.data.mid(3);
    m_snapshot.insertMemory(range, ba);
    tryAnswerGdbMemoryRequest(true);
}

void TrkGdbAdapter::handleReadMemoryUnbuffered(const TrkResult &result)
1287
{
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
    if (extractShort(result.data.data() + 1) + 3 != result.data.size())
        logMessage("\n BAD MEMORY RESULT: " + result.data.toHex() + "\n");
    const MemoryRange range = result.cookie.value<MemoryRange>();
    if (const int errorCode = result.errorCode()) {
        logMessage(_("TEMPORARY: ") + msgMemoryReadError(errorCode, range.from));
        logMessage(_("RETRYING UNBUFFERED"));
        const QByteArray ba = "E20";
        sendGdbServerMessage(ba, msgMemoryReadError(32, range.from).toLatin1());
        return;
    }
    const QByteArray ba = result.data.mid(3);
    m_snapshot.insertMemory(range, ba);
    tryAnswerGdbMemoryRequest(false);
1301
}
1302

1303
void TrkGdbAdapter::tryAnswerGdbMemoryRequest(bool buffered)
1304
{
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
    //logMessage("UNBUFFERED MEMORY READ: " + stringFromArray(result.data));

    MemoryRange wanted = m_snapshot.wantedMemory;
    MemoryRange needed = m_snapshot.wantedMemory;
    MEMORY_DEBUG("WANTED: " << wanted);
    Snapshot::Memory::const_iterator it = m_snapshot.memory.begin();
    Snapshot::Memory::const_iterator et = m_snapshot.memory.end();
    for ( ; it != et; ++it) {
        MEMORY_DEBUG("   NEEDED: " << needed);
        needed -= it.key(); 
    }
    MEMORY_DEBUG("NEEDED: " << needed);

    if (needed.to == 0) {
        // FIXME: need to combine chunks first.

        // All fine. Send package to gdb.
        it = m_snapshot.memory.begin();
        et = m_snapshot.memory.end();
        for ( ; it != et; ++it) {
            if (it.key().from <= wanted.from && wanted.to <= it.key().to) {
                int offset = wanted.from - it.key().from;
                int len = wanted.to - wanted.from;
                QByteArray ba = it.value().mid(offset, len);
                sendGdbServerMessage(ba.toHex(), memoryReadLogMessage(wanted.from, ba));
                return;
            }
        }
        // Happens when chunks are not comnbined
        QTC_ASSERT(false, /**/);
        return;
    }

    MEMORY_DEBUG("NEEDED AND UNSATISFIED: " << needed);
    if (buffered) {
        uint blockaddr = (needed.from / MemoryChunkSize) * MemoryChunkSize;
        logMessage(_("Requesting buffered memory %1 bytes from 0x%2")
            .arg(MemoryChunkSize).arg(blockaddr, 0, 16));
        MemoryRange range(blockaddr, blockaddr + MemoryChunkSize);
        MEMORY_DEBUGX("   FETCH MEMORY : " << range);
        sendTrkMessage(0x10, TrkCB(handleReadMemoryBuffered),
            trkReadMemoryMessage(range),
            QVariant::fromValue(range));
    } else { // Unbuffered, direct requests
        int len = needed.to - needed.from;
        logMessage(_("Requesting unbuffered memory %1 bytes from 0x%2")
            .arg(len).arg(needed.from, 0, 16));
        sendTrkMessage(0x10, TrkCB(handleReadMemoryUnbuffered),
            trkReadMemoryMessage(needed),
            QVariant::fromValue(needed));
        MEMORY_DEBUGX("   FETCH MEMORY : " << needed);
    }
}

/*
void TrkGdbAdapter::reportReadMemoryBuffered(const TrkResult &result)
{
    const MemoryRange range = result.cookie.value<MemoryRange>();
1363
1364
1365
    // Gdb accepts less memory according to documentation.
    // Send E on complete failure.
    QByteArray ba;
1366
    uint blockaddr = (range.from / MemoryChunkSize) * MemoryChunkSize;
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
    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));
    }
}
1386
*/
1387

hjk's avatar
hjk committed
1388
void TrkGdbAdapter::handleStepInto(const TrkResult &result)
1389
{
1390
    m_snapshot.reset();
1391
    if (result.errorCode()) {
1392
        logMessage("ERROR: " + result.errorString() + " in handleStepInto");
hjk's avatar
hjk committed
1393
1394
1395
        // Try fallback with Step Over
        QByteArray ba = trkStepRangeMessage(0x11);  // options "step over"
        sendTrkMessage(0x19, TrkCB(handleStepInto2), ba, "Step range");
1396
1397
        return;
    }
hjk's avatar
hjk committed
1398
    // The gdb server response is triggered later by the Stop Reply packet
hjk's avatar
hjk committed
1399
1400
1401
1402
1403
1404
    logMessage("STEP INTO FINISHED ");
}

void TrkGdbAdapter::handleStepInto2(const TrkResult &result)
{
    if (result.errorCode()) {
1405
        logMessage("ERROR: " + result.errorString() + " in handleStepInto2");
hjk's avatar
hjk committed
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
        // 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)
{
1416
    m_snapshot.reset();
hjk's avatar
hjk committed
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
    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)");
1437
1438
}

hjk's avatar
hjk committed
1439
void TrkGdbAdapter::handleAndReportSetBreakpoint(const TrkResult &result)
1440
1441
1442
1443
1444
{
    //---TRK------------------------------------------------------
    //  Command: 0x80 Acknowledge
    //    Error: 0x00
    // [80 09 00 00 00 00 0A]
1445
1446
1447
1448
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        return;
    }
hjk's avatar
hjk committed
1449
    uint bpnr = extractInt(result.data.data() + 1);
1450
1451
1452
1453
1454
1455
1456
1457
    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
1458
void TrkGdbAdapter::handleClearBreakpoint(const TrkResult &result)
1459
1460
1461
1462
1463
1464
1465
1466
1467
{
    logMessage("CLEAR BREAKPOINT ");
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        //return;
    } 
    sendGdbServerMessage("OK");
}

hjk's avatar
hjk committed
1468
void TrkGdbAdapter::handleSignalContinue(const TrkResult &result)
1469
1470
1471
1472
1473
1474
1475
1476
{
    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
1477
void TrkGdbAdapter::handleSupportMask(const TrkResult &result)
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
{
    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
1490
void TrkGdbAdapter::handleTrkVersions(const TrkResult &result)
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
{
    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
1504
void TrkGdbAdapter::handleDisconnect(const TrkResult & /*result*/)
1505
{
hjk's avatar
hjk committed
1506
    logMessage(QLatin1String("Trk disconnected"));