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