trkgdbadapter.cpp 59.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

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

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

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

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

hjk's avatar
hjk committed
54
#define TrkCB(s) TrkCallback(this, &TrkGdbAdapter::s)
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88


using namespace trk;

enum { KnownRegisters = RegisterPSGdb + 1};

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

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

namespace Debugger {
namespace Internal {

hjk's avatar
hjk committed
89
90
TrkGdbAdapter::TrkGdbAdapter(GdbEngine *engine, const TrkOptionsPtr &options) :
    AbstractGdbAdapter(engine),
91
92
93
94
95
96
    m_options(options),
    m_running(false),
    m_gdbAckMode(true),
    m_verbose(2),
    m_bufferedMemoryRead(true),
    m_waitCount(0)
97
{
dt's avatar
dt committed
98
#ifdef Q_OS_WIN
99
    const DWORD portOffset = GetCurrentProcessId() % 100;
dt's avatar
dt committed
100
#else
101
    const uid_t portOffset = getuid();
dt's avatar
dt committed
102
#endif
103
    m_gdbServerName = QString::fromLatin1("127.0.0.1:%1").arg(2222 + portOffset);
104
    connect(&m_gdbProc, SIGNAL(readyReadStandardError()),
hjk's avatar
hjk committed
105
        this, SIGNAL(readyReadStandardError()));
106
    connect(&m_gdbProc, SIGNAL(readyReadStandardOutput()),
hjk's avatar
hjk committed
107
        this, SIGNAL(readyReadStandardOutput()));
hjk's avatar
hjk committed
108
109
110
111
112
113
114
115
    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)));
116
117
118
119
120

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

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

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

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

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

148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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
167
void TrkGdbAdapter::trkLogMessage(const QString &msg)
168
169
170
171
{
    logMessage("TRK " + msg);
}

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

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

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

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

201
QByteArray TrkGdbAdapter::trkReadRegistersMessage()
202
203
204
205
206
207
208
209
210
211
{
    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;
}

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

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

hjk's avatar
hjk committed
235
236
237
238
239
240
241
242
243
244
245
QByteArray TrkGdbAdapter::trkStepRangeMessage(byte option)
{
    QByteArray ba;
    appendByte(&ba, option);
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // start address
    appendInt(&ba, m_snapshot.registers[RegisterPC]); // end address
    appendInt(&ba, m_session.pid);
    appendInt(&ba, m_session.tid);
    return ba;
}

hjk's avatar
hjk committed
246
void TrkGdbAdapter::startInferiorEarly()
247
{
hjk's avatar
hjk committed
248
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
249
    QString errorMessage;
250
251
    const QString device = effectiveTrkDevice();
    if (!m_trkDevice.open(device, &errorMessage)) {
hjk's avatar
hjk committed
252
        logMessage(QString::fromLatin1("Waiting on %1 (%2)").arg(device, errorMessage));
253
        // Do not loop forever
254
        if (m_waitCount++ < (m_options->mode == TrkOptions::BlueTooth ? 60 : 5)) {
hjk's avatar
hjk committed
255
            QTimer::singleShot(1000, this, SLOT(startInferiorEarly()));
256
        } else {
hjk's avatar
hjk committed
257
258
259
            QString msg = QString::fromLatin1("Failed to connect to %1 after "
                "%2 attempts").arg(device).arg(m_waitCount);
            logMessage(msg);
hjk's avatar
hjk committed
260
            setState(DebuggerNotReady);
hjk's avatar
hjk committed
261
            emit adapterStartFailed(msg);
262
        }
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        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); // ?

281
    appendString(&ba, m_remoteExecutable.toLatin1(), TargetByteOrder);
282
283
284
285
    sendTrkMessage(0x40, TrkCB(handleCreateProcess), ba); // Create Item
    //sendTrkMessage(TRK_WRITE_QUEUE_NOOP_CODE, TrkCB(startGdbServer));
}

hjk's avatar
hjk committed
286
void TrkGdbAdapter::logMessage(const QString &msg)
287
{
hjk's avatar
hjk committed
288
289
    if (m_verbose) {
#ifdef STANDALONE_RUNNER
hjk's avatar
hjk committed
290
        emit output(msg);
hjk's avatar
hjk committed
291
292
293
294
#else
        m_engine->debugMessage(msg);
#endif
    }
295
296
297
298
299
}

//
// Gdb
//
hjk's avatar
hjk committed
300
void TrkGdbAdapter::handleGdbConnection()
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
{
    logMessage("HANDLING GDB CONNECTION");

    m_gdbConnection = m_gdbServer.nextPendingConnection();
    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
316
void TrkGdbAdapter::readGdbServerCommand()
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
{
    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
383
bool TrkGdbAdapter::sendGdbServerPacket(const QByteArray &packet, bool doFlush)
384
385
386
{
    if (!m_gdbConnection) {
        logMessage(QString::fromLatin1("Cannot write to gdb: No connection (%1)")
hjk's avatar
hjk committed
387
            .arg(QString::fromLatin1(packet)));
388
389
390
391
        return false;
    }
    if (m_gdbConnection->state() != QAbstractSocket::ConnectedState) {
        logMessage(QString::fromLatin1("Cannot write to gdb: Not connected (%1)")
hjk's avatar
hjk committed
392
            .arg(QString::fromLatin1(packet)));
393
394
395
396
        return false;
    }
    if (m_gdbConnection->write(packet) == -1) {
        logMessage(QString::fromLatin1("Cannot write to gdb: %1 (%2)")
hjk's avatar
hjk committed
397
            .arg(m_gdbConnection->errorString()).arg(QString::fromLatin1(packet)));
398
399
400
401
402
403
404
        return false;
    }
    if (doFlush)
        m_gdbConnection->flush();
    return true;
}

hjk's avatar
hjk committed
405
void TrkGdbAdapter::sendGdbServerAck()
406
407
408
409
410
411
412
413
{
    if (!m_gdbAckMode)
        return;
    QByteArray packet = "+";
    logMessage("gdb: <- " + packet);
    sendGdbServerPacket(packet, false);
}

hjk's avatar
hjk committed
414
void TrkGdbAdapter::sendGdbServerMessage(const QByteArray &msg, const QByteArray &logNote)
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
{
    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
435
void TrkGdbAdapter::sendGdbServerMessageAfterTrkResponse(const QByteArray &msg,
436
437
438
439
440
441
    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
442
void TrkGdbAdapter::reportToGdb(const TrkResult &result)
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
{
    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
458
QByteArray TrkGdbAdapter::trkBreakpointMessage(uint addr, uint len, bool armMode)
459
460
461
462
463
464
465
466
467
468
469
470
{
    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
471
void TrkGdbAdapter::handleGdbServerCommand(const QByteArray &cmd)
472
473
474
475
476
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
{
    // 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
518
        sendTrkMessage(0x18, TrkCB(handleSignalContinue), ba, signalNumber);
519
520
521
522
523
524
525
526
527
    }

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

    else if (cmd == "g") {
        // Read general registers.
hjk's avatar
hjk committed
528
        logMessage(msgGdbPacket(QLatin1String("Read registers")));
529
        sendGdbServerAck();
hjk's avatar
hjk committed
530
        reportRegisters();
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
    }

    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
553
554
    else if (cmd == "k" || cmd.startsWith("vKill")) {
        // Kill inferior process
555
556
557
558
559
        logMessage(msgGdbPacket(QLatin1String("kill")));
        QByteArray ba;
        appendByte(&ba, 0); // ?
        appendByte(&ba, 0); // Sub-command: Delete Process
        appendInt(&ba, m_session.pid);
hjk's avatar
hjk committed
560
561
        sendTrkMessage(0x41, TrkCB(handleDeleteProcess),
            ba, "Delete process"); // Delete Item
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    }

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

588
589
590
591
592
593
594
595
596
597
    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
598
            appendInt(&ba, m_snapshot.registers[RegisterPSTrk], LittleEndian);
599
600
            logMsg += dumpRegister(registerNumber, m_snapshot.registers[RegisterPSTrk]);
            sendGdbServerMessage(ba.toHex(), logMsg);
hjk's avatar
hjk committed
601
        } else if (registerNumber < 16) {
602
            QByteArray ba;
hjk's avatar
hjk committed
603
            appendInt(&ba, m_snapshot.registers[registerNumber], LittleEndian);
604
605
606
            logMsg += dumpRegister(registerNumber, m_snapshot.registers[registerNumber]);
            sendGdbServerMessage(ba.toHex(), logMsg);
        } else {
hjk's avatar
hjk committed
607
608
609
            sendGdbServerMessage("0000", "read single unknown register #"
                + QByteArray::number(registerNumber));
            //sendGdbServerMessage("E01", "read single unknown register");
610
611
612
        }
    }

613
614
615
616
617
618
619
620
621
622
    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));
623
624
        // FIXME: Assume all goes well.
        m_snapshot.registers[registerNumber] = value;
625
626
627
628
629
        QByteArray ba = trkWriteRegisterMessage(registerNumber, value);
        sendTrkMessage(0x13, TrkCB(handleWriteRegister), ba, "Write register");
        // Note that App TRK refuses to write registers 13 and 14
    }

630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
    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
653
654
655
656
657
658
659
660
661
662
663
664
665
        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?");
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
    }

    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
688
689
            sendGdbServerMessage("qSymbol:" + QByteArray("_Z7E32Mainv").toHex(),
                "ask for more");
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
    }

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

    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
720
721
        QByteArray ba = trkStepRangeMessage(0x01);  // options "step into"
        sendTrkMessage(0x19, TrkCB(handleStepInto), ba, "Step range");
722
723
724
725
726
727
    }

    else if (cmd == "vCont?") {
        // actions supported by the vCont packet
        sendGdbServerAck();
        //sendGdbServerMessage("OK"); // we don't support vCont.
728
        sendGdbServerMessage("vCont;c;C;s;S");
729
730
731
732
733
734
735
736
737
738
739
    }

    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
740
        sendGdbServerAck();
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
        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;
        logMessage(QString::fromLatin1("Inserting breakpoint at 0x%1, %2")
            .arg(addr, 0, 16).arg(len));
        const QByteArray ba = trkBreakpointMessage(addr, len, m_session.pid);
        sendTrkMessage(0x1B, TrkCB(handleAndReportSetBreakpoint), ba, addr);
    }

    else if (cmd.startsWith("z0,") || cmd.startsWith("z1,")) {
        // Remove breakpoint
hjk's avatar
hjk committed
756
        sendGdbServerAck();
757
758
759
760
761
762
763
764
765
766
        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) {
            logMessage(QString::fromLatin1("NO RECORDED BP AT 0x%1, %2")
                .arg(addr, 0, 16).arg(len));
hjk's avatar
hjk committed
767
            sendGdbServerMessage("E00");
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
        } else {
            m_session.addressToBP.remove(addr);
            QByteArray ba;
            appendByte(&ba, 0x00);
            appendShort(&ba, bp);
            appendInt(&ba, addr);
            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) {
                    const QString msg = QString::fromLatin1("Read of OS auxilary "
                        "vector (%1, %2) not implemented.").arg(offset).arg(length);
hjk's avatar
hjk committed
793
                    logMessage(msgGdbPacket(msg));
794
795
796
797
798
799
800
801
                    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
802
            logMessage(msgGdbPacket(msg));
803
804
805
806
807
808
809
810
811
            sendGdbServerMessage("E20", msg.toLatin1());
        }
    } // qPart/qXfer
    else {
        logMessage(msgGdbPacket(QLatin1String("FIXME unknown: ")
            + QString::fromAscii(cmd)));
    }
}

hjk's avatar
hjk committed
812
void TrkGdbAdapter::executeCommand(const QString &msg)
813
814
815
816
817
{
    if (msg == "EI") {
        sendGdbMessage("-exec-interrupt");
    } else if (msg == "C") {
        sendTrkMessage(0x18, TrkCallback(), trkContinueMessage(), "CONTINUE");
hjk's avatar
hjk committed
818
819
820
821
    } else if (msg == "S") {
        sendTrkMessage(0x19, TrkCallback(), trkStepRangeMessage(0x01), "STEP");
    } else if (msg == "N") {
        sendTrkMessage(0x19, TrkCallback(), trkStepRangeMessage(0x11), "NEXT");
822
823
824
825
826
827
828
829
    } else if (msg == "I") {
        interruptInferior();
    } else {
        logMessage("EXECUTING GDB COMMAND " + msg);
        sendGdbMessage(msg);
    }
}

hjk's avatar
hjk committed
830
void TrkGdbAdapter::sendTrkMessage(byte code, TrkCallback callback,
831
832
833
834
835
    const QByteArray &data, const QVariant &cookie)
{
    m_trkDevice.sendTrkMessage(code, callback, data, cookie);
}

hjk's avatar
hjk committed
836
void TrkGdbAdapter::sendTrkAck(byte token)
837
{
838
    //logMessage(QString("SENDING ACKNOWLEDGEMENT FOR TOKEN %1").arg(int(token)));
839
840
841
    m_trkDevice.sendTrkAck(token);
}

hjk's avatar
hjk committed
842
void TrkGdbAdapter::handleTrkError(const QString &msg)
843
844
845
846
{
    logMessage("## TRK ERROR: " + msg);
}

hjk's avatar
hjk committed
847
void TrkGdbAdapter::handleTrkResult(const TrkResult &result)
848
849
850
851
852
853
854
855
{
    if (result.isDebugOutput) {
        sendTrkAck(result.token);
        logMessage(QLatin1String("APPLICATION OUTPUT: ") +
            QString::fromAscii(result.data));
        sendGdbServerMessage("O" + result.data.toHex());
        return;
    }
856
    //logMessage("READ TRK " + result.toString());
857
858
859
860
861
862
863
864
865
    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
866
            logMessage(logMsg);
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
            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);
            logMessage(prefix + QString::fromLatin1("NOTE: PID %1/TID %2 "
                "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
887
888
889
890
891
            // 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),
892
                trkReadRegistersMessage());
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
            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 << '\'';
            logMessage(logMsg);
            // This lets gdb trigger a register update etc
            //sendGdbServerMessage("T05library:r;");
            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);
            logMessage(QString::fromLatin1("%1 %2 UNLOAD: %3")
                .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
975
void TrkGdbAdapter::handleCpuType(const TrkResult &result)
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
{
    //---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
997
void TrkGdbAdapter::handleCreateProcess(const TrkResult &result)
998
{
hjk's avatar
hjk committed
999
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
    //  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]
    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
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
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
1037
void TrkGdbAdapter::handleReadRegisters(const TrkResult &result)
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
{
    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);
} 

1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
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
1062
void TrkGdbAdapter::reportRegisters()
1063
1064
1065
{
    QByteArray ba;
    for (int i = 0; i < 16; ++i) {
hjk's avatar
hjk committed
1066
        const uint reg = swapEndian(m_snapshot.registers[i]);
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
        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
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
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
1093
    // FIXME: those are not understood by gdb 6.4
hjk's avatar
hjk committed
1094
1095
1096
    //for (int i = 16; i < 25; ++i)
    //    appendRegister(&ba, i, 0x0);
    appendRegister(&ba, RegisterPSGdb, m_snapshot.registers[RegisterPSTrk]);
1097
    //qDebug() << "TrkGdbAdapter::handleAndReportReadRegistersAfterStop" << ba;
hjk's avatar
hjk committed
1098
1099
1100
    sendGdbServerMessage(ba, "Registers");
}

hjk's avatar
hjk committed
1101
static QString msgMemoryReadError(int code, uint addr, uint len = 0)
1102
1103
1104
1105
1106
1107
{
    const QString lenS = len ? QString::number(len) : QLatin1String("<unknown>");
    return QString::fromLatin1("Memory read error %1 at: 0x%2 %3")
        .arg(code).arg(addr, 0 ,16).arg(lenS);
}

hjk's avatar
hjk committed
1108
void TrkGdbAdapter::handleReadMemoryBuffered(const TrkResult &result)
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
{
    if (extractShort(result.data.data() + 1) + 3 != result.data.size())
        logMessage("\n BAD MEMORY RESULT: " + result.data.toHex() + "\n");
    const uint blockaddr = result.cookie.toUInt();
    if (const int errorCode = result.errorCode()) {
        logMessage(msgMemoryReadError(errorCode, blockaddr));
        return;
    }
    const QByteArray ba = result.data.mid(3);
    m_snapshot.memory.insert(blockaddr, ba);
}

// Format log message for memory access with some smartness about registers
hjk's avatar
hjk committed
1122
QByteArray TrkGdbAdapter::memoryReadLogMessage(uint addr, uint len, const QByteArray &ba) const
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
1150
1151
{
    QByteArray logMsg = "memory contents";
    if (m_verbose > 1) {
        logMsg += " addr: " + hexxNumber(addr);
        // indicate dereferencing of registers
        if (len == 4) {
            if (addr == m_snapshot.registers[RegisterPC]) {
                logMsg += "[PC]";
            } else if (addr == m_snapshot.registers[RegisterPSTrk]) {
                logMsg += "[PSTrk]";
            } else if (addr == m_snapshot.registers[RegisterSP]) {
                logMsg += "[SP]";
            } else if (addr == m_snapshot.registers[RegisterLR]) {
                logMsg += "[LR]";
            } else if (addr > m_snapshot.registers[RegisterSP] &&
                    (addr - m_snapshot.registers[RegisterSP]) < 10240) {
                logMsg += "[SP+"; // Stack area ...stack seems to be top-down
                logMsg += QByteArray::number(addr - m_snapshot.registers[RegisterSP]);
                logMsg += ']';
            }
        }
        logMsg += " length ";
        logMsg += QByteArray::number(len);
        logMsg += " :";
        logMsg += stringFromArray(ba, 16).toAscii();
    }
    return logMsg;
}

hjk's avatar
hjk committed
1152
void TrkGdbAdapter::reportReadMemoryBuffered(const TrkResult &result)
1153
1154
1155
1156
{
    const qulonglong cookie = result.cookie.toULongLong();
    const uint addr = cookie >> 32;
    const uint len = uint(cookie);
1157
1158
    reportReadMemoryBuffered(addr, len);
}
1159

1160
1161
void TrkGdbAdapter::reportReadMemoryBuffered(uint addr, uint len)
{
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
    // Gdb accepts less memory according to documentation.
    // Send E on complete failure.
    QByteArray ba;
    uint blockaddr = (addr / MemoryChunkSize) * MemoryChunkSize;
    for (; blockaddr < addr + len; blockaddr += MemoryChunkSize) {
        const Snapshot::Memory::const_iterator it = m_snapshot.memory.constFind(blockaddr);
        if (it == m_snapshot.memory.constEnd())
            break;
        ba.append(it.value());
    }
    const int previousChunkOverlap = addr % MemoryChunkSize;
    if (previousChunkOverlap != 0 && ba.size() > previousChunkOverlap)
        ba.remove(0, previousChunkOverlap);
    if (ba.size() > int(len))
        ba.truncate(len);

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

hjk's avatar
hjk committed
1186
void TrkGdbAdapter::handleReadMemoryUnbuffered(const TrkResult &result)
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
{
    //logMessage("UNBUFFERED MEMORY READ: " + stringFromArray(result.data));
    const uint blockaddr = result.cookie.toUInt();
    if (extractShort(result.data.data() + 1) + 3 != result.data.size())
        logMessage("\n BAD MEMORY RESULT: " + result.data.toHex() + "\n");
    if (const int errorCode = result.errorCode()) {
        const QByteArray ba = "E20";
        sendGdbServerMessage(ba, msgMemoryReadError(32, blockaddr).toLatin1());
    } else {
        const QByteArray ba = result.data.mid(3);
        sendGdbServerMessage(ba.toHex(), memoryReadLogMessage(blockaddr, ba.size(), ba));
    }
}

hjk's avatar
hjk committed
1201
void TrkGdbAdapter::handleStepInto(const TrkResult &result)
1202
{
1203
    m_snapshot.reset();
1204
    if (result.errorCode()) {
1205
        logMessage("ERROR: " + result.errorString() + " in handleStepInto");
hjk's avatar
hjk committed
1206
1207
1208
        // Try fallback with Step Over
        QByteArray ba = trkStepRangeMessage(0x11);  // options "step over"
        sendTrkMessage(0x19, TrkCB(handleStepInto2), ba, "Step range");
1209
1210
        return;
    }
hjk's avatar
hjk committed
1211
    // The gdb server response is triggered later by the Stop Reply packet
hjk's avatar
hjk committed
1212
1213
1214
1215
1216
1217
    logMessage("STEP INTO FINISHED ");
}

void TrkGdbAdapter::handleStepInto2(const TrkResult &result)
{
    if (result.errorCode()) {
1218
        logMessage("ERROR: " + result.errorString() + " in handleStepInto2");
hjk's avatar
hjk committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
        // 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)
{
1229
    m_snapshot.reset();
hjk's avatar
hjk committed
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
    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)");
1250
1251
}

hjk's avatar
hjk committed
1252
void TrkGdbAdapter::handleAndReportSetBreakpoint(const TrkResult &result)
1253
1254
1255
1256
1257
{
    //---TRK------------------------------------------------------
    //  Command: 0x80 Acknowledge
    //    Error: 0x00
    // [80 09 00 00 00 00 0A]
hjk's avatar
hjk committed
1258
    uint bpnr = extractInt(result.data.data() + 1);
1259
1260
1261
1262
1263
1264
1265
1266
    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
1267
void TrkGdbAdapter::handleClearBreakpoint(const TrkResult &result)
1268
1269
1270
1271
1272
1273
1274
1275
1276
{
    logMessage("CLEAR BREAKPOINT ");
    if (result.errorCode()) {
        logMessage("ERROR: " + result.errorString());
        //return;
    } 
    sendGdbServerMessage("OK");
}

hjk's avatar
hjk committed
1277
void TrkGdbAdapter::handleSignalContinue(const TrkResult &result)
1278
1279
1280
1281
1282
1283
1284
1285
{
    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
1286
void TrkGdbAdapter::handleSupportMask(const TrkResult &result)
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
{
    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
1299
void TrkGdbAdapter::handleTrkVersions(const TrkResult &result)
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
{
    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
1313
void TrkGdbAdapter::handleDisconnect(const TrkResult & /*result*/)
1314
{
hjk's avatar
hjk committed
1315
    logMessage(QLatin1String("Trk disconnected"));
1316
1317
}

hjk's avatar
hjk committed
1318
void TrkGdbAdapter::readMemory(uint addr, uint len)
1319
1320
1321
1322
1323
1324
1325
1326
1327
{
    Q_ASSERT(len < (2 << 16));

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

    if (m_bufferedMemoryRead) {
1328
        uint requests = 0;
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
        uint blockaddr = (addr / MemoryChunkSize) * MemoryChunkSize;
        for (; blockaddr < addr + len; blockaddr += MemoryChunkSize) {
            if (!m_snapshot.memory.contains(blockaddr)) {
                if (m_verbose)
                    logMessage(QString::fromLatin1("Requesting buffered "
                        "memory %1 bytes from 0x%2")
                    .arg(MemoryChunkSize).arg(blockaddr, 0, 16));
                sendTrkMessage(0x10, TrkCB(handleReadMemoryBuffered),
                    trkReadMemoryMessage(blockaddr, MemoryChunkSize),
                    QVariant(blockaddr));
1339
                requests++;
1340
1341
            }
        }
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
        // If requests have been sent: Sync
        if (requests) {
            const qulonglong cookie = (qulonglong(addr) << 32) + len;
            sendTrkMessage(TRK_WRITE_QUEUE_NOOP_CODE, TrkCB(reportReadMemoryBuffered),
                QByteArray(), cookie);
        } else {
            // Everything is already buffered: invoke callback directly
            reportReadMemoryBuffered(addr, len);
        }
    } else { // Unbuffered, direct requests
1352
1353
1354
1355
1356
1357
1358
1359
        if (m_verbose)
            logMessage(QString::fromLatin1("Requesting unbuffered memory %1 "
                "bytes from 0x%2").arg(len).arg(addr, 0, 16));
        sendTrkMessage(0x10, TrkCB(handleReadMemoryUnbuffered),
           trkReadMemoryMessage(addr, len), QVariant(addr));
    }
}

hjk's avatar
hjk committed
1360
void TrkGdbAdapter::interruptInferior()
1361
{
hjk's avatar
hjk committed
1362
    QTC_ASSERT(state() == AdapterStarted, qDebug() << state());
1363
    qDebug() << "TRYING TO INTERRUPT INFERIOR";
1364
1365
1366
1367
1368
1369
1370
1371
1372
    QByteArray ba;
    // 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.
    sendTrkMessage(0x1a, TrkCallback(), ba, "Interrupting...");
}

hjk's avatar
hjk committed
1373
void TrkGdbAdapter::handleGdbError(QProcess::ProcessError error)
1374
{
1375
1376
    logMessage(QString("GDB: Process Error %1: %2")
        .arg(error).arg(m_gdbProc.errorString()));
1377
1378
}

hjk's avatar
hjk committed
1379
void TrkGdbAdapter::handleGdbFinished(int exitCode, QProcess::ExitStatus exitStatus)
1380
{
1381
1382
    logMessage(QString("GDB: ProcessFinished %1 %2")
        .arg(exitCode).arg(exitStatus));
hjk's avatar
hjk committed
1383
    setState(DebuggerNotReady);
1384
    emit adapterShutDown();
1385
1386
}

hjk's avatar
hjk committed
1387
void TrkGdbAdapter::handleGdbStarted()
1388
{
hjk's avatar
hjk committed
1389
    QTC_ASSERT(state() == AdapterStarting, qDebug() << state());
hjk's avatar
hjk committed
1390
    logMessage(QString("GDB: Process Started"));
hjk's avatar
hjk committed
1391
    setState(AdapterStarted);
hjk's avatar
hjk committed
1392
    emit adapterStarted();
1393
1394
}

hjk's avatar
hjk committed
1395
void TrkGdbAdapter::handleGdbStateChanged(QProcess::ProcessState newState)
1396
{
hjk's avatar
hjk committed
1397
    logMessage(_("GDB: Process State %1").arg(newState));
1398
1399
}

1400
void TrkGdbAdapter::startAdapter()
1401
{
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
    // Retrieve parameters
    const DebuggerStartParameters &parameters = m_engine->startParameters();
    setOverrideTrkDevice(parameters.remoteChannel);
    m_remoteExecutable = parameters.executable;
    m_symbolFile = parameters.symbolFileName;
    // @todo: testing hack, remove!
    if (m_remoteExecutable.endsWith(_(".sym"))) {
        m_symbolFile = m_remoteExecutable;
        m_remoteExecutable = QLatin1String("C:\\sys\\bin\\filebrowseapp.exe");
    }
    // Start
hjk's avatar
hjk committed
1413
    QTC_ASSERT(state() == EngineStarting, qDebug() << state());
hjk's avatar
hjk committed
1414
1415
    setState(AdapterStarting);
    debugMessage(_("TRYING TO START ADAPTER"));
hjk's avatar
hjk committed
1416
    logMessage(QLatin1String("### Starting TrkGdbAdapter"));
1417
1418
1419
    if (m_options->mode == TrkOptions::BlueTooth) {
        const QString device = effectiveTrkDevice();
        const QString blueToothListener = QLatin1String("rfcomm");
hjk's avatar
hjk committed
1420
1421
1422
1423
1424
1425
1426
1427
1428
        QStringList blueToothListenerArguments;
        blueToothListenerArguments.append(_("-r"));
        blueToothListenerArguments.append(_("listen"));
        blueToothListenerArguments.append(m_options->blueToothDevice);
        blueToothListenerArguments.append(_("1"));
        logMessage(_("### Starting BlueTooth listener %1 on %2: %3 %4")
            .arg(blueToothListener).arg(device).arg(blueToothListener)
            .arg(blueToothListenerArguments.join(" ")));
        m_rfcommProc.start(blueToothListener, blueToothListenerArguments);
1429
1430
        m_rfcommProc.waitForStarted();
        if (m_rfcommProc.state() != QProcess::Running) {
hjk's avatar
hjk committed
1431
1432
1433
1434
1435
            QString msg = QString::fromLatin1("Failed to start BlueTooth "
                "listener %1 on %2: %3\n");
            msg = msg.arg(blueToothListener, device, m_rfcommProc.errorString());
            msg += QString::fromLocal8Bit(m_rfcommProc.readAllStandardError());
            emit adapterStartFailed(msg);
1436
1437
            return;
        }
hjk's avatar
hjk committed
1438
    }
1439
    m_waitCount = 0;
1440

hjk's avatar
hjk committed
1441
1442
1443
1444
1445
    startInferiorEarly();
}

void TrkGdbAdapter::prepareInferior()
{
hjk's avatar
hjk committed
1446
1447
1448
1449
    QTC_ASSERT(state() == AdapterStarted, qDebug() << state());
    // We already started the inferior process during the adapter start.
    // Now make gdb aware of it.
    setState(InferiorPreparing);
1450
1451
1452
1453
1454
1455
1456
1457
    const QString fileName = m_symbolFile;
    if (m_symbolFile.isEmpty()) {
        logMessage(QString::fromLatin1("WARNING: No symbol file available."));
    } else {
        m_engine->postCommand(_("add-symbol-file \"%1\" %2").arg(m_symbolFile)
                              .arg(m_session.codeseg));
        m_engine->postCommand(_("symbol-file \"%1\"").arg(m_symbolFile));
    }
hjk's avatar
hjk committed
1458
1459
1460
1461
    m_engine->postCommand(_("target remote ") + gdbServerName(),
        CB(handleTargetRemote));
}

hjk's avatar
hjk committed
1462
void TrkGdbAdapter::handleTargetRemote(const GdbResponse &record)
hjk's avatar
hjk committed
1463
1464
1465
1466
1467
1468
{
    QTC_ASSERT(state() == InferiorPreparing, qDebug() << state());
    if (record.resultClass == GdbResultDone) {
        setState(InferiorPrepared);
        emit inferiorPrepared();
    } else if (record.resultClass == GdbResultError) {
1469
1470
1471
        QString msg = tr("Connecting to trk server adapter failed:\n")
            + _(record.data.findChild("msg").data());
        emit inferiorPreparationFailed(msg);
hjk's avatar
hjk committed
1472
    }
hjk's avatar
hjk committed
1473
1474
1475
1476
}

void TrkGdbAdapter::startInferior()
{
hjk's avatar
hjk committed
1477
1478
    QTC_ASSERT(state() == InferiorStarting, qDebug() << state());
    setState(InferiorRunningRequested);
hjk's avatar
hjk committed
1479
1480
1481
    m_engine->postCommand(_("-exec-continue"), CB(handleFirstContinue));
}

hjk's avatar
hjk committed
1482
void TrkGdbAdapter::handleFirstContinue(const GdbResponse &record)
hjk's avatar
hjk committed
1483
{
hjk's avatar
hjk committed
1484
    QTC_ASSERT(state() == InferiorRunningRequested, qDebug() << state());
hjk's avatar
hjk committed
1485
    if (record.resultClass == GdbResultDone) {
1486
1487
        debugMessage(_("INFERIOR STARTED"));
        showStatusMessage(tr("Inferior running."));
hjk's avatar
hjk committed
1488
1489
1490
1491
1492
    } else if (record.resultClass == GdbResultError) {
        //QString msg = __(record.data.findChild("msg").data());
        QString msg1 = tr("Connecting to remote server failed:");
        emit inferiorStartFailed(msg1 + record.toString());
    }
1493
1494
}

1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
#ifdef Q_OS_WIN

// Prepend environment of the Symbian Gdb by Cygwin '/bin'
static void setGdbCygwinEnvironment(const QString &cygwin, QProcess *process)
{
    if (cygwin.isEmpty() || !QFileInfo(cygwin).isDir())
        return;
    const QString cygwinBinPath = QDir::toNativeSeparators(cygwin) + QLatin1String("\\bin");
    QStringList env = process->environment();
    if (env.isEmpty())
        env = QProcess::systemEnvironment();
1506
    const QRegExp pathPattern(QLatin1String("^PATH=.*"), Qt::CaseInsensitive);
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
    const int index = env.indexOf(pathPattern);
    if (index == -1)
        return;
    QString pathValue