trkgdbadapter.cpp 71.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
    connect(&m_gdbProc, SIGNAL(readyReadStandardError()),
hjk's avatar
hjk committed
207
        this, SIGNAL(readyReadStandardError()));
208
    connect(&m_gdbProc, SIGNAL(readyReadStandardOutput()),
hjk's avatar
hjk committed
209
        this, SIGNAL(readyReadStandardOutput()));
hjk's avatar
hjk committed
210
211
212
213
214
215
216
217
    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)));
218
219
220
221
222

    connect(&m_rfcommProc, SIGNAL(readyReadStandardError()),
        this, SLOT(handleRfcommReadyReadStandardError()));
    connect(&m_rfcommProc, SIGNAL(readyReadStandardOutput()),
        this, SLOT(handleRfcommReadyReadStandardOutput()));
223
    connect(&m_rfcommProc, SIGNAL(error(QProcess::ProcessError)),
hjk's avatar
hjk committed
224
        this, SLOT(handleRfcommError(QProcess::ProcessError)));
225
    connect(&m_rfcommProc, SIGNAL(finished(int, QProcess::ExitStatus)),
hjk's avatar
hjk committed
226
        this, SLOT(handleRfcommFinished(int, QProcess::ExitStatus)));
227
    connect(&m_rfcommProc, SIGNAL(started()),
hjk's avatar
hjk committed
228
        this, SLOT(handleRfcommStarted()));
229
    connect(&m_rfcommProc, SIGNAL(stateChanged(QProcess::ProcessState)),
hjk's avatar
hjk committed
230
        this, SLOT(handleRfcommStateChanged(QProcess::ProcessState)));
231

hjk's avatar
hjk committed
232
233
234
235
236
    connect(&m_trkDevice, SIGNAL(messageReceived(trk::TrkResult)),
        this, SLOT(handleTrkResult(trk::TrkResult)));
    connect(&m_trkDevice, SIGNAL(error(QString)),
        this, SLOT(handleTrkError(QString)));

237
    m_trkDevice.setVerbose(m_verbose);
238
    m_trkDevice.setSerialFrame(m_options->mode != TrkOptions::BlueTooth);
239
240
241
242
243

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

hjk's avatar
hjk committed
244
TrkGdbAdapter::~TrkGdbAdapter()
245
{
Friedemann Kleint's avatar
Friedemann Kleint committed
246
    cleanup();
hjk's avatar
hjk committed
247
    logMessage("Shutting down.\n");
248
249
}

250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
269
void TrkGdbAdapter::trkLogMessage(const QString &msg)
270
271
272
273
{
    logMessage("TRK " + msg);
}

hjk's avatar
hjk committed
274
void TrkGdbAdapter::setGdbServerName(const QString &name)
275
276
277
278
{
    m_gdbServerName = name;
}

hjk's avatar
hjk committed
279
QString TrkGdbAdapter::gdbServerIP() const
280
281
282
283
284
285
286
{
    int pos = m_gdbServerName.indexOf(':');
    if (pos == -1)
        return m_gdbServerName;
    return m_gdbServerName.left(pos);
}

hjk's avatar
hjk committed
287
uint TrkGdbAdapter::gdbServerPort() const
288
289
290
291
292
293
294
{
    int pos = m_gdbServerName.indexOf(':');
    if (pos == -1)
        return 0;
    return m_gdbServerName.mid(pos + 1).toUInt();
}

hjk's avatar
hjk committed
295
QByteArray TrkGdbAdapter::trkContinueMessage()
296
297
298
299
300
301
302
{
    QByteArray ba;
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

303
QByteArray TrkGdbAdapter::trkReadRegistersMessage()
304
305
306
307
308
309
310
311
312
313
{
    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;
}

314
315
316
317
318
319
320
321
322
323
324
325
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;
}

326
QByteArray TrkGdbAdapter::trkReadMemoryMessage(uint from, uint len)
327
328
{
    QByteArray ba;
329
    ba.reserve(11);
330
331
    appendByte(&ba, 0x08); // Options, FIXME: why?
    appendShort(&ba, len);
332
    appendInt(&ba, from);
333
334
335
336
337
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

338
339
340
341
342
QByteArray TrkGdbAdapter::trkReadMemoryMessage(const MemoryRange &range)
{
    return trkReadMemoryMessage(range.from, range.size());
}

hjk's avatar
hjk committed
343
344
345
346
347
348
349
350
351
352
353
354
355
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
356
357
358
QByteArray TrkGdbAdapter::trkStepRangeMessage(byte option)
{
    QByteArray ba;
hjk's avatar
hjk committed
359
    ba.reserve(17);
hjk's avatar
hjk committed
360
    appendByte(&ba, option);
hjk's avatar
hjk committed
361
    qDebug() << "STEP ON " << hexxNumber(m_snapshot.registers[RegisterPC]);
362
363
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // Start address
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // End address
hjk's avatar
hjk committed
364
365
366
367
368
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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
391
392
393
394
395
396
397
398
void TrkGdbAdapter::emitDelayedAdapterStartFailed(const QString &msg)
{
    m_adapterFailMessage = msg;
    QTimer::singleShot(0, this, SLOT(slotEmitDelayedAdapterStartFailed()));
}

void TrkGdbAdapter::slotEmitDelayedAdapterStartFailed()
{
399
    emit adapterStartFailed(m_adapterFailMessage, TrkOptionsPage::settingsId());
Friedemann Kleint's avatar
Friedemann Kleint committed
400
401
}

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

442
    appendString(&ba, m_remoteExecutable.toLatin1(), TargetByteOrder);
443
444
445
446
    sendTrkMessage(0x40, TrkCB(handleCreateProcess), ba); // Create Item
    //sendTrkMessage(TRK_WRITE_QUEUE_NOOP_CODE, TrkCB(startGdbServer));
}

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

//
// Gdb
//
hjk's avatar
hjk committed
461
void TrkGdbAdapter::handleGdbConnection()
462
463
{
    logMessage("HANDLING GDB CONNECTION");
hjk's avatar
hjk committed
464
465
466
    QTC_ASSERT(m_gdbConnection == 0, /**/);
    m_gdbConnection = m_gdbServer->nextPendingConnection();
    QTC_ASSERT(m_gdbConnection, return);
467
468
469
470
471
472
473
474
475
476
477
    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
478
void TrkGdbAdapter::readGdbServerCommand()
479
{
hjk's avatar
hjk committed
480
    QTC_ASSERT(m_gdbConnection, return);
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
542
543
544
545
    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
546
bool TrkGdbAdapter::sendGdbServerPacket(const QByteArray &packet, bool doFlush)
547
548
{
    if (!m_gdbConnection) {
549
550
        logMessage(_("Cannot write to gdb: No connection (%1)")
            .arg(_(packet)));
551
552
553
        return false;
    }
    if (m_gdbConnection->state() != QAbstractSocket::ConnectedState) {
554
555
        logMessage(_("Cannot write to gdb: Not connected (%1)")
            .arg(_(packet)));
556
557
558
        return false;
    }
    if (m_gdbConnection->write(packet) == -1) {
559
560
        logMessage(_("Cannot write to gdb: %1 (%2)")
            .arg(m_gdbConnection->errorString()).arg(_(packet)));
561
562
563
564
565
566
567
        return false;
    }
    if (doFlush)
        m_gdbConnection->flush();
    return true;
}

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

hjk's avatar
hjk committed
577
void TrkGdbAdapter::sendGdbServerMessage(const QByteArray &msg, const QByteArray &logNote)
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
{
    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
598
void TrkGdbAdapter::sendGdbServerMessageAfterTrkResponse(const QByteArray &msg,
599
600
601
602
603
604
    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
605
void TrkGdbAdapter::reportToGdb(const TrkResult &result)
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
{
    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
621
QByteArray TrkGdbAdapter::trkBreakpointMessage(uint addr, uint len, bool armMode)
622
623
624
625
626
627
628
629
630
631
632
633
{
    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
634
void TrkGdbAdapter::handleGdbServerCommand(const QByteArray &cmd)
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
677
678
679
680
{
    // 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
681
        sendTrkMessage(0x18, TrkCB(handleSignalContinue), ba, signalNumber);
682
683
684
685
686
687
688
689
690
    }

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

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

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

    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) {
741
            readMemory(addr, len, m_bufferedMemoryRead);
742
743
744
745
        } else {
            sendGdbServerMessage("E20", "Error " + cmd);
        }
    }
746

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

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

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

    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
847
848
            sendGdbServerMessage("qSymbol:" + QByteArray("_Z7E32Mainv").toHex(),
                "ask for more");
849
850
851
852
853
854
855
856
    }

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

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

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

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

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

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

hjk's avatar
hjk committed
980
void TrkGdbAdapter::executeCommand(const QString &msg)
981
982
983
984
985
{
    if (msg == "EI") {
        sendGdbMessage("-exec-interrupt");
    } else if (msg == "C") {
        sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
hjk's avatar
hjk committed
986
987
988
989
    } else if (msg == "S") {
        sendTrkMessage(0x19, TrkCallback(), trkStepRangeMessage(0x01), "STEP");
    } else if (msg == "N") {
        sendTrkMessage(0x19, TrkCallback(), trkStepRangeMessage(0x11), "NEXT");
990
991
992
993
994
995
996
997
    } else if (msg == "I") {
        interruptInferior();
    } else {
        logMessage("EXECUTING GDB COMMAND " + msg);
        sendGdbMessage(msg);
    }
}

hjk's avatar
hjk committed
998
void TrkGdbAdapter::sendTrkMessage(byte code, TrkCallback callback,
999
1000
1001
1002
1003
    const QByteArray &data, const QVariant &cookie)
{
    m_trkDevice.sendTrkMessage(code, callback, data, cookie);
}

hjk's avatar
hjk committed
1004
void TrkGdbAdapter::sendTrkAck(byte token)
1005
{
1006
    //logMessage(QString("SENDING ACKNOWLEDGEMENT FOR TOKEN %1").arg(int(token)));
1007
1008
1009
    m_trkDevice.sendTrkAck(token);
}

hjk's avatar
hjk committed
1010
void TrkGdbAdapter::handleTrkError(const QString &msg)
1011
1012
1013
1014
{
    logMessage("## TRK ERROR: " + msg);
}

hjk's avatar
hjk committed
1015
void TrkGdbAdapter::handleTrkResult(const TrkResult &result)
1016
1017
1018
1019
1020
1021
1022
1023
{
    if (result.isDebugOutput) {
        sendTrkAck(result.token);
        logMessage(QLatin1String("APPLICATION OUTPUT: ") +
            QString::fromAscii(result.data));
        sendGdbServerMessage("O" + result.data.toHex());
        return;
    }
1024
    //logMessage("READ TRK " + result.toString());
1025
1026
1027
1028
1029
1030
1031
1032
1033
    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
1034
            logMessage(logMsg);
1035
1036
1037
1038
1039
1040
1041
1042
            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);
1043
            logMessage(prefix + _("NOTE: PID %1/TID %2 "
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
                "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
1055
1056
1057
1058
1059
            // 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),
1060
                trkReadRegistersMessage());
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
            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 << '\'';
1096
1097
1098
1099
1100
            Library lib;
            lib.name = name;
            lib.codeseg = codeseg;
            lib.dataseg = dataseg;
            m_session.libraries.append(lib);
1101
            logMessage(logMsg);
1102
1103
1104
1105
            // 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:;");
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
            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);
1117
            logMessage(_("%1 %2 UNLOAD: %3")
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
                .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
1150
void TrkGdbAdapter::handleCpuType(const TrkResult &result)
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
{
    //---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
1172
void TrkGdbAdapter::handleCreateProcess(const TrkResult &result)
1173
{
hjk's avatar
hjk committed
1174
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
1175
1176
1177
    //  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
1178
1179
1180
1181
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        QString msg = _("Cannot start executable \"%1\" on the device:\n%2")
            .arg(m_remoteExecutable).arg(result.errorString());
Friedemann Kleint's avatar
Friedemann Kleint committed
1182
1183
1184
        // Delay cleanup as not to close a trk device from its read handler,
        // which blocks.
        emitDelayedAdapterStartFailed(msg);
hjk's avatar
hjk committed
1185
1186
        return;
    }
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
    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
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
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
1221
void TrkGdbAdapter::handleReadRegisters(const TrkResult &result)
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
{
    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);
} 

1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
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
1246
void TrkGdbAdapter::reportRegisters()
1247
1248
1249
{
    QByteArray ba;
    for (int i = 0; i < 16; ++i) {
hjk's avatar
hjk committed
1250
        const uint reg = swapEndian(m_snapshot.registers[i]);
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
        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
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
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
1277
    // FIXME: those are not understood by gdb 6.4
hjk's avatar
hjk committed
1278
1279
1280
    //for (int i = 16; i < 25; ++i)
    //    appendRegister(&ba, i, 0x0);
    appendRegister(&ba, RegisterPSGdb, m_snapshot.registers[RegisterPSTrk]);
1281
    //qDebug() << "TrkGdbAdapter::handleAndReportReadRegistersAfterStop" << ba;
hjk's avatar
hjk committed
1282
1283
1284
    sendGdbServerMessage(ba, "Registers");
}

hjk's avatar
hjk committed
1285
static QString msgMemoryReadError(int code, uint addr, uint len = 0)
1286
1287
{
    const QString lenS = len ? QString::number(len) : QLatin1String("<unknown>");
1288
    return _("Memory read error %1 at: 0x%2 %3")
1289
1290
1291
1292
        .arg(code).arg(addr, 0 ,16).arg(lenS);
}

// Format log message for memory access with some smartness about registers
1293
QByteArray TrkGdbAdapter::memoryReadLogMessage(uint addr, const QByteArray &ba) const
1294
1295
1296
1297
1298
{
    QByteArray logMsg = "memory contents";
    if (m_verbose > 1) {
        logMsg += " addr: " + hexxNumber(addr);
        // indicate dereferencing of registers
1299
        if (ba.size() == 4) {
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
            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 ";
1316
        logMsg += QByteArray::number(ba.size());
1317
1318
1319
1320
1321
1322
        logMsg += " :";
        logMsg += stringFromArray(ba, 16).toAscii();
    }
    return logMsg;
}

1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
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)
1342
{
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
    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);
1356
}
1357

1358
void TrkGdbAdapter::tryAnswerGdbMemoryRequest(bool buffered)
1359
{
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
    //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>();
1418
1419
1420
    // Gdb accepts less memory according to documentation.
    // Send E on complete failure.
    QByteArray ba;
1421
    uint blockaddr = (range.from / MemoryChunkSize) * MemoryChunkSize;
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
    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));
    }
}
1441
*/
1442

hjk's avatar
hjk committed
1443
void TrkGdbAdapter::handleStepInto(const TrkResult &result)
1444
{
1445
    m_snapshot.reset();
1446
    if (result.errorCode()) {
1447
        logMessage("ERROR: " + result.errorString() + " in handleStepInto");
hjk's avatar
hjk committed
1448
1449
1450
        // Try fallback with Step Over
        QByteArray ba = trkStepRangeMessage(0x11);  // options "step over"
        sendTrkMessage(0x19, TrkCB(handleStepInto2), ba, "Step range");
1451
1452
        return;
    }
hjk's avatar
hjk committed
1453
    // The gdb server response is triggered later by the Stop Reply packet
hjk's avatar
hjk committed
1454
1455
1456
1457
1458
1459
    logMessage("STEP INTO FINISHED ");
}

void TrkGdbAdapter::handleStepInto2(const TrkResult &result)
{
    if (result.errorCode()) {
1460
        logMessage("ERROR: " + result.errorString() + " in handleStepInto2");
hjk's avatar
hjk committed
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
        // 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)
{
1471
    m_snapshot.reset();
hjk's avatar
hjk committed
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
    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)");
1492
1493
}

hjk's avatar
hjk committed
1494
void TrkGdbAdapter::handleAndReportSetBreakpoint(const TrkResult &result)
1495
1496
1497
1498
1499
{
    //---TRK------------------------------------------------------
    //  Command: 0x80 Acknowledge
    //    Error: 0x00
    // [80 09 00 00 00 00 0A]
1500
1501
1502
1503
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        return;
    }
hjk's avatar
hjk committed
1504
    uint bpnr = extractInt(result.data.data() + 1);
1505
1506
1507
1508
1509
1510
1511
1512
    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
1513
void TrkGdbAdapter::handleClearBreakpoint(const TrkResult &result)
1514
1515
1516
1517
1518
1519
1520
1521
1522
{
    logMessage("CLEAR BREAKPOINT ");
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        //return;
    } 
    sendGdbServerMessage("OK");
}

hjk's avatar
hjk committed
1523
void TrkGdbAdapter::handleSignalContinue(const TrkResult &result)
1524
1525
1526
1527
1528
1529
1530
1531
{
    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
1532
void TrkGdbAdapter::handleSupportMask(const TrkResult &result)
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
{
    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
1545
void TrkGdbAdapter::handleTrkVersions(const TrkResult &result)
1546