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