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