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