remote_gdb.cc revision 2107
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
29/*
30 * Copyright (c) 1990, 1993
31 *	The Regents of the University of California.  All rights reserved.
32 *
33 * This software was developed by the Computer Systems Engineering group
34 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
35 * contributed to Berkeley.
36 *
37 * All advertising materials mentioning features or use of this software
38 * must display the following acknowledgement:
39 *	This product includes software developed by the University of
40 *	California, Lawrence Berkeley Laboratories.
41 *
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
44 * are met:
45 * 1. Redistributions of source code must retain the above copyright
46 *    notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 *    notice, this list of conditions and the following disclaimer in the
49 *    documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 *    must display the following acknowledgement:
52 *	This product includes software developed by the University of
53 *	California, Berkeley and its contributors.
54 * 4. Neither the name of the University nor the names of its contributors
55 *    may be used to endorse or promote products derived from this software
56 *    without specific prior written permission.
57 *
58 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * SUCH DAMAGE.
69 *
70 *	@(#)kgdb_stub.c	8.4 (Berkeley) 1/12/94
71 */
72
73/*-
74 * Copyright (c) 2001 The NetBSD Foundation, Inc.
75 * All rights reserved.
76 *
77 * This code is derived from software contributed to The NetBSD Foundation
78 * by Jason R. Thorpe.
79 *
80 * Redistribution and use in source and binary forms, with or without
81 * modification, are permitted provided that the following conditions
82 * are met:
83 * 1. Redistributions of source code must retain the above copyright
84 *    notice, this list of conditions and the following disclaimer.
85 * 2. Redistributions in binary form must reproduce the above copyright
86 *    notice, this list of conditions and the following disclaimer in the
87 *    documentation and/or other materials provided with the distribution.
88 * 3. All advertising materials mentioning features or use of this software
89 *    must display the following acknowledgement:
90 *	This product includes software developed by the NetBSD
91 *	Foundation, Inc. and its contributors.
92 * 4. Neither the name of The NetBSD Foundation nor the names of its
93 *    contributors may be used to endorse or promote products derived
94 *    from this software without specific prior written permission.
95 *
96 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
97 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
98 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
99 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
100 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106 * POSSIBILITY OF SUCH DAMAGE.
107 */
108
109/*
110 * $NetBSD: kgdb_stub.c,v 1.8 2001/07/07 22:58:00 wdk Exp $
111 *
112 * Taken from NetBSD
113 *
114 * "Stub" to allow remote cpu to debug over a serial line using gdb.
115 */
116
117#include <sys/signal.h>
118
119#include <cstdio>
120#include <string>
121#include <unistd.h>
122
123#include "base/intmath.hh"
124#include "base/kgdb.h"
125#include "base/remote_gdb.hh"
126#include "base/socket.hh"
127#include "base/trace.hh"
128#include "cpu/exec_context.hh"
129#include "cpu/static_inst.hh"
130#include "mem/functional/physical.hh"
131#include "sim/system.hh"
132#include "targetarch/vtophys.hh"
133
134using namespace std;
135using namespace TheISA;
136
137#ifndef NDEBUG
138vector<RemoteGDB *> debuggers;
139int current_debugger = -1;
140
141void
142debugger()
143{
144    if (current_debugger >= 0 && current_debugger < debuggers.size()) {
145        RemoteGDB *gdb = debuggers[current_debugger];
146        if (!gdb->isattached())
147            gdb->listener->accept();
148        if (gdb->isattached())
149            gdb->trap(ALPHA_KENTRY_IF);
150    }
151}
152#endif
153
154///////////////////////////////////////////////////////////
155//
156//
157//
158
159GDBListener::Event::Event(GDBListener *l, int fd, int e)
160    : PollEvent(fd, e), listener(l)
161{}
162
163void
164GDBListener::Event::process(int revent)
165{
166    listener->accept();
167}
168
169GDBListener::GDBListener(RemoteGDB *g, int p)
170    : event(NULL), gdb(g), port(p)
171{
172    assert(!gdb->listener);
173    gdb->listener = this;
174}
175
176GDBListener::~GDBListener()
177{
178    if (event)
179        delete event;
180}
181
182string
183GDBListener::name()
184{
185    return gdb->name() + ".listener";
186}
187
188void
189GDBListener::listen()
190{
191    while (!listener.listen(port, true)) {
192        DPRINTF(GDBMisc, "Can't bind port %d\n", port);
193        port++;
194    }
195
196    event = new Event(this, listener.getfd(), POLLIN);
197    pollQueue.schedule(event);
198
199#ifndef NDEBUG
200    gdb->number = debuggers.size();
201    debuggers.push_back(gdb);
202#endif
203
204#ifndef NDEBUG
205    ccprintf(cerr, "%d: %s: listening for remote gdb #%d on port %d\n",
206             curTick, name(), gdb->number, port);
207#else
208    ccprintf(cerr, "%d: %s: listening for remote gdb on port %d\n",
209             curTick, name(), port);
210#endif
211}
212
213void
214GDBListener::accept()
215{
216    if (!listener.islistening())
217        panic("GDBListener::accept(): cannot accept if we're not listening!");
218
219    int sfd = listener.accept(true);
220
221    if (sfd != -1) {
222        if (gdb->isattached())
223            close(sfd);
224        else
225            gdb->attach(sfd);
226    }
227}
228
229///////////////////////////////////////////////////////////
230//
231//
232//
233int digit2i(char);
234char i2digit(int);
235void mem2hex(void *, const void *, int);
236const char *hex2mem(void *, const char *, int);
237Addr hex2i(const char **);
238
239RemoteGDB::Event::Event(RemoteGDB *g, int fd, int e)
240    : PollEvent(fd, e), gdb(g)
241{}
242
243void
244RemoteGDB::Event::process(int revent)
245{
246    if (revent & POLLIN)
247        gdb->trap(ALPHA_KENTRY_IF);
248    else if (revent & POLLNVAL)
249        gdb->detach();
250}
251
252RemoteGDB::RemoteGDB(System *_system, ExecContext *c)
253    : event(NULL), listener(NULL), number(-1), fd(-1),
254      active(false), attached(false),
255      system(_system), pmem(_system->physmem), context(c)
256{
257    memset(gdbregs, 0, sizeof(gdbregs));
258}
259
260RemoteGDB::~RemoteGDB()
261{
262    if (event)
263        delete event;
264}
265
266string
267RemoteGDB::name()
268{
269    return system->name() + ".remote_gdb";
270}
271
272bool
273RemoteGDB::isattached()
274{ return attached; }
275
276void
277RemoteGDB::attach(int f)
278{
279    fd = f;
280
281    event = new Event(this, fd, POLLIN);
282    pollQueue.schedule(event);
283
284    attached = true;
285    DPRINTFN("remote gdb attached\n");
286}
287
288void
289RemoteGDB::detach()
290{
291    attached = false;
292    close(fd);
293    fd = -1;
294
295    pollQueue.remove(event);
296    DPRINTFN("remote gdb detached\n");
297}
298
299const char *
300gdb_command(char cmd)
301{
302    switch (cmd) {
303      case KGDB_SIGNAL: return "KGDB_SIGNAL";
304      case KGDB_SET_BAUD: return "KGDB_SET_BAUD";
305      case KGDB_SET_BREAK: return "KGDB_SET_BREAK";
306      case KGDB_CONT: return "KGDB_CONT";
307      case KGDB_ASYNC_CONT: return "KGDB_ASYNC_CONT";
308      case KGDB_DEBUG: return "KGDB_DEBUG";
309      case KGDB_DETACH: return "KGDB_DETACH";
310      case KGDB_REG_R: return "KGDB_REG_R";
311      case KGDB_REG_W: return "KGDB_REG_W";
312      case KGDB_SET_THREAD: return "KGDB_SET_THREAD";
313      case KGDB_CYCLE_STEP: return "KGDB_CYCLE_STEP";
314      case KGDB_SIG_CYCLE_STEP: return "KGDB_SIG_CYCLE_STEP";
315      case KGDB_KILL: return "KGDB_KILL";
316      case KGDB_MEM_W: return "KGDB_MEM_W";
317      case KGDB_MEM_R: return "KGDB_MEM_R";
318      case KGDB_SET_REG: return "KGDB_SET_REG";
319      case KGDB_READ_REG: return "KGDB_READ_REG";
320      case KGDB_QUERY_VAR: return "KGDB_QUERY_VAR";
321      case KGDB_SET_VAR: return "KGDB_SET_VAR";
322      case KGDB_RESET: return "KGDB_RESET";
323      case KGDB_STEP: return "KGDB_STEP";
324      case KGDB_ASYNC_STEP: return "KGDB_ASYNC_STEP";
325      case KGDB_THREAD_ALIVE: return "KGDB_THREAD_ALIVE";
326      case KGDB_TARGET_EXIT: return "KGDB_TARGET_EXIT";
327      case KGDB_BINARY_DLOAD: return "KGDB_BINARY_DLOAD";
328      case KGDB_CLR_HW_BKPT: return "KGDB_CLR_HW_BKPT";
329      case KGDB_SET_HW_BKPT: return "KGDB_SET_HW_BKPT";
330      case KGDB_START: return "KGDB_START";
331      case KGDB_END: return "KGDB_END";
332      case KGDB_GOODP: return "KGDB_GOODP";
333      case KGDB_BADP: return "KGDB_BADP";
334      default: return "KGDB_UNKNOWN";
335    }
336}
337
338///////////////////////////////////////////////////////////
339// RemoteGDB::acc
340//
341//	Determine if the mapping at va..(va+len) is valid.
342//
343bool
344RemoteGDB::acc(Addr va, size_t len)
345{
346    Addr last_va;
347
348    va = TheISA::TruncPage(va);
349    last_va = TheISA::RoundPage(va + len);
350
351    do  {
352        if (TheISA::IsK0Seg(va)) {
353            if (va < (TheISA::K0SegBase + pmem->size())) {
354                DPRINTF(GDBAcc, "acc:   Mapping is valid  K0SEG <= "
355                        "%#x < K0SEG + size\n", va);
356                return true;
357            } else {
358                DPRINTF(GDBAcc, "acc:   Mapping invalid %#x > K0SEG + size\n",
359                        va);
360                return false;
361            }
362        }
363
364    /**
365     * This code says that all accesses to palcode (instruction and data)
366     * are valid since there isn't a va->pa mapping because palcode is
367     * accessed physically. At some point this should probably be cleaned up
368     * but there is no easy way to do it.
369     */
370
371        if (AlphaISA::PcPAL(va) || va < 0x10000)
372            return true;
373
374        Addr ptbr = context->regs.ipr[AlphaISA::IPR_PALtemp20];
375        TheISA::PageTableEntry pte = kernel_pte_lookup(pmem, ptbr, va);
376        if (!pte.valid()) {
377            DPRINTF(GDBAcc, "acc:   %#x pte is invalid\n", va);
378            return false;
379        }
380        va += TheISA::PageBytes;
381    } while (va < last_va);
382
383    DPRINTF(GDBAcc, "acc:   %#x mapping is valid\n", va);
384    return true;
385}
386
387///////////////////////////////////////////////////////////
388// RemoteGDB::signal
389//
390//	Translate a trap number into a Unix-compatible signal number.
391//	(GDB only understands Unix signal numbers.)
392//
393int
394RemoteGDB::signal(int type)
395{
396    switch (type) {
397      case ALPHA_KENTRY_INT:
398        return (SIGTRAP);
399
400      case ALPHA_KENTRY_UNA:
401        return (SIGBUS);
402
403      case ALPHA_KENTRY_ARITH:
404        return (SIGFPE);
405
406      case ALPHA_KENTRY_IF:
407        return (SIGILL);
408
409      case ALPHA_KENTRY_MM:
410        return (SIGSEGV);
411
412      default:
413        panic("unknown signal type");
414        return 0;
415    }
416}
417
418///////////////////////////////////////////////////////////
419// RemoteGDB::getregs
420//
421//	Translate the kernel debugger register format into
422//	the GDB register format.
423void
424RemoteGDB::getregs()
425{
426    memset(gdbregs, 0, sizeof(gdbregs));
427    memcpy(&gdbregs[KGDB_REG_V0], context->regs.intRegFile, 32 * sizeof(uint64_t));
428#ifdef KGDB_FP_REGS
429    memcpy(&gdbregs[KGDB_REG_F0], context->regs.floatRegFile.q,
430           32 * sizeof(uint64_t));
431#endif
432    gdbregs[KGDB_REG_PC] = context->regs.pc;
433}
434
435///////////////////////////////////////////////////////////
436// RemoteGDB::setregs
437//
438//	Translate the GDB register format into the kernel
439//	debugger register format.
440//
441void
442RemoteGDB::setregs()
443{
444    memcpy(context->regs.intRegFile, &gdbregs[KGDB_REG_V0],
445           32 * sizeof(uint64_t));
446#ifdef KGDB_FP_REGS
447    memcpy(context->regs.floatRegFile.q, &gdbregs[KGDB_REG_F0],
448           32 * sizeof(uint64_t));
449#endif
450    context->regs.pc = gdbregs[KGDB_REG_PC];
451}
452
453void
454RemoteGDB::setTempBreakpoint(TempBreakpoint &bkpt, Addr addr)
455{
456    DPRINTF(GDBMisc, "setTempBreakpoint: addr=%#x\n", addr);
457
458    bkpt.address = addr;
459    insertHardBreak(addr, 4);
460}
461
462void
463RemoteGDB::clearTempBreakpoint(TempBreakpoint &bkpt)
464{
465    DPRINTF(GDBMisc, "setTempBreakpoint: addr=%#x\n",
466            bkpt.address);
467
468
469    removeHardBreak(bkpt.address, 4);
470    bkpt.address = 0;
471}
472
473void
474RemoteGDB::clearSingleStep()
475{
476    DPRINTF(GDBMisc, "clearSingleStep bt_addr=%#x nt_addr=%#x\n",
477            takenBkpt.address, notTakenBkpt.address);
478
479    if (takenBkpt.address != 0)
480        clearTempBreakpoint(takenBkpt);
481
482    if (notTakenBkpt.address != 0)
483        clearTempBreakpoint(notTakenBkpt);
484}
485
486void
487RemoteGDB::setSingleStep()
488{
489    Addr pc = context->regs.pc;
490    Addr npc, bpc;
491    bool set_bt = false;
492
493    npc = pc + sizeof(MachInst);
494
495    // User was stopped at pc, e.g. the instruction at pc was not
496    // executed.
497    MachInst inst = read<MachInst>(pc);
498    StaticInstPtr si(inst);
499    if (si->hasBranchTarget(pc, context, bpc)) {
500        // Don't bother setting a breakpoint on the taken branch if it
501        // is the same as the next pc
502        if (bpc != npc)
503            set_bt = true;
504    }
505
506    DPRINTF(GDBMisc, "setSingleStep bt_addr=%#x nt_addr=%#x\n",
507            takenBkpt.address, notTakenBkpt.address);
508
509    setTempBreakpoint(notTakenBkpt, npc);
510
511    if (set_bt)
512        setTempBreakpoint(takenBkpt, bpc);
513}
514
515/////////////////////////
516//
517//
518
519uint8_t
520RemoteGDB::getbyte()
521{
522    uint8_t b;
523    ::read(fd, &b, 1);
524    return b;
525}
526
527void
528RemoteGDB::putbyte(uint8_t b)
529{
530    ::write(fd, &b, 1);
531}
532
533// Send a packet to gdb
534void
535RemoteGDB::send(const char *bp)
536{
537    const char *p;
538    uint8_t csum, c;
539
540    DPRINTF(GDBSend, "send:  %s\n", bp);
541
542    do {
543        p = bp;
544        putbyte(KGDB_START);
545        for (csum = 0; (c = *p); p++) {
546            putbyte(c);
547            csum += c;
548        }
549        putbyte(KGDB_END);
550        putbyte(i2digit(csum >> 4));
551        putbyte(i2digit(csum));
552    } while ((c = getbyte() & 0x7f) == KGDB_BADP);
553}
554
555// Receive a packet from gdb
556int
557RemoteGDB::recv(char *bp, int maxlen)
558{
559    char *p;
560    int c, csum;
561    int len;
562
563    do {
564        p = bp;
565        csum = len = 0;
566        while ((c = getbyte()) != KGDB_START)
567            ;
568
569        while ((c = getbyte()) != KGDB_END && len < maxlen) {
570            c &= 0x7f;
571            csum += c;
572            *p++ = c;
573            len++;
574        }
575        csum &= 0xff;
576        *p = '\0';
577
578        if (len >= maxlen) {
579            putbyte(KGDB_BADP);
580            continue;
581        }
582
583        csum -= digit2i(getbyte()) * 16;
584        csum -= digit2i(getbyte());
585
586        if (csum == 0) {
587            putbyte(KGDB_GOODP);
588            // Sequence present?
589            if (bp[2] == ':') {
590                putbyte(bp[0]);
591                putbyte(bp[1]);
592                len -= 3;
593                bcopy(bp + 3, bp, len);
594            }
595            break;
596        }
597        putbyte(KGDB_BADP);
598    } while (1);
599
600    DPRINTF(GDBRecv, "recv:  %s: %s\n", gdb_command(*bp), bp);
601
602    return (len);
603}
604
605// Read bytes from kernel address space for debugger.
606bool
607RemoteGDB::read(Addr vaddr, size_t size, char *data)
608{
609    static Addr lastaddr = 0;
610    static size_t lastsize = 0;
611
612    uint8_t *maddr;
613
614    if (vaddr < 10) {
615      DPRINTF(GDBRead, "read:  reading memory location zero!\n");
616      vaddr = lastaddr + lastsize;
617    }
618
619    DPRINTF(GDBRead, "read:  addr=%#x, size=%d", vaddr, size);
620#if TRACING_ON
621    char *d = data;
622    size_t s = size;
623#endif
624
625    lastaddr = vaddr;
626    lastsize = size;
627
628    size_t count = min((Addr)size,
629                       VMPageSize - (vaddr & (VMPageSize - 1)));
630
631    maddr = vtomem(context, vaddr, count);
632    memcpy(data, maddr, count);
633
634    vaddr += count;
635    data += count;
636    size -= count;
637
638    while (size >= VMPageSize) {
639        maddr = vtomem(context, vaddr, count);
640        memcpy(data, maddr, VMPageSize);
641
642        vaddr += VMPageSize;
643        data += VMPageSize;
644        size -= VMPageSize;
645    }
646
647    if (size > 0) {
648        maddr = vtomem(context, vaddr, count);
649        memcpy(data, maddr, size);
650    }
651
652#if TRACING_ON
653    if (DTRACE(GDBRead)) {
654        if (DTRACE(GDBExtra)) {
655            char buf[1024];
656            mem2hex(buf, d, s);
657            DPRINTFNR(": %s\n", buf);
658        } else
659            DPRINTFNR("\n");
660    }
661#endif
662
663    return true;
664}
665
666// Write bytes to kernel address space for debugger.
667bool
668RemoteGDB::write(Addr vaddr, size_t size, const char *data)
669{
670    static Addr lastaddr = 0;
671    static size_t lastsize = 0;
672
673    uint8_t *maddr;
674
675    if (vaddr < 10) {
676      DPRINTF(GDBWrite, "write: writing memory location zero!\n");
677      vaddr = lastaddr + lastsize;
678    }
679
680    if (DTRACE(GDBWrite)) {
681        DPRINTFN("write: addr=%#x, size=%d", vaddr, size);
682        if (DTRACE(GDBExtra)) {
683            char buf[1024];
684            mem2hex(buf, data, size);
685            DPRINTFNR(": %s\n", buf);
686        } else
687            DPRINTFNR("\n");
688    }
689
690    lastaddr = vaddr;
691    lastsize = size;
692
693    size_t count = min((Addr)size,
694                       VMPageSize - (vaddr & (VMPageSize - 1)));
695
696    maddr = vtomem(context, vaddr, count);
697    memcpy(maddr, data, count);
698
699    vaddr += count;
700    data += count;
701    size -= count;
702
703    while (size >= VMPageSize) {
704        maddr = vtomem(context, vaddr, count);
705        memcpy(maddr, data, VMPageSize);
706
707        vaddr += VMPageSize;
708        data += VMPageSize;
709        size -= VMPageSize;
710    }
711
712    if (size > 0) {
713        maddr = vtomem(context, vaddr, count);
714        memcpy(maddr, data, size);
715    }
716
717#ifdef IMB
718    alpha_pal_imb();
719#endif
720
721    return true;
722}
723
724
725PCEventQueue *RemoteGDB::getPcEventQueue()
726{
727    return &system->pcEventQueue;
728}
729
730
731RemoteGDB::HardBreakpoint::HardBreakpoint(RemoteGDB *_gdb, Addr pc)
732    : PCEvent(_gdb->getPcEventQueue(), "HardBreakpoint Event", pc),
733      gdb(_gdb), refcount(0)
734{
735    DPRINTF(GDBMisc, "creating hardware breakpoint at %#x\n", evpc);
736}
737
738void
739RemoteGDB::HardBreakpoint::process(ExecContext *xc)
740{
741    DPRINTF(GDBMisc, "handling hardware breakpoint at %#x\n", pc());
742
743    if (xc == gdb->context)
744        gdb->trap(ALPHA_KENTRY_INT);
745}
746
747bool
748RemoteGDB::insertSoftBreak(Addr addr, size_t len)
749{
750    if (len != sizeof(MachInst))
751        panic("invalid length\n");
752
753    return insertHardBreak(addr, len);
754}
755
756bool
757RemoteGDB::removeSoftBreak(Addr addr, size_t len)
758{
759    if (len != sizeof(MachInst))
760        panic("invalid length\n");
761
762    return removeHardBreak(addr, len);
763}
764
765bool
766RemoteGDB::insertHardBreak(Addr addr, size_t len)
767{
768    if (len != sizeof(MachInst))
769        panic("invalid length\n");
770
771    DPRINTF(GDBMisc, "inserting hardware breakpoint at %#x\n", addr);
772
773    HardBreakpoint *&bkpt = hardBreakMap[addr];
774    if (bkpt == 0)
775        bkpt = new HardBreakpoint(this, addr);
776
777    bkpt->refcount++;
778
779    return true;
780}
781
782bool
783RemoteGDB::removeHardBreak(Addr addr, size_t len)
784{
785    if (len != sizeof(MachInst))
786        panic("invalid length\n");
787
788    DPRINTF(GDBMisc, "removing hardware breakpoint at %#x\n", addr);
789
790    break_iter_t i = hardBreakMap.find(addr);
791    if (i == hardBreakMap.end())
792        return false;
793
794    HardBreakpoint *hbp = (*i).second;
795    if (--hbp->refcount == 0) {
796        delete hbp;
797        hardBreakMap.erase(i);
798    }
799
800    return true;
801}
802
803const char *
804break_type(char c)
805{
806    switch(c) {
807      case '0': return "software breakpoint";
808      case '1': return "hardware breakpoint";
809      case '2': return "write watchpoint";
810      case '3': return "read watchpoint";
811      case '4': return "access watchpoint";
812      default: return "unknown breakpoint/watchpoint";
813    }
814}
815
816// This function does all command processing for interfacing to a
817// remote gdb.  Note that the error codes are ignored by gdb at
818// present, but might eventually become meaningful. (XXX) It might
819// makes sense to use POSIX errno values, because that is what the
820// gdb/remote.c functions want to return.
821bool
822RemoteGDB::trap(int type)
823{
824    uint64_t val;
825    size_t datalen, len;
826    char data[KGDB_BUFLEN + 1];
827    char buffer[sizeof(gdbregs) * 2 + 256];
828    char temp[KGDB_BUFLEN];
829    const char *p;
830    char command, subcmd;
831    string var;
832    bool ret;
833
834    if (!attached)
835        return false;
836
837    DPRINTF(GDBMisc, "trap: PC=%#x NPC=%#x\n",
838            context->regs.pc, context->regs.npc);
839
840    clearSingleStep();
841
842    /*
843     * The first entry to this function is normally through
844     * a breakpoint trap in kgdb_connect(), in which case we
845     * must advance past the breakpoint because gdb will not.
846     *
847     * On the first entry here, we expect that gdb is not yet
848     * listening to us, so just enter the interaction loop.
849     * After the debugger is "active" (connected) it will be
850     * waiting for a "signaled" message from us.
851     */
852    if (!active)
853        active = true;
854    else
855        // Tell remote host that an exception has occurred.
856        snprintf((char *)buffer, sizeof(buffer), "S%02x", signal(type));
857        send(buffer);
858
859    // Stick frame regs into our reg cache.
860    getregs();
861
862    for (;;) {
863        datalen = recv(data, sizeof(data));
864        data[sizeof(data) - 1] = 0; // Sentinel
865        command = data[0];
866        subcmd = 0;
867        p = data + 1;
868        switch (command) {
869
870          case KGDB_SIGNAL:
871            // if this command came from a running gdb, answer it --
872            // the other guy has no way of knowing if we're in or out
873            // of this loop when he issues a "remote-signal".
874            snprintf((char *)buffer, sizeof(buffer), "S%02x", signal(type));
875            send(buffer);
876            continue;
877
878          case KGDB_REG_R:
879            if (2 * sizeof(gdbregs) > sizeof(buffer))
880                panic("buffer too small");
881
882            mem2hex(buffer, gdbregs, sizeof(gdbregs));
883            send(buffer);
884            continue;
885
886          case KGDB_REG_W:
887            p = hex2mem(gdbregs, p, sizeof(gdbregs));
888            if (p == NULL || *p != '\0')
889                send("E01");
890            else {
891                setregs();
892                send("OK");
893            }
894            continue;
895
896#if 0
897          case KGDB_SET_REG:
898            val = hex2i(&p);
899            if (*p++ != '=') {
900                send("E01");
901                continue;
902            }
903            if (val < 0 && val >= KGDB_NUMREGS) {
904                send("E01");
905                continue;
906            }
907
908            gdbregs[val] = hex2i(&p);
909            setregs();
910            send("OK");
911
912            continue;
913#endif
914
915          case KGDB_MEM_R:
916            val = hex2i(&p);
917            if (*p++ != ',') {
918                send("E02");
919                continue;
920            }
921            len = hex2i(&p);
922            if (*p != '\0') {
923                send("E03");
924                continue;
925            }
926            if (len > sizeof(buffer)) {
927                send("E04");
928                continue;
929            }
930            if (!acc(val, len)) {
931                send("E05");
932                continue;
933            }
934
935            if (read(val, (size_t)len, (char *)buffer)) {
936              mem2hex(temp, buffer, len);
937              send(temp);
938            } else {
939              send("E05");
940            }
941            continue;
942
943          case KGDB_MEM_W:
944            val = hex2i(&p);
945            if (*p++ != ',') {
946                send("E06");
947                continue;
948            }
949            len = hex2i(&p);
950            if (*p++ != ':') {
951                send("E07");
952                continue;
953            }
954            if (len > datalen - (p - data)) {
955                send("E08");
956                continue;
957            }
958            p = hex2mem(buffer, p, sizeof(buffer));
959            if (p == NULL) {
960                send("E09");
961                continue;
962            }
963            if (!acc(val, len)) {
964                send("E0A");
965                continue;
966            }
967            if (write(val, (size_t)len, (char *)buffer))
968              send("OK");
969            else
970              send("E0B");
971            continue;
972
973          case KGDB_SET_THREAD:
974            subcmd = *p++;
975            val = hex2i(&p);
976            if (val == 0)
977                send("OK");
978            else
979                send("E01");
980            continue;
981
982          case KGDB_DETACH:
983          case KGDB_KILL:
984            active = false;
985            clearSingleStep();
986            detach();
987            goto out;
988
989          case KGDB_ASYNC_CONT:
990            subcmd = hex2i(&p);
991            if (*p++ == ';') {
992                val = hex2i(&p);
993                context->regs.pc = val;
994                context->regs.npc = val + sizeof(MachInst);
995            }
996            clearSingleStep();
997            goto out;
998
999          case KGDB_CONT:
1000            if (p - data < datalen) {
1001                val = hex2i(&p);
1002                context->regs.pc = val;
1003                context->regs.npc = val + sizeof(MachInst);
1004            }
1005            clearSingleStep();
1006            goto out;
1007
1008          case KGDB_ASYNC_STEP:
1009            subcmd = hex2i(&p);
1010            if (*p++ == ';') {
1011                val = hex2i(&p);
1012                context->regs.pc = val;
1013                context->regs.npc = val + sizeof(MachInst);
1014            }
1015            setSingleStep();
1016            goto out;
1017
1018          case KGDB_STEP:
1019            if (p - data < datalen) {
1020                val = hex2i(&p);
1021                context->regs.pc = val;
1022                context->regs.npc = val + sizeof(MachInst);
1023            }
1024            setSingleStep();
1025            goto out;
1026
1027          case KGDB_CLR_HW_BKPT:
1028            subcmd = *p++;
1029            if (*p++ != ',') send("E0D");
1030            val = hex2i(&p);
1031            if (*p++ != ',') send("E0D");
1032            len = hex2i(&p);
1033
1034            DPRINTF(GDBMisc, "clear %s, addr=%#x, len=%d\n",
1035                    break_type(subcmd), val, len);
1036
1037            ret = false;
1038
1039            switch (subcmd) {
1040              case '0': // software breakpoint
1041                ret = removeSoftBreak(val, len);
1042                break;
1043
1044              case '1': // hardware breakpoint
1045                ret = removeHardBreak(val, len);
1046                break;
1047
1048              case '2': // write watchpoint
1049              case '3': // read watchpoint
1050              case '4': // access watchpoint
1051              default: // unknown
1052                send("");
1053                break;
1054            }
1055
1056            send(ret ? "OK" : "E0C");
1057            continue;
1058
1059          case KGDB_SET_HW_BKPT:
1060            subcmd = *p++;
1061            if (*p++ != ',') send("E0D");
1062            val = hex2i(&p);
1063            if (*p++ != ',') send("E0D");
1064            len = hex2i(&p);
1065
1066            DPRINTF(GDBMisc, "set %s, addr=%#x, len=%d\n",
1067                    break_type(subcmd), val, len);
1068
1069            ret = false;
1070
1071            switch (subcmd) {
1072              case '0': // software breakpoint
1073                ret = insertSoftBreak(val, len);
1074                break;
1075
1076              case '1': // hardware breakpoint
1077                ret = insertHardBreak(val, len);
1078                break;
1079
1080              case '2': // write watchpoint
1081              case '3': // read watchpoint
1082              case '4': // access watchpoint
1083              default: // unknown
1084                send("");
1085                break;
1086            }
1087
1088            send(ret ? "OK" : "E0C");
1089            continue;
1090
1091          case KGDB_QUERY_VAR:
1092            var = string(p, datalen - 1);
1093            if (var == "C")
1094                send("QC0");
1095            else
1096                send("");
1097            continue;
1098
1099          case KGDB_SET_BAUD:
1100          case KGDB_SET_BREAK:
1101          case KGDB_DEBUG:
1102          case KGDB_CYCLE_STEP:
1103          case KGDB_SIG_CYCLE_STEP:
1104          case KGDB_READ_REG:
1105          case KGDB_SET_VAR:
1106          case KGDB_RESET:
1107          case KGDB_THREAD_ALIVE:
1108          case KGDB_TARGET_EXIT:
1109          case KGDB_BINARY_DLOAD:
1110            // Unsupported command
1111            DPRINTF(GDBMisc, "Unsupported command: %s\n",
1112                    gdb_command(command));
1113            DDUMP(GDBMisc, (uint8_t *)data, datalen);
1114            send("");
1115            continue;
1116
1117          default:
1118            // Unknown command.
1119            DPRINTF(GDBMisc, "Unknown command: %c(%#x)\n",
1120                    command, command);
1121            send("");
1122            continue;
1123
1124
1125        }
1126    }
1127
1128  out:
1129    return true;
1130}
1131
1132// Convert a hex digit into an integer.
1133// This returns -1 if the argument passed is no valid hex digit.
1134int
1135digit2i(char c)
1136{
1137    if (c >= '0' && c <= '9')
1138        return (c - '0');
1139    else if (c >= 'a' && c <= 'f')
1140        return (c - 'a' + 10);
1141    else if (c >= 'A' && c <= 'F')
1142
1143        return (c - 'A' + 10);
1144    else
1145        return (-1);
1146}
1147
1148// Convert the low 4 bits of an integer into an hex digit.
1149char
1150i2digit(int n)
1151{
1152    return ("0123456789abcdef"[n & 0x0f]);
1153}
1154
1155// Convert a byte array into an hex string.
1156void
1157mem2hex(void *vdst, const void *vsrc, int len)
1158{
1159    char *dst = (char *)vdst;
1160    const char *src = (const char *)vsrc;
1161
1162    while (len--) {
1163        *dst++ = i2digit(*src >> 4);
1164        *dst++ = i2digit(*src++);
1165    }
1166    *dst = '\0';
1167}
1168
1169// Convert an hex string into a byte array.
1170// This returns a pointer to the character following the last valid
1171// hex digit. If the string ends in the middle of a byte, NULL is
1172// returned.
1173const char *
1174hex2mem(void *vdst, const char *src, int maxlen)
1175{
1176    char *dst = (char *)vdst;
1177    int msb, lsb;
1178
1179    while (*src && maxlen--) {
1180        msb = digit2i(*src++);
1181        if (msb < 0)
1182            return (src - 1);
1183        lsb = digit2i(*src++);
1184        if (lsb < 0)
1185            return (NULL);
1186        *dst++ = (msb << 4) | lsb;
1187    }
1188    return (src);
1189}
1190
1191// Convert an hex string into an integer.
1192// This returns a pointer to the character following the last valid
1193// hex digit.
1194Addr
1195hex2i(const char **srcp)
1196{
1197    const char *src = *srcp;
1198    Addr r = 0;
1199    int nibble;
1200
1201    while ((nibble = digit2i(*src)) >= 0) {
1202        r *= 16;
1203        r += nibble;
1204        src++;
1205    }
1206    *srcp = src;
1207    return (r);
1208}
1209
1210