Deleted Added
sdiff udiff text old ( 10599:910fc5624d68 ) new ( 10601:6efb37480d87 )
full compact
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)
270{
271 memset(gdbregs.regs, 0, gdbregs.bytes());
272}
273
274BaseRemoteGDB::~BaseRemoteGDB()
275{
276 if (inputEvent)
277 delete inputEvent;
278}
279
280string
281BaseRemoteGDB::name()
282{
283 return system->name() + ".remote_gdb";
284}
285
286bool
287BaseRemoteGDB::isattached()
288{ return attached; }
289
290void
291BaseRemoteGDB::attach(int f)
292{
293 fd = f;
294
295 inputEvent = new InputEvent(this, fd, POLLIN);
296 pollQueue.schedule(inputEvent);
297
298 attached = true;
299 DPRINTFN("remote gdb attached\n");
300}
301
302void
303BaseRemoteGDB::detach()
304{
305 attached = false;
306 close(fd);
307 fd = -1;
308
309 pollQueue.remove(inputEvent);
310 DPRINTFN("remote gdb detached\n");
311}
312
313const char *
314BaseRemoteGDB::gdb_command(char cmd)
315{
316 switch (cmd) {
317 case GDBSignal: return "KGDB_SIGNAL";
318 case GDBSetBaud: return "KGDB_SET_BAUD";
319 case GDBSetBreak: return "KGDB_SET_BREAK";
320 case GDBCont: return "KGDB_CONT";
321 case GDBAsyncCont: return "KGDB_ASYNC_CONT";
322 case GDBDebug: return "KGDB_DEBUG";
323 case GDBDetach: return "KGDB_DETACH";
324 case GDBRegR: return "KGDB_REG_R";
325 case GDBRegW: return "KGDB_REG_W";
326 case GDBSetThread: return "KGDB_SET_THREAD";
327 case GDBCycleStep: return "KGDB_CYCLE_STEP";
328 case GDBSigCycleStep: return "KGDB_SIG_CYCLE_STEP";
329 case GDBKill: return "KGDB_KILL";
330 case GDBMemW: return "KGDB_MEM_W";
331 case GDBMemR: return "KGDB_MEM_R";
332 case GDBSetReg: return "KGDB_SET_REG";
333 case GDBReadReg: return "KGDB_READ_REG";
334 case GDBQueryVar: return "KGDB_QUERY_VAR";
335 case GDBSetVar: return "KGDB_SET_VAR";
336 case GDBReset: return "KGDB_RESET";
337 case GDBStep: return "KGDB_STEP";
338 case GDBAsyncStep: return "KGDB_ASYNC_STEP";
339 case GDBThreadAlive: return "KGDB_THREAD_ALIVE";
340 case GDBTargetExit: return "KGDB_TARGET_EXIT";
341 case GDBBinaryDload: return "KGDB_BINARY_DLOAD";
342 case GDBClrHwBkpt: return "KGDB_CLR_HW_BKPT";
343 case GDBSetHwBkpt: return "KGDB_SET_HW_BKPT";
344 case GDBStart: return "KGDB_START";
345 case GDBEnd: return "KGDB_END";
346 case GDBGoodP: return "KGDB_GOODP";
347 case GDBBadP: return "KGDB_BADP";
348 default: return "KGDB_UNKNOWN";
349 }
350}
351
352/////////////////////////
353//
354//
355
356uint8_t
357BaseRemoteGDB::getbyte()
358{
359 uint8_t b;
360 if (::read(fd, &b, 1) != 1)
361 warn("could not read byte from debugger");
362 return b;
363}
364
365void
366BaseRemoteGDB::putbyte(uint8_t b)
367{
368 if (::write(fd, &b, 1) != 1)
369 warn("could not write byte to debugger");
370}
371
372// Send a packet to gdb
373void
374BaseRemoteGDB::send(const char *bp)
375{
376 const char *p;
377 uint8_t csum, c;
378
379 DPRINTF(GDBSend, "send: %s\n", bp);
380
381 do {
382 p = bp;
383 //Start sending a packet
384 putbyte(GDBStart);
385 //Send the contents, and also keep a check sum.
386 for (csum = 0; (c = *p); p++) {
387 putbyte(c);
388 csum += c;
389 }
390 //Send the ending character.
391 putbyte(GDBEnd);
392 //Sent the checksum.
393 putbyte(i2digit(csum >> 4));
394 putbyte(i2digit(csum));
395 //Try transmitting over and over again until the other end doesn't send an
396 //error back.
397 } while ((c = getbyte() & 0x7f) == GDBBadP);
398}
399
400// Receive a packet from gdb
401int
402BaseRemoteGDB::recv(char *bp, int maxlen)
403{
404 char *p;
405 int c, csum;
406 int len;
407
408 do {
409 p = bp;
410 csum = len = 0;
411 //Find the beginning of a packet
412 while ((c = getbyte()) != GDBStart)
413 ;
414
415 //Read until you find the end of the data in the packet, and keep
416 //track of the check sum.
417 while ((c = getbyte()) != GDBEnd && len < maxlen) {
418 c &= 0x7f;
419 csum += c;
420 *p++ = c;
421 len++;
422 }
423
424 //Mask the check sum, and terminate the command string.
425 csum &= 0xff;
426 *p = '\0';
427
428 //If the command was too long, report an error.
429 if (len >= maxlen) {
430 putbyte(GDBBadP);
431 continue;
432 }
433
434 //Bring in the checksum. If the check sum matches, csum will be 0.
435 csum -= digit2i(getbyte()) * 16;
436 csum -= digit2i(getbyte());
437
438 //If the check sum was correct
439 if (csum == 0) {
440 //Report that the packet was received correctly
441 putbyte(GDBGoodP);
442 // Sequence present?
443 if (bp[2] == ':') {
444 putbyte(bp[0]);
445 putbyte(bp[1]);
446 len -= 3;
447 memcpy(bp, bp+3, len);
448 }
449 break;
450 }
451 //Otherwise, report that there was a mistake.
452 putbyte(GDBBadP);
453 } while (1);
454
455 DPRINTF(GDBRecv, "recv: %s: %s\n", gdb_command(*bp), bp);
456
457 return (len);
458}
459
460// Read bytes from kernel address space for debugger.
461bool
462BaseRemoteGDB::read(Addr vaddr, size_t size, char *data)
463{
464 static Addr lastaddr = 0;
465 static size_t lastsize = 0;
466
467 if (vaddr < 10) {
468 DPRINTF(GDBRead, "read: reading memory location zero!\n");
469 vaddr = lastaddr + lastsize;
470 }
471
472 DPRINTF(GDBRead, "read: addr=%#x, size=%d", vaddr, size);
473
474 if (FullSystem) {
475 FSTranslatingPortProxy &proxy = context->getVirtProxy();
476 proxy.readBlob(vaddr, (uint8_t*)data, size);
477 } else {
478 SETranslatingPortProxy &proxy = context->getMemProxy();
479 proxy.readBlob(vaddr, (uint8_t*)data, size);
480 }
481
482#if TRACING_ON
483 if (DTRACE(GDBRead)) {
484 if (DTRACE(GDBExtra)) {
485 char buf[1024];
486 mem2hex(buf, data, size);
487 DPRINTFNR(": %s\n", buf);
488 } else
489 DPRINTFNR("\n");
490 }
491#endif
492
493 return true;
494}
495
496// Write bytes to kernel address space for debugger.
497bool
498BaseRemoteGDB::write(Addr vaddr, size_t size, const char *data)
499{
500 static Addr lastaddr = 0;
501 static size_t lastsize = 0;
502
503 if (vaddr < 10) {
504 DPRINTF(GDBWrite, "write: writing memory location zero!\n");
505 vaddr = lastaddr + lastsize;
506 }
507
508 if (DTRACE(GDBWrite)) {
509 DPRINTFN("write: addr=%#x, size=%d", vaddr, size);
510 if (DTRACE(GDBExtra)) {
511 char buf[1024];
512 mem2hex(buf, data, size);
513 DPRINTFNR(": %s\n", buf);
514 } else
515 DPRINTFNR("\n");
516 }
517 if (FullSystem) {
518 FSTranslatingPortProxy &proxy = context->getVirtProxy();
519 proxy.writeBlob(vaddr, (uint8_t*)data, size);
520 } else {
521 SETranslatingPortProxy &proxy = context->getMemProxy();
522 proxy.writeBlob(vaddr, (uint8_t*)data, size);
523 }
524
525 return true;
526}
527
528PCEventQueue *BaseRemoteGDB::getPcEventQueue()
529{
530 return &system->pcEventQueue;
531}
532
533EventQueue *
534BaseRemoteGDB::getComInstEventQueue()
535{
536 BaseCPU *cpu = context->getCpuPtr();
537 return cpu->comInstEventQueue[context->threadId()];
538}
539
540void
541BaseRemoteGDB::scheduleInstCommitEvent(Event *ev, int delta)
542{
543 EventQueue *eq = getComInstEventQueue();
544 // Here "ticks" aren't simulator ticks which measure time, they're
545 // instructions committed by the CPU.
546 eq->schedule(ev, eq->getCurTick() + delta);
547}
548
549void
550BaseRemoteGDB::descheduleInstCommitEvent(Event *ev)
551{
552 if (ev->scheduled())
553 getComInstEventQueue()->deschedule(ev);
554}
555
556bool
557BaseRemoteGDB::checkBpLen(size_t len)
558{
559 return len == sizeof(MachInst);
560}
561
562BaseRemoteGDB::HardBreakpoint::HardBreakpoint(BaseRemoteGDB *_gdb, Addr pc)
563 : PCEvent(_gdb->getPcEventQueue(), "HardBreakpoint Event", pc),
564 gdb(_gdb), refcount(0)
565{
566 DPRINTF(GDBMisc, "creating hardware breakpoint at %#x\n", evpc);
567}
568
569void
570BaseRemoteGDB::HardBreakpoint::process(ThreadContext *tc)
571{
572 DPRINTF(GDBMisc, "handling hardware breakpoint at %#x\n", pc());
573
574 if (tc == gdb->context)
575 gdb->trap(SIGTRAP);
576}
577
578bool
579BaseRemoteGDB::insertSoftBreak(Addr addr, size_t len)
580{
581 if (!checkBpLen(len))
582 panic("invalid length\n");
583
584 return insertHardBreak(addr, len);
585}
586
587bool
588BaseRemoteGDB::removeSoftBreak(Addr addr, size_t len)
589{
590 if (!checkBpLen(len))
591 panic("invalid length\n");
592
593 return removeHardBreak(addr, len);
594}
595
596bool
597BaseRemoteGDB::insertHardBreak(Addr addr, size_t len)
598{
599 if (!checkBpLen(len))
600 panic("invalid length\n");
601
602 DPRINTF(GDBMisc, "inserting hardware breakpoint at %#x\n", addr);
603
604 HardBreakpoint *&bkpt = hardBreakMap[addr];
605 if (bkpt == 0)
606 bkpt = new HardBreakpoint(this, addr);
607
608 bkpt->refcount++;
609
610 return true;
611}
612
613bool
614BaseRemoteGDB::removeHardBreak(Addr addr, size_t len)
615{
616 if (!checkBpLen(len))
617 panic("invalid length\n");
618
619 DPRINTF(GDBMisc, "removing hardware breakpoint at %#x\n", addr);
620
621 break_iter_t i = hardBreakMap.find(addr);
622 if (i == hardBreakMap.end())
623 return false;
624
625 HardBreakpoint *hbp = (*i).second;
626 if (--hbp->refcount == 0) {
627 delete hbp;
628 hardBreakMap.erase(i);
629 }
630
631 return true;
632}
633
634void
635BaseRemoteGDB::setTempBreakpoint(Addr bkpt)
636{
637 DPRINTF(GDBMisc, "setTempBreakpoint: addr=%#x\n", bkpt);
638 insertHardBreak(bkpt, sizeof(TheISA::MachInst));
639}
640
641void
642BaseRemoteGDB::clearTempBreakpoint(Addr &bkpt)
643{
644 DPRINTF(GDBMisc, "setTempBreakpoint: addr=%#x\n", bkpt);
645 removeHardBreak(bkpt, sizeof(TheISA::MachInst));
646 bkpt = 0;
647}
648
649const char *
650BaseRemoteGDB::break_type(char c)
651{
652 switch(c) {
653 case '0': return "software breakpoint";
654 case '1': return "hardware breakpoint";
655 case '2': return "write watchpoint";
656 case '3': return "read watchpoint";
657 case '4': return "access watchpoint";
658 default: return "unknown breakpoint/watchpoint";
659 }
660}
661
662// This function does all command processing for interfacing to a
663// remote gdb. Note that the error codes are ignored by gdb at
664// present, but might eventually become meaningful. (XXX) It might
665// makes sense to use POSIX errno values, because that is what the
666// gdb/remote.c functions want to return.
667bool
668BaseRemoteGDB::trap(int type)
669{
670 uint64_t val;
671 size_t datalen, len;
672 char data[GDBPacketBufLen + 1];
673 char *buffer;
674 size_t bufferSize;
675 const char *p;
676 char command, subcmd;
677 string var;
678 bool ret;
679
680 if (!attached)
681 return false;
682
683 bufferSize = gdbregs.bytes() * 2 + 256;
684 buffer = (char*)malloc(bufferSize);
685
686 DPRINTF(GDBMisc, "trap: PC=%s\n", context->pcState());
687
688 clearSingleStep();
689
690 /*
691 * The first entry to this function is normally through
692 * a breakpoint trap in kgdb_connect(), in which case we
693 * must advance past the breakpoint because gdb will not.
694 *
695 * On the first entry here, we expect that gdb is not yet
696 * listening to us, so just enter the interaction loop.
697 * After the debugger is "active" (connected) it will be
698 * waiting for a "signaled" message from us.
699 */
700 if (!active) {
701 active = true;
702 } else {
703 // Tell remote host that an exception has occurred.
704 snprintf((char *)buffer, bufferSize, "S%02x", type);
705 send(buffer);
706 }
707
708 // Stick frame regs into our reg cache.
709 getregs();
710
711 for (;;) {
712 datalen = recv(data, sizeof(data));
713 data[sizeof(data) - 1] = 0; // Sentinel
714 command = data[0];
715 subcmd = 0;
716 p = data + 1;
717 switch (command) {
718
719 case GDBSignal:
720 // if this command came from a running gdb, answer it --
721 // the other guy has no way of knowing if we're in or out
722 // of this loop when he issues a "remote-signal".
723 snprintf((char *)buffer, bufferSize,
724 "S%02x", type);
725 send(buffer);
726 continue;
727
728 case GDBRegR:
729 if (2 * gdbregs.bytes() > bufferSize)
730 panic("buffer too small");
731
732 mem2hex(buffer, gdbregs.regs, gdbregs.bytes());
733 send(buffer);
734 continue;
735
736 case GDBRegW:
737 p = hex2mem(gdbregs.regs, p, gdbregs.bytes());
738 if (p == NULL || *p != '\0')
739 send("E01");
740 else {
741 setregs();
742 send("OK");
743 }
744 continue;
745
746#if 0
747 case GDBSetReg:
748 val = hex2i(&p);
749 if (*p++ != '=') {
750 send("E01");
751 continue;
752 }
753 if (val < 0 && val >= KGDB_NUMREGS) {
754 send("E01");
755 continue;
756 }
757
758 gdbregs.regs[val] = hex2i(&p);
759 setregs();
760 send("OK");
761
762 continue;
763#endif
764
765 case GDBMemR:
766 val = hex2i(&p);
767 if (*p++ != ',') {
768 send("E02");
769 continue;
770 }
771 len = hex2i(&p);
772 if (*p != '\0') {
773 send("E03");
774 continue;
775 }
776 if (len > bufferSize) {
777 send("E04");
778 continue;
779 }
780 if (!acc(val, len)) {
781 send("E05");
782 continue;
783 }
784
785 if (read(val, (size_t)len, (char *)buffer)) {
786 // variable length array would be nice, but C++ doesn't
787 // officially support those...
788 char *temp = new char[2*len+1];
789 mem2hex(temp, buffer, len);
790 send(temp);
791 delete [] temp;
792 } else {
793 send("E05");
794 }
795 continue;
796
797 case GDBMemW:
798 val = hex2i(&p);
799 if (*p++ != ',') {
800 send("E06");
801 continue;
802 }
803 len = hex2i(&p);
804 if (*p++ != ':') {
805 send("E07");
806 continue;
807 }
808 if (len > datalen - (p - data)) {
809 send("E08");
810 continue;
811 }
812 p = hex2mem(buffer, p, bufferSize);
813 if (p == NULL) {
814 send("E09");
815 continue;
816 }
817 if (!acc(val, len)) {
818 send("E0A");
819 continue;
820 }
821 if (write(val, (size_t)len, (char *)buffer))
822 send("OK");
823 else
824 send("E0B");
825 continue;
826
827 case GDBSetThread:
828 subcmd = *p++;
829 val = hex2i(&p);
830 if (val == 0)
831 send("OK");
832 else
833 send("E01");
834 continue;
835
836 case GDBDetach:
837 case GDBKill:
838 active = false;
839 clearSingleStep();
840 detach();
841 goto out;
842
843 case GDBAsyncCont:
844 subcmd = hex2i(&p);
845 if (*p++ == ';') {
846 val = hex2i(&p);
847 context->pcState(val);
848 }
849 clearSingleStep();
850 goto out;
851
852 case GDBCont:
853 if (p - data < (ptrdiff_t)datalen) {
854 val = hex2i(&p);
855 context->pcState(val);
856 }
857 clearSingleStep();
858 goto out;
859
860 case GDBAsyncStep:
861 subcmd = hex2i(&p);
862 if (*p++ == ';') {
863 val = hex2i(&p);
864 context->pcState(val);
865 }
866 setSingleStep();
867 goto out;
868
869 case GDBStep:
870 if (p - data < (ptrdiff_t)datalen) {
871 val = hex2i(&p);
872 context->pcState(val);
873 }
874 setSingleStep();
875 goto out;
876
877 case GDBClrHwBkpt:
878 subcmd = *p++;
879 if (*p++ != ',') send("E0D");
880 val = hex2i(&p);
881 if (*p++ != ',') send("E0D");
882 len = hex2i(&p);
883
884 DPRINTF(GDBMisc, "clear %s, addr=%#x, len=%d\n",
885 break_type(subcmd), val, len);
886
887 ret = false;
888
889 switch (subcmd) {
890 case '0': // software breakpoint
891 ret = removeSoftBreak(val, len);
892 break;
893
894 case '1': // hardware breakpoint
895 ret = removeHardBreak(val, len);
896 break;
897
898 case '2': // write watchpoint
899 case '3': // read watchpoint
900 case '4': // access watchpoint
901 default: // unknown
902 send("");
903 break;
904 }
905
906 send(ret ? "OK" : "E0C");
907 continue;
908
909 case GDBSetHwBkpt:
910 subcmd = *p++;
911 if (*p++ != ',') send("E0D");
912 val = hex2i(&p);
913 if (*p++ != ',') send("E0D");
914 len = hex2i(&p);
915
916 DPRINTF(GDBMisc, "set %s, addr=%#x, len=%d\n",
917 break_type(subcmd), val, len);
918
919 ret = false;
920
921 switch (subcmd) {
922 case '0': // software breakpoint
923 ret = insertSoftBreak(val, len);
924 break;
925
926 case '1': // hardware breakpoint
927 ret = insertHardBreak(val, len);
928 break;
929
930 case '2': // write watchpoint
931 case '3': // read watchpoint
932 case '4': // access watchpoint
933 default: // unknown
934 send("");
935 break;
936 }
937
938 send(ret ? "OK" : "E0C");
939 continue;
940
941 case GDBQueryVar:
942 var = string(p, datalen - 1);
943 if (var == "C")
944 send("QC0");
945 else
946 send("");
947 continue;
948
949 case GDBSetBaud:
950 case GDBSetBreak:
951 case GDBDebug:
952 case GDBCycleStep:
953 case GDBSigCycleStep:
954 case GDBReadReg:
955 case GDBSetVar:
956 case GDBReset:
957 case GDBThreadAlive:
958 case GDBTargetExit:
959 case GDBBinaryDload:
960 // Unsupported command
961 DPRINTF(GDBMisc, "Unsupported command: %s\n",
962 gdb_command(command));
963 DDUMP(GDBMisc, (uint8_t *)data, datalen);
964 send("");
965 continue;
966
967 default:
968 // Unknown command.
969 DPRINTF(GDBMisc, "Unknown command: %c(%#x)\n",
970 command, command);
971 send("");
972 continue;
973
974
975 }
976 }
977
978 out:
979 free(buffer);
980 return true;
981}
982
983// Convert a hex digit into an integer.
984// This returns -1 if the argument passed is no valid hex digit.
985int
986BaseRemoteGDB::digit2i(char c)
987{
988 if (c >= '0' && c <= '9')
989 return (c - '0');
990 else if (c >= 'a' && c <= 'f')
991 return (c - 'a' + 10);
992 else if (c >= 'A' && c <= 'F')
993
994 return (c - 'A' + 10);
995 else
996 return (-1);
997}
998
999// Convert the low 4 bits of an integer into an hex digit.
1000char
1001BaseRemoteGDB::i2digit(int n)
1002{
1003 return ("0123456789abcdef"[n & 0x0f]);
1004}
1005
1006// Convert a byte array into an hex string.
1007void
1008BaseRemoteGDB::mem2hex(void *vdst, const void *vsrc, int len)
1009{
1010 char *dst = (char *)vdst;
1011 const char *src = (const char *)vsrc;
1012
1013 while (len--) {
1014 *dst++ = i2digit(*src >> 4);
1015 *dst++ = i2digit(*src++);
1016 }
1017 *dst = '\0';
1018}
1019
1020// Convert an hex string into a byte array.
1021// This returns a pointer to the character following the last valid
1022// hex digit. If the string ends in the middle of a byte, NULL is
1023// returned.
1024const char *
1025BaseRemoteGDB::hex2mem(void *vdst, const char *src, int maxlen)
1026{
1027 char *dst = (char *)vdst;
1028 int msb, lsb;
1029
1030 while (*src && maxlen--) {
1031 msb = digit2i(*src++);
1032 if (msb < 0)
1033 return (src - 1);
1034 lsb = digit2i(*src++);
1035 if (lsb < 0)
1036 return (NULL);
1037 *dst++ = (msb << 4) | lsb;
1038 }
1039 return (src);
1040}
1041
1042// Convert an hex string into an integer.
1043// This returns a pointer to the character following the last valid
1044// hex digit.
1045Addr
1046BaseRemoteGDB::hex2i(const char **srcp)
1047{
1048 const char *src = *srcp;
1049 Addr r = 0;
1050 int nibble;
1051
1052 while ((nibble = digit2i(*src)) >= 0) {
1053 r *= 16;
1054 r += nibble;
1055 src++;
1056 }
1057 *srcp = src;
1058 return (r);
1059}
1060