remote_gdb.cc revision 5499:8bfc7650c344
1/*
2 * Copyright (c) 2002-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Nathan Binkert
29 */
30
31/*
32 * Copyright (c) 1990, 1993
33 *	The Regents of the University of California.  All rights reserved.
34 *
35 * This software was developed by the Computer Systems Engineering group
36 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
37 * contributed to Berkeley.
38 *
39 * All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
41 *	This product includes software developed by the University of
42 *	California, Lawrence Berkeley Laboratories.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 *    notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 *    notice, this list of conditions and the following disclaimer in the
51 *    documentation and/or other materials provided with the distribution.
52 * 3. All advertising materials mentioning features or use of this software
53 *    must display the following acknowledgement:
54 *	This product includes software developed by the University of
55 *	California, Berkeley and its contributors.
56 * 4. Neither the name of the University nor the names of its contributors
57 *    may be used to endorse or promote products derived from this software
58 *    without specific prior written permission.
59 *
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
71 *
72 *	@(#)kgdb_stub.c	8.4 (Berkeley) 1/12/94
73 */
74
75/*-
76 * Copyright (c) 2001 The NetBSD Foundation, Inc.
77 * All rights reserved.
78 *
79 * This code is derived from software contributed to The NetBSD Foundation
80 * by Jason R. Thorpe.
81 *
82 * Redistribution and use in source and binary forms, with or without
83 * modification, are permitted provided that the following conditions
84 * are met:
85 * 1. Redistributions of source code must retain the above copyright
86 *    notice, this list of conditions and the following disclaimer.
87 * 2. Redistributions in binary form must reproduce the above copyright
88 *    notice, this list of conditions and the following disclaimer in the
89 *    documentation and/or other materials provided with the distribution.
90 * 3. All advertising materials mentioning features or use of this software
91 *    must display the following acknowledgement:
92 *	This product includes software developed by the NetBSD
93 *	Foundation, Inc. and its contributors.
94 * 4. Neither the name of The NetBSD Foundation nor the names of its
95 *    contributors may be used to endorse or promote products derived
96 *    from this software without specific prior written permission.
97 *
98 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
99 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
100 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
101 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
102 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
103 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
104 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
105 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
106 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
107 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
108 * POSSIBILITY OF SUCH DAMAGE.
109 */
110
111/*
112 * $NetBSD: kgdb_stub.c,v 1.8 2001/07/07 22:58:00 wdk Exp $
113 *
114 * Taken from NetBSD
115 *
116 * "Stub" to allow remote cpu to debug over a serial line using gdb.
117 */
118
119#include <sys/signal.h>
120
121#include <string>
122#include <unistd.h>
123
124#include "config/full_system.hh"
125
126#if FULL_SYSTEM
127#include "arch/vtophys.hh"
128#endif
129
130#include "base/intmath.hh"
131#include "base/remote_gdb.hh"
132#include "base/socket.hh"
133#include "base/trace.hh"
134#include "cpu/thread_context.hh"
135#include "cpu/static_inst.hh"
136//#include "mem/physical.hh"
137#include "mem/port.hh"
138#include "mem/translating_port.hh"
139#include "sim/system.hh"
140
141using namespace std;
142using namespace TheISA;
143
144#ifndef NDEBUG
145vector<BaseRemoteGDB *> debuggers;
146
147void
148debugger()
149{
150    static int current_debugger = -1;
151    if (current_debugger >= 0 && current_debugger < debuggers.size()) {
152        BaseRemoteGDB *gdb = debuggers[current_debugger];
153        if (!gdb->isattached())
154            gdb->listener->accept();
155        if (gdb->isattached())
156            gdb->trap(SIGILL);
157    }
158}
159#endif
160
161///////////////////////////////////////////////////////////
162//
163//
164//
165
166GDBListener::Event::Event(GDBListener *l, int fd, int e)
167    : PollEvent(fd, e), listener(l)
168{}
169
170void
171GDBListener::Event::process(int revent)
172{
173    listener->accept();
174}
175
176GDBListener::GDBListener(BaseRemoteGDB *g, int p)
177    : event(NULL), gdb(g), port(p)
178{
179    assert(!gdb->listener);
180    gdb->listener = this;
181}
182
183GDBListener::~GDBListener()
184{
185    if (event)
186        delete event;
187}
188
189string
190GDBListener::name()
191{
192    return gdb->name() + ".listener";
193}
194
195void
196GDBListener::listen()
197{
198    while (!listener.listen(port, true)) {
199        DPRINTF(GDBMisc, "Can't bind port %d\n", port);
200        port++;
201    }
202
203    event = new Event(this, listener.getfd(), POLLIN);
204    pollQueue.schedule(event);
205
206#ifndef NDEBUG
207    gdb->number = debuggers.size();
208    debuggers.push_back(gdb);
209#endif
210
211#ifndef NDEBUG
212    ccprintf(cerr, "%d: %s: listening for remote gdb #%d on port %d\n",
213             curTick, name(), gdb->number, port);
214#else
215    ccprintf(cerr, "%d: %s: listening for remote gdb on port %d\n",
216             curTick, name(), port);
217#endif
218}
219
220void
221GDBListener::accept()
222{
223    if (!listener.islistening())
224        panic("GDBListener::accept(): cannot accept if we're not listening!");
225
226    int sfd = listener.accept(true);
227
228    if (sfd != -1) {
229        if (gdb->isattached())
230            close(sfd);
231        else
232            gdb->attach(sfd);
233    }
234}
235
236BaseRemoteGDB::Event::Event(BaseRemoteGDB *g, int fd, int e)
237    : PollEvent(fd, e), gdb(g)
238{}
239
240void
241BaseRemoteGDB::Event::process(int revent)
242{
243    if (revent & POLLIN)
244        gdb->trap(SIGILL);
245    else if (revent & POLLNVAL)
246        gdb->detach();
247}
248
249BaseRemoteGDB::BaseRemoteGDB(System *_system, ThreadContext *c, size_t cacheSize)
250    : event(NULL), listener(NULL), number(-1), fd(-1),
251      active(false), attached(false),
252      system(_system), pmem(_system->physmem), context(c),
253      gdbregs(cacheSize)
254{
255    memset(gdbregs.regs, 0, gdbregs.bytes());
256}
257
258BaseRemoteGDB::~BaseRemoteGDB()
259{
260    if (event)
261        delete event;
262}
263
264string
265BaseRemoteGDB::name()
266{
267    return system->name() + ".remote_gdb";
268}
269
270bool
271BaseRemoteGDB::isattached()
272{ return attached; }
273
274void
275BaseRemoteGDB::attach(int f)
276{
277    fd = f;
278
279    event = new Event(this, fd, POLLIN);
280    pollQueue.schedule(event);
281
282    attached = true;
283    DPRINTFN("remote gdb attached\n");
284}
285
286void
287BaseRemoteGDB::detach()
288{
289    attached = false;
290    close(fd);
291    fd = -1;
292
293    pollQueue.remove(event);
294    DPRINTFN("remote gdb detached\n");
295}
296
297const char *
298BaseRemoteGDB::gdb_command(char cmd)
299{
300    switch (cmd) {
301      case GDBSignal: return "KGDB_SIGNAL";
302      case GDBSetBaud: return "KGDB_SET_BAUD";
303      case GDBSetBreak: return "KGDB_SET_BREAK";
304      case GDBCont: return "KGDB_CONT";
305      case GDBAsyncCont: return "KGDB_ASYNC_CONT";
306      case GDBDebug: return "KGDB_DEBUG";
307      case GDBDetach: return "KGDB_DETACH";
308      case GDBRegR: return "KGDB_REG_R";
309      case GDBRegW: return "KGDB_REG_W";
310      case GDBSetThread: return "KGDB_SET_THREAD";
311      case GDBCycleStep: return "KGDB_CYCLE_STEP";
312      case GDBSigCycleStep: return "KGDB_SIG_CYCLE_STEP";
313      case GDBKill: return "KGDB_KILL";
314      case GDBMemW: return "KGDB_MEM_W";
315      case GDBMemR: return "KGDB_MEM_R";
316      case GDBSetReg: return "KGDB_SET_REG";
317      case GDBReadReg: return "KGDB_READ_REG";
318      case GDBQueryVar: return "KGDB_QUERY_VAR";
319      case GDBSetVar: return "KGDB_SET_VAR";
320      case GDBReset: return "KGDB_RESET";
321      case GDBStep: return "KGDB_STEP";
322      case GDBAsyncStep: return "KGDB_ASYNC_STEP";
323      case GDBThreadAlive: return "KGDB_THREAD_ALIVE";
324      case GDBTargetExit: return "KGDB_TARGET_EXIT";
325      case GDBBinaryDload: return "KGDB_BINARY_DLOAD";
326      case GDBClrHwBkpt: return "KGDB_CLR_HW_BKPT";
327      case GDBSetHwBkpt: return "KGDB_SET_HW_BKPT";
328      case GDBStart: return "KGDB_START";
329      case GDBEnd: return "KGDB_END";
330      case GDBGoodP: return "KGDB_GOODP";
331      case GDBBadP: return "KGDB_BADP";
332      default: return "KGDB_UNKNOWN";
333    }
334}
335
336/////////////////////////
337//
338//
339
340uint8_t
341BaseRemoteGDB::getbyte()
342{
343    uint8_t b;
344    ::read(fd, &b, 1);
345    return b;
346}
347
348void
349BaseRemoteGDB::putbyte(uint8_t b)
350{
351    ::write(fd, &b, 1);
352}
353
354// Send a packet to gdb
355void
356BaseRemoteGDB::send(const char *bp)
357{
358    const char *p;
359    uint8_t csum, c;
360
361    DPRINTF(GDBSend, "send:  %s\n", bp);
362
363    do {
364        p = bp;
365        //Start sending a packet
366        putbyte(GDBStart);
367        //Send the contents, and also keep a check sum.
368        for (csum = 0; (c = *p); p++) {
369            putbyte(c);
370            csum += c;
371        }
372        //Send the ending character.
373        putbyte(GDBEnd);
374        //Sent the checksum.
375        putbyte(i2digit(csum >> 4));
376        putbyte(i2digit(csum));
377        //Try transmitting over and over again until the other end doesn't send an
378        //error back.
379    } while ((c = getbyte() & 0x7f) == GDBBadP);
380}
381
382// Receive a packet from gdb
383int
384BaseRemoteGDB::recv(char *bp, int maxlen)
385{
386    char *p;
387    int c, csum;
388    int len;
389
390    do {
391        p = bp;
392        csum = len = 0;
393        //Find the beginning of a packet
394        while ((c = getbyte()) != GDBStart)
395            ;
396
397        //Read until you find the end of the data in the packet, and keep
398        //track of the check sum.
399        while ((c = getbyte()) != GDBEnd && len < maxlen) {
400            c &= 0x7f;
401            csum += c;
402            *p++ = c;
403            len++;
404        }
405
406        //Mask the check sum, and terminate the command string.
407        csum &= 0xff;
408        *p = '\0';
409
410        //If the command was too long, report an error.
411        if (len >= maxlen) {
412            putbyte(GDBBadP);
413            continue;
414        }
415
416        //Bring in the checksum. If the check sum matches, csum will be 0.
417        csum -= digit2i(getbyte()) * 16;
418        csum -= digit2i(getbyte());
419
420        //If the check sum was correct
421        if (csum == 0) {
422            //Report that the packet was received correctly
423            putbyte(GDBGoodP);
424            // Sequence present?
425            if (bp[2] == ':') {
426                putbyte(bp[0]);
427                putbyte(bp[1]);
428                len -= 3;
429                memcpy(bp, bp+3, len);
430            }
431            break;
432        }
433        //Otherwise, report that there was a mistake.
434        putbyte(GDBBadP);
435    } while (1);
436
437    DPRINTF(GDBRecv, "recv:  %s: %s\n", gdb_command(*bp), bp);
438
439    return (len);
440}
441
442// Read bytes from kernel address space for debugger.
443bool
444BaseRemoteGDB::read(Addr vaddr, size_t size, char *data)
445{
446    static Addr lastaddr = 0;
447    static size_t lastsize = 0;
448
449    if (vaddr < 10) {
450      DPRINTF(GDBRead, "read:  reading memory location zero!\n");
451      vaddr = lastaddr + lastsize;
452    }
453
454    DPRINTF(GDBRead, "read:  addr=%#x, size=%d", vaddr, size);
455
456#if FULL_SYSTEM
457    VirtualPort *port = context->getVirtPort();
458#else
459    TranslatingPort *port = context->getMemPort();
460#endif
461    port->readBlob(vaddr, (uint8_t*)data, size);
462
463#if TRACING_ON
464    if (DTRACE(GDBRead)) {
465        if (DTRACE(GDBExtra)) {
466            char buf[1024];
467            mem2hex(buf, data, size);
468            DPRINTFNR(": %s\n", buf);
469        } else
470            DPRINTFNR("\n");
471    }
472#endif
473
474    return true;
475}
476
477// Write bytes to kernel address space for debugger.
478bool
479BaseRemoteGDB::write(Addr vaddr, size_t size, const char *data)
480{
481    static Addr lastaddr = 0;
482    static size_t lastsize = 0;
483
484    if (vaddr < 10) {
485      DPRINTF(GDBWrite, "write: writing memory location zero!\n");
486      vaddr = lastaddr + lastsize;
487    }
488
489    if (DTRACE(GDBWrite)) {
490        DPRINTFN("write: addr=%#x, size=%d", vaddr, size);
491        if (DTRACE(GDBExtra)) {
492            char buf[1024];
493            mem2hex(buf, data, size);
494            DPRINTFNR(": %s\n", buf);
495        } else
496            DPRINTFNR("\n");
497    }
498#if FULL_SYSTEM
499    VirtualPort *port = context->getVirtPort();
500#else
501    TranslatingPort *port = context->getMemPort();
502#endif
503    port->writeBlob(vaddr, (uint8_t*)data, size);
504#if !FULL_SYSTEM
505    delete port;
506#endif
507
508    return true;
509}
510
511PCEventQueue *BaseRemoteGDB::getPcEventQueue()
512{
513    return &system->pcEventQueue;
514}
515
516BaseRemoteGDB::HardBreakpoint::HardBreakpoint(BaseRemoteGDB *_gdb, Addr pc)
517    : PCEvent(_gdb->getPcEventQueue(), "HardBreakpoint Event", pc),
518      gdb(_gdb), refcount(0)
519{
520    DPRINTF(GDBMisc, "creating hardware breakpoint at %#x\n", evpc);
521}
522
523void
524BaseRemoteGDB::HardBreakpoint::process(ThreadContext *tc)
525{
526    DPRINTF(GDBMisc, "handling hardware breakpoint at %#x\n", pc());
527
528    if (tc == gdb->context)
529        gdb->trap(SIGTRAP);
530}
531
532bool
533BaseRemoteGDB::insertSoftBreak(Addr addr, size_t len)
534{
535    if (len != sizeof(TheISA::MachInst))
536        panic("invalid length\n");
537
538    return insertHardBreak(addr, len);
539}
540
541bool
542BaseRemoteGDB::removeSoftBreak(Addr addr, size_t len)
543{
544    if (len != sizeof(MachInst))
545        panic("invalid length\n");
546
547    return removeHardBreak(addr, len);
548}
549
550bool
551BaseRemoteGDB::insertHardBreak(Addr addr, size_t len)
552{
553    if (len != sizeof(MachInst))
554        panic("invalid length\n");
555
556    DPRINTF(GDBMisc, "inserting hardware breakpoint at %#x\n", addr);
557
558    HardBreakpoint *&bkpt = hardBreakMap[addr];
559    if (bkpt == 0)
560        bkpt = new HardBreakpoint(this, addr);
561
562    bkpt->refcount++;
563
564    return true;
565}
566
567bool
568BaseRemoteGDB::removeHardBreak(Addr addr, size_t len)
569{
570    if (len != sizeof(MachInst))
571        panic("invalid length\n");
572
573    DPRINTF(GDBMisc, "removing hardware breakpoint at %#x\n", addr);
574
575    break_iter_t i = hardBreakMap.find(addr);
576    if (i == hardBreakMap.end())
577        return false;
578
579    HardBreakpoint *hbp = (*i).second;
580    if (--hbp->refcount == 0) {
581        delete hbp;
582        hardBreakMap.erase(i);
583    }
584
585    return true;
586}
587
588void
589BaseRemoteGDB::setTempBreakpoint(Addr bkpt)
590{
591    DPRINTF(GDBMisc, "setTempBreakpoint: addr=%#x\n", bkpt);
592    insertHardBreak(bkpt, sizeof(TheISA::MachInst));
593}
594
595void
596BaseRemoteGDB::clearTempBreakpoint(Addr &bkpt)
597{
598    DPRINTF(GDBMisc, "setTempBreakpoint: addr=%#x\n", bkpt);
599    removeHardBreak(bkpt, sizeof(TheISA::MachInst));
600    bkpt = 0;
601}
602
603const char *
604BaseRemoteGDB::break_type(char c)
605{
606    switch(c) {
607      case '0': return "software breakpoint";
608      case '1': return "hardware breakpoint";
609      case '2': return "write watchpoint";
610      case '3': return "read watchpoint";
611      case '4': return "access watchpoint";
612      default: return "unknown breakpoint/watchpoint";
613    }
614}
615
616// This function does all command processing for interfacing to a
617// remote gdb.  Note that the error codes are ignored by gdb at
618// present, but might eventually become meaningful. (XXX) It might
619// makes sense to use POSIX errno values, because that is what the
620// gdb/remote.c functions want to return.
621bool
622BaseRemoteGDB::trap(int type)
623{
624    uint64_t val;
625    size_t datalen, len;
626    char data[GDBPacketBufLen + 1];
627    char *buffer;
628    int bufferSize;
629    const char *p;
630    char command, subcmd;
631    string var;
632    bool ret;
633
634    if (!attached)
635        return false;
636
637    bufferSize = gdbregs.bytes() * 2 + 256;
638    buffer = (char*)malloc(bufferSize);
639
640    DPRINTF(GDBMisc, "trap: PC=%#x NPC=%#x\n",
641            context->readPC(), context->readNextPC());
642
643    clearSingleStep();
644
645    /*
646     * The first entry to this function is normally through
647     * a breakpoint trap in kgdb_connect(), in which case we
648     * must advance past the breakpoint because gdb will not.
649     *
650     * On the first entry here, we expect that gdb is not yet
651     * listening to us, so just enter the interaction loop.
652     * After the debugger is "active" (connected) it will be
653     * waiting for a "signaled" message from us.
654     */
655    if (!active)
656        active = true;
657    else
658        // Tell remote host that an exception has occurred.
659        snprintf((char *)buffer, bufferSize, "S%02x", type);
660        send(buffer);
661
662    // Stick frame regs into our reg cache.
663    getregs();
664
665    for (;;) {
666        datalen = recv(data, sizeof(data));
667        data[sizeof(data) - 1] = 0; // Sentinel
668        command = data[0];
669        subcmd = 0;
670        p = data + 1;
671        switch (command) {
672
673          case GDBSignal:
674            // if this command came from a running gdb, answer it --
675            // the other guy has no way of knowing if we're in or out
676            // of this loop when he issues a "remote-signal".
677            snprintf((char *)buffer, bufferSize,
678                    "S%02x", type);
679            send(buffer);
680            continue;
681
682          case GDBRegR:
683            if (2 * gdbregs.bytes() > bufferSize)
684                panic("buffer too small");
685
686            mem2hex(buffer, gdbregs.regs, gdbregs.bytes());
687            send(buffer);
688            continue;
689
690          case GDBRegW:
691            p = hex2mem(gdbregs.regs, p, gdbregs.bytes());
692            if (p == NULL || *p != '\0')
693                send("E01");
694            else {
695                setregs();
696                send("OK");
697            }
698            continue;
699
700#if 0
701          case GDBSetReg:
702            val = hex2i(&p);
703            if (*p++ != '=') {
704                send("E01");
705                continue;
706            }
707            if (val < 0 && val >= KGDB_NUMREGS) {
708                send("E01");
709                continue;
710            }
711
712            gdbregs.regs[val] = hex2i(&p);
713            setregs();
714            send("OK");
715
716            continue;
717#endif
718
719          case GDBMemR:
720            val = hex2i(&p);
721            if (*p++ != ',') {
722                send("E02");
723                continue;
724            }
725            len = hex2i(&p);
726            if (*p != '\0') {
727                send("E03");
728                continue;
729            }
730            if (len > bufferSize) {
731                send("E04");
732                continue;
733            }
734            if (!acc(val, len)) {
735                send("E05");
736                continue;
737            }
738
739            if (read(val, (size_t)len, (char *)buffer)) {
740               // variable length array would be nice, but C++ doesn't
741               // officially support those...
742               char *temp = new char[2*len+1];
743               mem2hex(temp, buffer, len);
744               send(temp);
745               delete [] temp;
746            } else {
747               send("E05");
748            }
749            continue;
750
751          case GDBMemW:
752            val = hex2i(&p);
753            if (*p++ != ',') {
754                send("E06");
755                continue;
756            }
757            len = hex2i(&p);
758            if (*p++ != ':') {
759                send("E07");
760                continue;
761            }
762            if (len > datalen - (p - data)) {
763                send("E08");
764                continue;
765            }
766            p = hex2mem(buffer, p, bufferSize);
767            if (p == NULL) {
768                send("E09");
769                continue;
770            }
771            if (!acc(val, len)) {
772                send("E0A");
773                continue;
774            }
775            if (write(val, (size_t)len, (char *)buffer))
776              send("OK");
777            else
778              send("E0B");
779            continue;
780
781          case GDBSetThread:
782            subcmd = *p++;
783            val = hex2i(&p);
784            if (val == 0)
785                send("OK");
786            else
787                send("E01");
788            continue;
789
790          case GDBDetach:
791          case GDBKill:
792            active = false;
793            clearSingleStep();
794            detach();
795            goto out;
796
797          case GDBAsyncCont:
798            subcmd = hex2i(&p);
799            if (*p++ == ';') {
800                val = hex2i(&p);
801                context->setPC(val);
802                context->setNextPC(val + sizeof(MachInst));
803            }
804            clearSingleStep();
805            goto out;
806
807          case GDBCont:
808            if (p - data < datalen) {
809                val = hex2i(&p);
810                context->setPC(val);
811                context->setNextPC(val + sizeof(MachInst));
812            }
813            clearSingleStep();
814            goto out;
815
816          case GDBAsyncStep:
817            subcmd = hex2i(&p);
818            if (*p++ == ';') {
819                val = hex2i(&p);
820                context->setPC(val);
821                context->setNextPC(val + sizeof(MachInst));
822            }
823            setSingleStep();
824            goto out;
825
826          case GDBStep:
827            if (p - data < datalen) {
828                val = hex2i(&p);
829                context->setPC(val);
830                context->setNextPC(val + sizeof(MachInst));
831            }
832            setSingleStep();
833            goto out;
834
835          case GDBClrHwBkpt:
836            subcmd = *p++;
837            if (*p++ != ',') send("E0D");
838            val = hex2i(&p);
839            if (*p++ != ',') send("E0D");
840            len = hex2i(&p);
841
842            DPRINTF(GDBMisc, "clear %s, addr=%#x, len=%d\n",
843                    break_type(subcmd), val, len);
844
845            ret = false;
846
847            switch (subcmd) {
848              case '0': // software breakpoint
849                ret = removeSoftBreak(val, len);
850                break;
851
852              case '1': // hardware breakpoint
853                ret = removeHardBreak(val, len);
854                break;
855
856              case '2': // write watchpoint
857              case '3': // read watchpoint
858              case '4': // access watchpoint
859              default: // unknown
860                send("");
861                break;
862            }
863
864            send(ret ? "OK" : "E0C");
865            continue;
866
867          case GDBSetHwBkpt:
868            subcmd = *p++;
869            if (*p++ != ',') send("E0D");
870            val = hex2i(&p);
871            if (*p++ != ',') send("E0D");
872            len = hex2i(&p);
873
874            DPRINTF(GDBMisc, "set %s, addr=%#x, len=%d\n",
875                    break_type(subcmd), val, len);
876
877            ret = false;
878
879            switch (subcmd) {
880              case '0': // software breakpoint
881                ret = insertSoftBreak(val, len);
882                break;
883
884              case '1': // hardware breakpoint
885                ret = insertHardBreak(val, len);
886                break;
887
888              case '2': // write watchpoint
889              case '3': // read watchpoint
890              case '4': // access watchpoint
891              default: // unknown
892                send("");
893                break;
894            }
895
896            send(ret ? "OK" : "E0C");
897            continue;
898
899          case GDBQueryVar:
900            var = string(p, datalen - 1);
901            if (var == "C")
902                send("QC0");
903            else
904                send("");
905            continue;
906
907          case GDBSetBaud:
908          case GDBSetBreak:
909          case GDBDebug:
910          case GDBCycleStep:
911          case GDBSigCycleStep:
912          case GDBReadReg:
913          case GDBSetVar:
914          case GDBReset:
915          case GDBThreadAlive:
916          case GDBTargetExit:
917          case GDBBinaryDload:
918            // Unsupported command
919            DPRINTF(GDBMisc, "Unsupported command: %s\n",
920                    gdb_command(command));
921            DDUMP(GDBMisc, (uint8_t *)data, datalen);
922            send("");
923            continue;
924
925          default:
926            // Unknown command.
927            DPRINTF(GDBMisc, "Unknown command: %c(%#x)\n",
928                    command, command);
929            send("");
930            continue;
931
932
933        }
934    }
935
936  out:
937    free(buffer);
938    return true;
939}
940
941// Convert a hex digit into an integer.
942// This returns -1 if the argument passed is no valid hex digit.
943int
944BaseRemoteGDB::digit2i(char c)
945{
946    if (c >= '0' && c <= '9')
947        return (c - '0');
948    else if (c >= 'a' && c <= 'f')
949        return (c - 'a' + 10);
950    else if (c >= 'A' && c <= 'F')
951
952        return (c - 'A' + 10);
953    else
954        return (-1);
955}
956
957// Convert the low 4 bits of an integer into an hex digit.
958char
959BaseRemoteGDB::i2digit(int n)
960{
961    return ("0123456789abcdef"[n & 0x0f]);
962}
963
964// Convert a byte array into an hex string.
965void
966BaseRemoteGDB::mem2hex(void *vdst, const void *vsrc, int len)
967{
968    char *dst = (char *)vdst;
969    const char *src = (const char *)vsrc;
970
971    while (len--) {
972        *dst++ = i2digit(*src >> 4);
973        *dst++ = i2digit(*src++);
974    }
975    *dst = '\0';
976}
977
978// Convert an hex string into a byte array.
979// This returns a pointer to the character following the last valid
980// hex digit. If the string ends in the middle of a byte, NULL is
981// returned.
982const char *
983BaseRemoteGDB::hex2mem(void *vdst, const char *src, int maxlen)
984{
985    char *dst = (char *)vdst;
986    int msb, lsb;
987
988    while (*src && maxlen--) {
989        msb = digit2i(*src++);
990        if (msb < 0)
991            return (src - 1);
992        lsb = digit2i(*src++);
993        if (lsb < 0)
994            return (NULL);
995        *dst++ = (msb << 4) | lsb;
996    }
997    return (src);
998}
999
1000// Convert an hex string into an integer.
1001// This returns a pointer to the character following the last valid
1002// hex digit.
1003Addr
1004BaseRemoteGDB::hex2i(const char **srcp)
1005{
1006    const char *src = *srcp;
1007    Addr r = 0;
1008    int nibble;
1009
1010    while ((nibble = digit2i(*src)) >= 0) {
1011        r *= 16;
1012        r += nibble;
1013        src++;
1014    }
1015    *srcp = src;
1016    return (r);
1017}
1018
1019