OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [or1ksim/] [debug/] [rsp-server.c] - Blame information for rev 85

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 19 jeremybenn
/* rsp-server.c -- Remote Serial Protocol server for GDB
2
 
3
   Copyright (C) 2008 Embecosm Limited
4
 
5
   Contributor Jeremy Bennett <jeremy.bennett@embecosm.com>
6
 
7
   This file is part of Or1ksim, the OpenRISC 1000 Architectural Simulator.
8
 
9
   This program is free software; you can redistribute it and/or modify it
10
   under the terms of the GNU General Public License as published by the Free
11
   Software Foundation; either version 3 of the License, or (at your option)
12
   any later version.
13
 
14
   This program is distributed in the hope that it will be useful, but WITHOUT
15
   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16
   FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
17
   more details.
18
 
19
   You should have received a copy of the GNU General Public License along
20
   with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
 
22
/* This program is commented throughout in a fashion suitable for processing
23
   with Doxygen. */
24
 
25
 
26
/* Autoconf and/or portability configuration */
27
#include "config.h"
28
#include "port.h"
29
 
30
/* System includes */
31
#include <stdlib.h>
32
#include <unistd.h>
33
#include <netdb.h>
34
#include <stdio.h>
35
#include <errno.h>
36
#include <sys/types.h>
37
#include <sys/socket.h>
38
#include <fcntl.h>
39
#include <arpa/inet.h>
40
#include <poll.h>
41
#include <netinet/tcp.h>
42
#include <signal.h>
43
 
44
/* Package includes */
45
#include "sim-config.h"
46
#include "except.h"
47
#include "opcode/or32.h"
48
#include "spr-defs.h"
49
#include "execute.h"
50
#include "debug-unit.h"
51
#include "sprs.h"
52
#include "toplevel-support.h"
53
 
54
 
55
/* Define to log each packet */
56
/* #define RSP_TRACE  1 */
57
 
58
/*! Name of the Or1ksim RSP service */
59
#define OR1KSIM_RSP_SERVICE  "or1ksim-rsp"
60
 
61
/*! Protocol used by Or1ksim */
62
#define OR1KSIM_RSP_PROTOCOL  "tcp"
63
 
64
/*! Thread ID used by Or1ksim */
65
#define OR1KSIM_TID  1
66
 
67
/* Indices of GDB registers that are not GPRs. Must match GDB settings! */
68
#define PPC_REGNUM  (MAX_GPRS + 0)      /*!< Previous PC */
69
#define NPC_REGNUM  (MAX_GPRS + 1)      /*!< Next PC */
70
#define SR_REGNUM   (MAX_GPRS + 2)      /*!< Supervision Register */
71
#define NUM_REGS    (MAX_GRPS + 3)      /*!< Total GDB registers */
72
 
73
/*! Trap instruction for OR32 */
74
#define OR1K_TRAP_INSTR  0x21000001
75
 
76
/*! Definition of GDB target signals. Data taken from the GDB 6.8
77
    source. Only those we use defined here. */
78
enum target_signal {
79
  TARGET_SIGNAL_NONE =  0,
80
  TARGET_SIGNAL_INT  =  2,
81
  TARGET_SIGNAL_ILL  =  4,
82
  TARGET_SIGNAL_TRAP =  5,
83
  TARGET_SIGNAL_FPE  =  8,
84
  TARGET_SIGNAL_BUS  = 10,
85
  TARGET_SIGNAL_SEGV = 11,
86
  TARGET_SIGNAL_ALRM = 14,
87
  TARGET_SIGNAL_USR2 = 31,
88
  TARGET_SIGNAL_PWR  = 32
89
};
90
 
91
/*! The maximum number of characters in inbound/outbound buffers.  The largest
92
    packets are the 'G' packet, which must hold the 'G' and all the registers
93
    with two hex digits per byte and the 'g' reply, which must hold all the
94
    registers, and (in our implementation) an end-of-string (0)
95
    character. Adding the EOS allows us to print out the packet as a
96
    string. So at least NUMREGBYTES*2 + 1 (for the 'G' or the EOS) are needed
97
    for register packets */
98
#define GDB_BUF_MAX  ((NUM_REGS) * 8 + 1)
99
 
100
/*! Size of the matchpoint hash table. Largest prime < 2^10 */
101
#define MP_HASH_SIZE  1021
102
 
103
/*! String to map hex digits to chars */
104
static const char hexchars[]="0123456789abcdef";
105
 
106
/*! Data structure for RSP buffers. Can't be null terminated, since it may
107
  include zero bytes */
108
struct rsp_buf
109
{
110
  char  data[GDB_BUF_MAX];
111
  int   len;
112
};
113
 
114
/*! Enumeration of different types of matchpoint. These have explicit values
115
    matching the second digit of 'z' and 'Z' packets. */
116
enum mp_type {
117
  BP_MEMORY   = 0,
118
  BP_HARDWARE = 1,
119
  WP_WRITE    = 2,
120
  WP_READ     = 3,
121
  WP_ACCESS   = 4
122
};
123
 
124
/*! Data structure for a matchpoint hash table entry */
125
struct mp_entry
126
{
127
  enum mp_type       type;              /*!< Type of matchpoint */
128
  unsigned long int  addr;              /*!< Address with the matchpoint */
129
  unsigned long int  instr;             /*!< Substituted instruction */
130
  struct mp_entry   *next;              /*!< Next entry with this hash */
131
};
132
 
133
/*! Central data for the RSP connection */
134
static struct
135
{
136
  int                client_waiting;    /*!< Is client waiting a response? */
137
  int                proto_num;         /*!< Number of the protocol used */
138
  int                client_fd;         /*!< FD for talking to GDB */
139
  int                sigval;            /*!< GDB signal for any exception */
140
  unsigned long int  start_addr;        /*!< Start of last run */
141
  struct mp_entry   *mp_hash[MP_HASH_SIZE];     /*!< Matchpoint hash table */
142
} rsp;
143
 
144
/* Forward declarations of static functions */
145
static void               rsp_get_client ();
146
static void               rsp_client_request ();
147
static void               rsp_client_close ();
148
static void               put_packet (struct rsp_buf *buf);
149
static void               put_str_packet (const char *str);
150
static struct rsp_buf    *get_packet ();
151
static void               put_rsp_char (char  c);
152
static int                get_rsp_char ();
153
static int                rsp_unescape (char *data,
154
                                        int   len);
155
static void               mp_hash_init ();
156
static void               mp_hash_add (enum mp_type       type,
157
                                       unsigned long int  addr,
158
                                       unsigned long int  instr);
159
static struct mp_entry   *mp_hash_lookup (enum mp_type       type,
160
                                          unsigned long int  addr);
161
static struct mp_entry   *mp_hash_delete (enum mp_type       type,
162
                                          unsigned long int  addr);
163
static int                hex (int  c);
164
static void               reg2hex (unsigned long int  val,
165
                                   char              *buf);
166
static unsigned long int  hex2reg (char *buf);
167
static void               ascii2hex (char *dest,
168
                                     char *src);
169
static void               hex2ascii (char *dest,
170
                                     char *src);
171
static void               set_npc (unsigned long int  addr);
172
static void               rsp_report_exception ();
173
static void               rsp_continue (struct rsp_buf *buf);
174
static void               rsp_continue_with_signal (struct rsp_buf *buf);
175
static void               rsp_continue_generic (unsigned long int  addr,
176
                                                unsigned long int  except);
177
static void               rsp_read_all_regs ();
178
static void               rsp_write_all_regs (struct rsp_buf *buf);
179
static void               rsp_read_mem (struct rsp_buf *buf);
180
static void               rsp_write_mem (struct rsp_buf *buf);
181
static void               rsp_read_reg (struct rsp_buf *buf);
182
static void               rsp_write_reg (struct rsp_buf *buf);
183
static void               rsp_query (struct rsp_buf *buf);
184
static void               rsp_command (struct rsp_buf *buf);
185
static void               rsp_set (struct rsp_buf *buf);
186
static void               rsp_restart ();
187
static void               rsp_step (struct rsp_buf *buf);
188
static void               rsp_step_with_signal (struct rsp_buf *buf);
189
static void               rsp_step_generic (unsigned long int  addr,
190
                                            unsigned long int  except);
191
static void               rsp_vpkt (struct rsp_buf *buf);
192
static void               rsp_write_mem_bin (struct rsp_buf *buf);
193
static void               rsp_remove_matchpoint (struct rsp_buf *buf);
194
static void               rsp_insert_matchpoint (struct rsp_buf *buf);
195
 
196
 
197
/*---------------------------------------------------------------------------*/
198
/*!Initialize the Remote Serial Protocol connection
199
 
200
   Set up the central data structures.                                       */
201
/*---------------------------------------------------------------------------*/
202
void
203
rsp_init ()
204
{
205
  /* Clear out the central data structure */
206
  rsp.client_waiting =  0;               /* GDB client is not waiting for us */
207
  rsp.client_fd      = -1;              /* i.e. invalid */
208
  rsp.sigval         =  0;               /* No exception */
209
  rsp.start_addr     = EXCEPT_RESET;    /* Default restart point */
210
 
211
  /* Set up the matchpoint hash table */
212
  mp_hash_init ();
213
 
214
}       /* rsp_init () */
215
 
216
 
217
/*---------------------------------------------------------------------------*/
218
/*!Look for action on RSP
219
 
220
   This function is called when the processor has stalled, which, except for
221
   initialization, must be due to an interrupt.
222
 
223
   If we have no RSP client, we get one. We can make no progress until the
224
   client is available.
225
 
226
   Then if the cause is an exception following a step or continue command, and
227
   the exception not been notified to GDB, a packet reporting the cause of the
228
   exception is sent.
229
 
230
   The next client request is then processed.                                */
231
/*---------------------------------------------------------------------------*/
232
void
233
handle_rsp ()
234
{
235
  /* If we have no RSP client, wait until we get one. */
236
  while (-1 == rsp.client_fd)
237
    {
238
      rsp_get_client ();
239
      rsp.client_waiting = 0;            /* No longer waiting */
240
    }
241
 
242
  /* If we have an unacknowledged exception tell the GDB client. If this
243
     exception was a trap due to a memory breakpoint, then adjust the NPC. */
244
  if (rsp.client_waiting)
245
    {
246
      if ((TARGET_SIGNAL_TRAP == rsp.sigval) &&
247
          (NULL != mp_hash_lookup (BP_MEMORY, cpu_state.sprs[SPR_PPC])))
248
        {
249
          set_npc (cpu_state.sprs[SPR_PPC]);
250
        }
251
 
252
      rsp_report_exception();
253
      rsp.client_waiting = 0;            /* No longer waiting */
254
    }
255
 
256
  /* Get a RSP client request */
257
  rsp_client_request ();
258
 
259
}       /* handle_rsp () */
260
 
261
 
262
/*---------------------------------------------------------------------------*/
263
/*!Note an exception for future processing
264
 
265
   The simulator has encountered an exception. Record it here, so that a
266
   future call to handle_exception will report it back to the client. The
267
   signal is supplied in Or1ksim form and recorded in GDB form.
268
 
269
   We flag up a warning if an exception is already pending, and ignore the
270
   earlier exception.
271
 
272
   @param[in] except  The exception (Or1ksim form)                           */
273
/*---------------------------------------------------------------------------*/
274
void
275
rsp_exception (unsigned long int  except)
276
{
277
  int  sigval;                  /* GDB signal equivalent to exception */
278
 
279
  switch (except)
280
    {
281
    case EXCEPT_RESET:    sigval = TARGET_SIGNAL_PWR;  break;
282
    case EXCEPT_BUSERR:   sigval = TARGET_SIGNAL_BUS;  break;
283
    case EXCEPT_DPF:      sigval = TARGET_SIGNAL_SEGV; break;
284
    case EXCEPT_IPF:      sigval = TARGET_SIGNAL_SEGV; break;
285
    case EXCEPT_TICK:     sigval = TARGET_SIGNAL_ALRM; break;
286
    case EXCEPT_ALIGN:    sigval = TARGET_SIGNAL_BUS;  break;
287
    case EXCEPT_ILLEGAL:  sigval = TARGET_SIGNAL_ILL;  break;
288
    case EXCEPT_INT:      sigval = TARGET_SIGNAL_INT;  break;
289
    case EXCEPT_DTLBMISS: sigval = TARGET_SIGNAL_SEGV; break;
290
    case EXCEPT_ITLBMISS: sigval = TARGET_SIGNAL_SEGV; break;
291
    case EXCEPT_RANGE:    sigval = TARGET_SIGNAL_FPE;  break;
292
    case EXCEPT_SYSCALL:  sigval = TARGET_SIGNAL_USR2; break;
293
    case EXCEPT_FPE:      sigval = TARGET_SIGNAL_FPE;  break;
294
    case EXCEPT_TRAP:     sigval = TARGET_SIGNAL_TRAP; break;
295
 
296
    default:
297
      fprintf (stderr, "Warning: Unknown RSP exception %lu: Ignored\n", except);
298
      return;
299
    }
300
 
301
  if ((0 != rsp.sigval) && (sigval != rsp.sigval))
302
    {
303
      fprintf (stderr, "Warning: RSP signal %d received while signal "
304
               "%d pending: Pending exception replaced\n", sigval, rsp.sigval);
305
    }
306
 
307
  rsp.sigval         = sigval;          /* Save the signal value */
308
 
309
}       /* rsp_exception () */
310
 
311
 
312
/*---------------------------------------------------------------------------*/
313
/*!Get a new client connection.
314
 
315
   Blocks until the client connection is available.
316
 
317
   A lot of this code is copied from remote_open in gdbserver remote-utils.c.
318
 
319
   This involves setting up a socket to listen on a socket for attempted
320
   connections from a single GDB instance (we couldn't be talking to multiple
321
   GDBs at once!).
322
 
323
   The service is specified either as a port number in the Or1ksim configuration
324
   (parameter rsp_port in section debug, default 51000) or as a service name
325
   in the constant OR1KSIM_RSP_SERVICE.
326
 
327
   The protocol used for communication is specified in OR1KSIM_RSP_PROTOCOL. */
328
/*---------------------------------------------------------------------------*/
329
static void
330
rsp_get_client ()
331
{
332
  int                 tmp_fd;           /* Temporary descriptor for socket */
333
  int                 optval;           /* Socket options */
334
  struct sockaddr_in  sock_addr;        /* Socket address */
335
  socklen_t           len;              /* Size of the socket address */
336
 
337
  /* 0 is used as the RSP port number to indicate that we should use the
338
     service name instead. */
339
  if (0 == config.debug.rsp_port)
340
    {
341
      struct servent *service =
342
        getservbyname (OR1KSIM_RSP_SERVICE, "tcp");
343
 
344
      if (NULL == service)
345
        {
346
          fprintf (stderr, "Warning: RSP unable to find service \"%s\": %s\n",
347
                   OR1KSIM_RSP_SERVICE, strerror (errno));
348
          return;
349
        }
350
 
351
      config.debug.rsp_port = ntohs (service->s_port);
352
    }
353
 
354
  /* Open a socket on which we'll listen for clients */
355
  tmp_fd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
356
  if (tmp_fd < 0)
357
    {
358
      fprintf (stderr, "ERROR: Cannot open RSP socket\n");
359
      sim_done ();
360
    }
361
 
362
  /* Allow rapid reuse of the port on this socket */
363
  optval = 1;
364
  setsockopt (tmp_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval,
365
              sizeof (optval));
366
 
367
  /* Bind the port to the socket */
368
  sock_addr.sin_family      = PF_INET;
369
  sock_addr.sin_port        = htons (config.debug.rsp_port);
370
  sock_addr.sin_addr.s_addr = INADDR_ANY;
371
  if (bind (tmp_fd, (struct sockaddr *) &sock_addr, sizeof (sock_addr)))
372
    {
373
      fprintf (stderr, "ERROR: Cannot bind to RSP socket\n");
374
      sim_done ();
375
    }
376
 
377
  /* Listen for (at most one) client */
378
  if (listen (tmp_fd, 1))
379
    {
380
      fprintf (stderr, "ERROR: Cannot listen on RSP socket\n");
381
      sim_done ();
382
    }
383
 
384
  printf ("Listening for RSP on port %d\n", config.debug.rsp_port);
385
  fflush (stdout);
386
 
387
  /* Accept a client which connects */
388 85 jeremybenn
  len = sizeof (socklen_t);             /* Bug fix by Julius Baxter */
389 19 jeremybenn
  rsp.client_fd = accept (tmp_fd, (struct sockaddr *)&sock_addr, &len);
390
 
391
  if (-1 == rsp.client_fd)
392
    {
393
      fprintf (stderr, "Warning: Failed to accept RSP client\n");
394
      return;
395
    }
396
 
397
  /* Enable TCP keep alive process */
398
  optval = 1;
399
  setsockopt (rsp.client_fd, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval,
400
              sizeof (optval));
401
 
402
  /* Don't delay small packets, for better interactive response (disable
403
     Nagel's algorithm) */
404
  optval = 1;
405
  setsockopt (rsp.client_fd, IPPROTO_TCP, TCP_NODELAY, (char *)&optval,
406
              sizeof (optval));
407
 
408
  /* Socket is no longer needed */
409
  close (tmp_fd);                       /* No longer need this */
410
  signal (SIGPIPE, SIG_IGN);            /* So we don't exit if client dies */
411
 
412
  printf ("Remote debugging from host %s\n", inet_ntoa (sock_addr.sin_addr));
413
 
414
  /* If fcntl () is available, use it to enable async I/O
415
#if defined(F_SETFL) && defined (FASYNC)
416
  save_fcntl_flags = fcntl (remote_desc, F_GETFL, 0);
417
  fcntl (remote_desc, F_SETFL, save_fcntl_flags | FASYNC);
418
#if defined (F_SETOWN)
419
  fcntl (remote_desc, F_SETOWN, getpid ());
420
#endif
421
#endif */
422
 
423
}       /* rsp_get_client () */
424
 
425
 
426
/*---------------------------------------------------------------------------*/
427
/*!Deal with a request from the GDB client session
428
 
429
   In general, apart from the simplest requests, this function replies on
430
   other functions to implement the functionality.                           */
431
/*---------------------------------------------------------------------------*/
432
static void
433
rsp_client_request ()
434
{
435
  struct rsp_buf *buf = get_packet ();  /* Message sent to us */
436
 
437
  // Null packet means we hit EOF or the link was closed for some other
438
  // reason. Close the client and return
439
  if (NULL == buf)
440
    {
441
      rsp_client_close ();
442
      return;
443
    }
444
 
445
#if RSP_TRACE
446
  printf ("Packet received %s: %d chars\n", buf->data, buf->len );
447
  fflush (stdout);
448
#endif
449
 
450
  switch (buf->data[0])
451
    {
452
    case '!':
453
      /* Request for extended remote mode */
454
      put_str_packet ("OK");
455
      return;
456
 
457
    case '?':
458
      /* Return last signal ID */
459
      rsp_report_exception();
460
      return;
461
 
462
    case 'A':
463
      /* Initialization of argv not supported */
464
      fprintf (stderr, "Warning: RSP 'A' packet not supported: ignored\n");
465
      put_str_packet ("E01");
466
      return;
467
 
468
    case 'b':
469
      /* Setting baud rate is deprecated */
470
      fprintf (stderr, "Warning: RSP 'b' packet is deprecated and not "
471
               "supported: ignored\n");
472
      return;
473
 
474
    case 'B':
475
      /* Breakpoints should be set using Z packets */
476
      fprintf (stderr, "Warning: RSP 'B' packet is deprecated (use 'Z'/'z' "
477
               "packets instead): ignored\n");
478
      return;
479
 
480
    case 'c':
481
      /* Continue */
482
      rsp_continue (buf);
483
      return;
484
 
485
    case 'C':
486
      /* Continue with signal */
487
      rsp_continue_with_signal (buf);
488
      return;
489
 
490
    case 'd':
491
      /* Disable debug using a general query */
492
      fprintf (stderr, "Warning: RSP 'd' packet is deprecated (define a 'Q' "
493
               "packet instead: ignored\n");
494
      return;
495
 
496
    case 'D':
497
      /* Detach GDB. Do this by closing the client. The rules say that
498
         execution should continue. TODO. Is this really then intended
499
         meaning? Or does it just mean that only vAttach will be recognized
500
         after this? */
501
      put_str_packet ("OK");
502
      rsp_client_close ();
503
      set_stall_state (0);
504
      rsp.sigval = TARGET_SIGNAL_NONE;  /* No signal now */
505
      return;
506
 
507
    case 'F':
508
      /* File I/O is not currently supported */
509
      fprintf (stderr, "Warning: RSP file I/O not currently supported: 'F' "
510
               "packet ignored\n");
511
      return;
512
 
513
    case 'g':
514
      rsp_read_all_regs ();
515
      return;
516
 
517
    case 'G':
518
      rsp_write_all_regs (buf);
519
      return;
520
 
521
    case 'H':
522
      /* Set the thread number of subsequent operations. For now ignore
523
         silently and just reply "OK" */
524
      put_str_packet ("OK");
525
      return;
526
 
527
    case 'i':
528
      /* Single instruction step */
529
      fprintf (stderr, "Warning: RSP cycle stepping not supported: target "
530
               "stopped immediately\n");
531
      rsp.client_waiting = 1;                   /* Stop reply will be sent */
532
      return;
533
 
534
    case 'I':
535
      /* Single instruction step with signal */
536
      fprintf (stderr, "Warning: RSP cycle stepping not supported: target "
537
               "stopped immediately\n");
538
      rsp.client_waiting = 1;                   /* Stop reply will be sent */
539
      return;
540
 
541
    case 'k':
542
      /* Kill request. Do nothing for now. */
543
      return;
544
 
545
    case 'm':
546
      /* Read memory (symbolic) */
547
      rsp_read_mem (buf);
548
      return;
549
 
550
    case 'M':
551
      /* Write memory (symbolic) */
552
      rsp_write_mem (buf);
553
      return;
554
 
555
    case 'p':
556
      /* Read a register */
557
      rsp_read_reg (buf);
558
      return;
559
 
560
    case 'P':
561
      /* Write a register */
562
      rsp_write_reg (buf);
563
      return;
564
 
565
    case 'q':
566
      /* Any one of a number of query packets */
567
      rsp_query (buf);
568
      return;
569
 
570
    case 'Q':
571
      /* Any one of a number of set packets */
572
      rsp_set (buf);
573
      return;
574
 
575
    case 'r':
576
      /* Reset the system. Deprecated (use 'R' instead) */
577
      fprintf (stderr, "Warning: RSP 'r' packet is deprecated (use 'R' "
578
               "packet instead): ignored\n");
579
      return;
580
 
581
    case 'R':
582
      /* Restart the program being debugged. */
583
      rsp_restart ();
584
      return;
585
 
586
    case 's':
587
      /* Single step (one high level instruction). This could be hard without
588
         DWARF2 info */
589
      rsp_step (buf);
590
      return;
591
 
592
    case 'S':
593
      /* Single step (one high level instruction) with signal. This could be
594
         hard without DWARF2 info */
595
      rsp_step_with_signal (buf);
596
      return;
597
 
598
    case 't':
599
      /* Search. This is not well defined in the manual and for now we don't
600
         support it. No response is defined. */
601
      fprintf (stderr, "Warning: RSP 't' packet not supported: ignored\n");
602
      return;
603
 
604
    case 'T':
605
      /* Is the thread alive. We are bare metal, so don't have a thread
606
         context. The answer is always "OK". */
607
      put_str_packet ("OK");
608
      return;
609
 
610
    case 'v':
611
      /* Any one of a number of packets to control execution */
612
      rsp_vpkt (buf);
613
      return;
614
 
615
    case 'X':
616
      /* Write memory (binary) */
617
      rsp_write_mem_bin (buf);
618
      return;
619
 
620
    case 'z':
621
      /* Remove a breakpoint/watchpoint. */
622
      rsp_remove_matchpoint (buf);
623
      return;
624
 
625
    case 'Z':
626
      /* Insert a breakpoint/watchpoint. */
627
      rsp_insert_matchpoint (buf);
628
      return;
629
 
630
    default:
631
      /* Unknown commands are ignored */
632
      fprintf (stderr, "Warning: Unknown RSP request %s\n", buf->data);
633
      return;
634
    }
635
}       /* rsp_client_request () */
636
 
637
 
638
/*---------------------------------------------------------------------------*/
639
/*!Close the connection to the client if it is open                          */
640
/*---------------------------------------------------------------------------*/
641
static void
642
rsp_client_close ()
643
{
644
  if (-1 != rsp.client_fd)
645
    {
646
      close (rsp.client_fd);
647
      rsp.client_fd = -1;
648
    }
649
}       /* rsp_client_close () */
650
 
651
 
652
/*---------------------------------------------------------------------------*/
653
/*!Send a packet to the GDB client
654
 
655
   Modeled on the stub version supplied with GDB. Put out the data preceded by
656
   a '$', followed by a '#' and a one byte checksum. '$', '#', '*' and '}' are
657
   escaped by preceding them with '}' and then XORing the character with
658
   0x20.
659
 
660
   @param[in] buf  The data to send                                          */
661
/*---------------------------------------------------------------------------*/
662
static void
663
put_packet (struct rsp_buf *buf)
664
{
665
  int  ch;                              /* Ack char */
666
 
667
  /* Construct $<packet info>#<checksum>. Repeat until the GDB client
668
     acknowledges satisfactory receipt. */
669
  do
670
    {
671
      unsigned char checksum = 0;        /* Computed checksum */
672
      int           count    = 0;        /* Index into the buffer */
673
 
674
#if RSP_TRACE
675
      printf ("Putting %s\n", buf->data);
676
      fflush (stdout);
677
#endif
678
 
679
      put_rsp_char ('$');               /* Start char */
680
 
681
      /* Body of the packet */
682
      for (count = 0; count < buf->len; count++)
683
        {
684
          unsigned char  ch = buf->data[count];
685
 
686
          /* Check for escaped chars */
687
          if (('$' == ch) || ('#' == ch) || ('*' == ch) || ('}' == ch))
688
            {
689
              ch       ^= 0x20;
690
              checksum += (unsigned char)'}';
691
              put_rsp_char ('}');
692
            }
693
 
694
          checksum += ch;
695
          put_rsp_char (ch);
696
        }
697
 
698
      put_rsp_char ('#');               /* End char */
699
 
700
      /* Computed checksum */
701
      put_rsp_char (hexchars[checksum >> 4]);
702
      put_rsp_char (hexchars[checksum % 16]);
703
 
704
      /* Check for ack of connection failure */
705
      ch = get_rsp_char ();
706
      if (-1 == ch)
707
        {
708
          return;                       /* Fail the put silently. */
709
        }
710
    }
711
  while ('+' != ch);
712
 
713
}       /* put_packet () */
714
 
715
 
716
/*---------------------------------------------------------------------------*/
717
/*!Convenience to put a constant string packet
718
 
719
   param[in] str  The text of the packet                                     */
720
/*---------------------------------------------------------------------------*/
721
static void
722
put_str_packet (const char *str)
723
{
724
  struct rsp_buf  buf;
725
  int             len = strlen (str);
726
 
727
  /* Construct the packet to send, so long as string is not too big,
728
     otherwise truncate. Add EOS at the end for convenient debug printout */
729
 
730
  if (len >= GDB_BUF_MAX)
731
    {
732
      fprintf (stderr, "Warning: String %s too large for RSP packet: "
733
               "truncated\n", str);
734
      len = GDB_BUF_MAX - 1;
735
    }
736
 
737
  strncpy (buf.data, str, len);
738
  buf.data[len] = 0;
739
  buf.len       = len;
740
 
741
  put_packet (&buf);
742
 
743
}       /* put_str_packet () */
744
 
745
 
746
/*---------------------------------------------------------------------------*/
747
/*!Get a packet from the GDB client
748
 
749
   Modeled on the stub version supplied with GDB. The data is in a static
750
   buffer. The data should be copied elsewhere if it is to be preserved across
751
   a subsequent call to get_packet().
752
 
753
   Unlike the reference implementation, we don't deal with sequence
754
   numbers. GDB has never used them, and this implementation is only intended
755
   for use with GDB 6.8 or later. Sequence numbers were removed from the RSP
756
   standard at GDB 5.0.
757
 
758
   @return  A pointer to the static buffer containing the data                */
759
/*---------------------------------------------------------------------------*/
760
static struct rsp_buf *
761
get_packet ()
762
{
763
  static struct rsp_buf  buf;           /* Survives the return */
764
 
765
  /* Keep getting packets, until one is found with a valid checksum */
766
  while (1)
767
    {
768
      unsigned char  checksum;          /* The checksum we have computed */
769
      int            count;             /* Index into the buffer */
770
      int            ch;                /* Current character */
771
 
772
      /* Wait around for the start character ('$'). Ignore all other
773
         characters */
774
      ch = get_rsp_char ();
775
      while (ch != '$')
776
        {
777
          if (-1 == ch)
778
            {
779
              return  NULL;             /* Connection failed */
780
            }
781
 
782
          ch = get_rsp_char ();
783
        }
784
 
785
      /* Read until a '#' or end of buffer is found */
786
      checksum =  0;
787
      count    =  0;
788
      while (count < GDB_BUF_MAX - 1)
789
        {
790
          ch = get_rsp_char ();
791
 
792
          /* Check for connection failure */
793
          if (-1 == ch)
794
            {
795
              return  NULL;
796
            }
797
 
798
          /* If we hit a start of line char begin all over again */
799
          if ('$' == ch)
800
            {
801
              checksum =  0;
802
              count    =  0;
803
 
804
              continue;
805
            }
806
 
807
          /* Break out if we get the end of line char */
808
          if ('#' == ch)
809
            {
810
              break;
811
            }
812
 
813
          /* Update the checksum and add the char to the buffer */
814
 
815
          checksum        = checksum + (unsigned char)ch;
816
          buf.data[count] = (char)ch;
817
          count           = count + 1;
818
        }
819
 
820
      /* Mark the end of the buffer with EOS - it's convenient for non-binary
821
         data to be valid strings. */
822
      buf.data[count] = 0;
823
      buf.len         = count;
824
 
825
      /* If we have a valid end of packet char, validate the checksum */
826
      if ('#' == ch)
827
        {
828
          unsigned char  xmitcsum;      /* The checksum in the packet */
829
 
830
          ch = get_rsp_char ();
831
          if (-1 == ch)
832
            {
833
              return  NULL;             /* Connection failed */
834
            }
835
          xmitcsum = hex (ch) << 4;
836
 
837
          ch = get_rsp_char ();
838
          if (-1 == ch)
839
            {
840
              return  NULL;             /* Connection failed */
841
            }
842
 
843
          xmitcsum += hex (ch);
844
 
845
          /* If the checksums don't match print a warning, and put the
846
             negative ack back to the client. Otherwise put a positive ack. */
847
          if (checksum != xmitcsum)
848
            {
849
              fprintf (stderr, "Warning: Bad RSP checksum: Computed "
850
                       "0x%02x, received 0x%02x\n", checksum, xmitcsum);
851
 
852
              put_rsp_char ('-');       /* Failed checksum */
853
            }
854
          else
855
            {
856
              put_rsp_char ('+');       /* successful transfer */
857
              break;
858
            }
859
        }
860
      else
861
        {
862
          fprintf (stderr, "Warning: RSP packet overran buffer\n");
863
        }
864
    }
865
 
866
  return &buf;                          /* Success */
867
 
868
}       /* get_packet () */
869
 
870
 
871
/*---------------------------------------------------------------------------*/
872
/*!Put a single character out onto the client socket
873
 
874
   This should only be called if the client is open, but we check for safety.
875
 
876
   @param[in] c  The character to put out                                    */
877
/*---------------------------------------------------------------------------*/
878
static void
879
put_rsp_char (char  c)
880
{
881
  if (-1 == rsp.client_fd)
882
    {
883
      fprintf (stderr, "Warning: Attempt to write '%c' to unopened RSP "
884
               "client: Ignored\n", c);
885
      return;
886
    }
887
 
888
  /* Write until successful (we retry after interrupts) or catastrophic
889
     failure. */
890
  while (1)
891
    {
892
      switch (write (rsp.client_fd, &c, sizeof (c)))
893
        {
894
        case -1:
895
          /* Error: only allow interrupts or would block */
896
          if ((EAGAIN != errno) && (EINTR != errno))
897
            {
898
              fprintf (stderr, "Warning: Failed to write to RSP client: "
899
                       "Closing client connection: %s\n",
900
                       strerror (errno));
901
              rsp_client_close ();
902
              return;
903
            }
904
 
905
          break;
906
 
907
        case 0:
908
          break;                /* Nothing written! Try again */
909
 
910
        default:
911
          return;               /* Success, we can return */
912
        }
913
    }
914
}       /* put_rsp_char () */
915
 
916
 
917
/*---------------------------------------------------------------------------*/
918
/*!Get a single character from the client socket
919
 
920
   This should only be called if the client is open, but we check for safety.
921
 
922
   @return  The character read, or -1 on failure                             */
923
/*---------------------------------------------------------------------------*/
924
static int
925
get_rsp_char ()
926
{
927
  if (-1 == rsp.client_fd)
928
    {
929
      fprintf (stderr, "Warning: Attempt to read from unopened RSP "
930
               "client: Ignored\n");
931
      return  -1;
932
    }
933
 
934
  /* Non-blocking read until successful (we retry after interrupts) or
935
     catastrophic failure. */
936
  while (1)
937
    {
938
      unsigned char  c;
939
 
940
      switch (read (rsp.client_fd, &c, sizeof (c)))
941
        {
942
        case -1:
943
          /* Error: only allow interrupts */
944
          if ((EAGAIN != errno) && (EINTR != errno))
945
            {
946
              fprintf (stderr, "Warning: Failed to read from RSP client: "
947
                       "Closing client connection: %s\n",
948
                       strerror (errno));
949
              rsp_client_close ();
950
              return  -1;
951
            }
952
 
953
          break;
954
 
955
        case 0:
956
          // EOF
957
          rsp_client_close ();
958
          return  -1;
959
 
960
        default:
961
          return  c & 0xff; /* Success, we can return (no sign extend!) */
962
        }
963
    }
964
}       /* get_rsp_char () */
965
 
966
 
967
/*---------------------------------------------------------------------------*/
968
/*!"Unescape" RSP binary data
969
 
970
   '#', '$' and '}' are escaped by preceding them by '}' and oring with 0x20.
971
 
972
   This function reverses that, modifying the data in place.
973
 
974
   @param[in] data  The array of bytes to convert
975
   @para[in]  len   The number of bytes to be converted
976
 
977
   @return  The number of bytes AFTER conversion                             */
978
/*---------------------------------------------------------------------------*/
979
static int
980
rsp_unescape (char *data,
981
              int   len)
982
{
983
  int  from_off = 0;             /* Offset to source char */
984
  int  to_off   = 0;             /* Offset to dest char */
985
 
986
  while (from_off < len)
987
    {
988
      /* Is it escaped */
989
      if ( '}' == data[from_off])
990
        {
991
          from_off++;
992
          data[to_off] = data[from_off] ^ 0x20;
993
        }
994
      else
995
        {
996
          data[to_off] = data[from_off];
997
        }
998
 
999
      from_off++;
1000
      to_off++;
1001
    }
1002
 
1003
  return  to_off;
1004
 
1005
}       /* rsp_unescape () */
1006
 
1007
 
1008
/*---------------------------------------------------------------------------*/
1009
/*!Initialize the matchpoint hash table
1010
 
1011
   This is an open hash table, so this function clears all the links to
1012
   NULL.                                                                     */
1013
/*---------------------------------------------------------------------------*/
1014
static void
1015
mp_hash_init ()
1016
{
1017
  int  i;
1018
 
1019
  for (i = 0; i < MP_HASH_SIZE; i++)
1020
    {
1021
      rsp.mp_hash[i] = NULL;
1022
    }
1023
}       /* mp_hash_init () */
1024
 
1025
 
1026
/*---------------------------------------------------------------------------*/
1027
/*!Add an entry to the matchpoint hash table
1028
 
1029
   Add the entry if it wasn't already there. If it was there do nothing. The
1030
   match just be on type and addr. The instr need not match, since if this is
1031
   a duplicate insertion (perhaps due to a lost packet) they will be
1032
   different.
1033
 
1034
   @param[in] type   The type of matchpoint
1035
   @param[in] addr   The address of the matchpoint
1036
   @para[in]  instr  The instruction to associate with the address           */
1037
/*---------------------------------------------------------------------------*/
1038
static void
1039
mp_hash_add (enum mp_type       type,
1040
             unsigned long int  addr,
1041
             unsigned long int  instr)
1042
{
1043
  int              hv    = addr % MP_HASH_SIZE;
1044
  struct mp_entry *curr;
1045
 
1046
  /* See if we already have the entry */
1047
  for(curr = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1048
    {
1049
      if ((type == curr->type) && (addr == curr->addr))
1050
        {
1051
          return;               /* We already have the entry */
1052
        }
1053
    }
1054
 
1055
  /* Insert the new entry at the head of the chain */
1056
  curr = malloc (sizeof (*curr));
1057
 
1058
  curr->type  = type;
1059
  curr->addr  = addr;
1060
  curr->instr = instr;
1061
  curr->next  = rsp.mp_hash[hv];
1062
 
1063
  rsp.mp_hash[hv] = curr;
1064
 
1065
}       /* mp_hash_add () */
1066
 
1067
 
1068
/*---------------------------------------------------------------------------*/
1069
/*!Look up an entry in the matchpoint hash table
1070
 
1071
   The match must be on type AND addr.
1072
 
1073
   @param[in] type   The type of matchpoint
1074
   @param[in] addr   The address of the matchpoint
1075
 
1076
   @return  The entry deleted, or NULL if the entry was not found            */
1077
/*---------------------------------------------------------------------------*/
1078
static struct mp_entry *
1079
mp_hash_lookup (enum mp_type       type,
1080
                unsigned long int  addr)
1081
{
1082
  int              hv   = addr % MP_HASH_SIZE;
1083
  struct mp_entry *curr;
1084
 
1085
  /* Search */
1086
  for (curr = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1087
    {
1088
      if ((type == curr->type) && (addr == curr->addr))
1089
        {
1090
          return  curr;         /* The entry found */
1091
        }
1092
    }
1093
 
1094
  /* Not found */
1095
  return  NULL;
1096
 
1097
}       /* mp_hash_lookup () */
1098
 
1099
 
1100
/*---------------------------------------------------------------------------*/
1101
/*!Delete an entry from the matchpoint hash table
1102
 
1103
   If it is there the entry is deleted from the hash table. If it is not
1104
   there, no action is taken. The match must be on type AND addr.
1105
 
1106
   The usual fun and games tracking the previous entry, so we can delete
1107
   things.
1108
 
1109
   @note  The deletion DOES NOT free the memory associated with the entry,
1110
          since that is returned. The caller should free the memory when they
1111
          have used the information.
1112
 
1113
   @param[in] type   The type of matchpoint
1114
   @param[in] addr   The address of the matchpoint
1115
 
1116
   @return  The entry deleted, or NULL if the entry was not found            */
1117
/*---------------------------------------------------------------------------*/
1118
static struct mp_entry *
1119
mp_hash_delete (enum mp_type       type,
1120
                unsigned long int  addr)
1121
{
1122
  int              hv   = addr % MP_HASH_SIZE;
1123
  struct mp_entry *prev = NULL;
1124
  struct mp_entry *curr;
1125
 
1126
  /* Search */
1127
  for (curr  = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1128
    {
1129
      if ((type == curr->type) && (addr == curr->addr))
1130
        {
1131
          /* Found - delete. Method depends on whether we are the head of
1132
             chain. */
1133
          if (NULL == prev)
1134
            {
1135
              rsp.mp_hash[hv] = curr->next;
1136
            }
1137
          else
1138
            {
1139
              prev->next = curr->next;
1140
            }
1141
 
1142
          return  curr;         /* The entry deleted */
1143
        }
1144
 
1145
      prev = curr;
1146
    }
1147
 
1148
  /* Not found */
1149
  return  NULL;
1150
 
1151
}       /* mp_hash_delete () */
1152
 
1153
 
1154
/*---------------------------------------------------------------------------*/
1155
/*!Utility to give the value of a hex char
1156
 
1157
   @param[in] ch  A character representing a hexadecimal digit. Done as -1,
1158
                  for consistency with other character routines, which can use
1159
                  -1 as EOF.
1160
 
1161
   @return  The value of the hex character, or -1 if the character is
1162
            invalid.                                                         */
1163
/*---------------------------------------------------------------------------*/
1164
static int
1165
hex (int  c)
1166
{
1167
  return  ((c >= 'a') && (c <= 'f')) ? c - 'a' + 10 :
1168
          ((c >= '0') && (c <= '9')) ? c - '0' :
1169
          ((c >= 'A') && (c <= 'F')) ? c - 'A' + 10 : -1;
1170
 
1171
}       /* hex () */
1172
 
1173
 
1174
/*---------------------------------------------------------------------------*/
1175
/*!Convert a register to a hex digit string
1176
 
1177
   The supplied 32-bit value is converted to an 8 digit hex string according
1178
   the target endianism. It is null terminated for convenient printing.
1179
 
1180
   @param[in]  val  The value to convert
1181
   @param[out] buf  The buffer for the text string                           */
1182
/*---------------------------------------------------------------------------*/
1183
static void
1184
reg2hex (unsigned long int  val,
1185
         char              *buf)
1186
{
1187
  int  n;                       /* Counter for digits */
1188
 
1189
  for (n = 0; n < 8; n++)
1190
    {
1191
#ifdef WORDSBIGENDIAN
1192
      int  nyb_shift = n * 4;
1193
#else
1194
      int  nyb_shift = 28 - (n * 4);
1195
#endif
1196
      buf[n] = hexchars[(val >> nyb_shift) & 0xf];
1197
    }
1198
 
1199
  buf[8] = 0;                    /* Useful to terminate as string */
1200
 
1201
}       /* reg2hex () */
1202
 
1203
 
1204
/*---------------------------------------------------------------------------*/
1205
/*!Convert a hex digit string to a register value
1206
 
1207
   The supplied 8 digit hex string is converted to a 32-bit value according
1208
   the target endianism
1209
 
1210
   @param[in] buf  The buffer with the hex string
1211
 
1212
   @return  The value to convert                                             */
1213
/*---------------------------------------------------------------------------*/
1214
static unsigned long int
1215
hex2reg (char *buf)
1216
{
1217
  int                n;         /* Counter for digits */
1218
  unsigned long int  val = 0;    /* The result */
1219
 
1220
  for (n = 0; n < 8; n++)
1221
    {
1222
#ifdef WORDSBIGENDIAN
1223
      int  nyb_shift = n * 4;
1224
#else
1225
      int  nyb_shift = 28 - (n * 4);
1226
#endif
1227
      val |= hex (buf[n]) << nyb_shift;
1228
    }
1229
 
1230
  return val;
1231
 
1232
}       /* hex2reg () */
1233
 
1234
 
1235
/*---------------------------------------------------------------------------*/
1236
/*!Convert an ASCII character string to pairs of hex digits
1237
 
1238
   Both source and destination are null terminated.
1239
 
1240
   @param[out] dest  Buffer to store the hex digit pairs (null terminated)
1241
   @param[in]  src   The ASCII string (null terminated)                      */
1242
/*---------------------------------------------------------------------------*/
1243
static void  ascii2hex (char *dest,
1244
                        char *src)
1245
{
1246
  int  i;
1247
 
1248
  /* Step through converting the source string */
1249
  for (i = 0; src[i] != '\0'; i++)
1250
    {
1251
      char  ch = src[i];
1252
 
1253
      dest[i * 2]     = hexchars[ch >> 4 & 0xf];
1254
      dest[i * 2 + 1] = hexchars[ch      & 0xf];
1255
    }
1256
 
1257
  dest[i * 2] = '\0';
1258
 
1259
}       /* ascii2hex () */
1260
 
1261
 
1262
/*---------------------------------------------------------------------------*/
1263
/*!Convert pairs of hex digits to an ASCII character string
1264
 
1265
   Both source and destination are null terminated.
1266
 
1267
   @param[out] dest  The ASCII string (null terminated)
1268
   @param[in]  src   Buffer holding the hex digit pairs (null terminated)    */
1269
/*---------------------------------------------------------------------------*/
1270
static void  hex2ascii (char *dest,
1271
                        char *src)
1272
{
1273
  int  i;
1274
 
1275
  /* Step through convering the source hex digit pairs */
1276
  for (i = 0; src[i * 2] != '\0' && src[i * 2 + 1] != '\0'; i++)
1277
    {
1278
      dest[i] = ((hex (src[i * 2]) & 0xf) << 4) | (hex (src[i * 2 + 1]) & 0xf);
1279
    }
1280
 
1281
  dest[i] = '\0';
1282
 
1283
}       /* hex2ascii () */
1284
 
1285
 
1286
/*---------------------------------------------------------------------------*/
1287
/*!Set the program counter
1288
 
1289
   This sets the value in the NPC SPR. Not completely trivial, since this is
1290
   actually cached in cpu_state.pc. Any reset of the NPC also involves
1291
   clearing the delay state and setting the pcnext global.
1292
 
1293
   Only actually do this if the requested address is different to the current
1294
   NPC (avoids clearing the delay pipe).
1295
 
1296
   @param[in] addr  The address to use                                       */
1297
/*---------------------------------------------------------------------------*/
1298
static void
1299
set_npc (unsigned long int  addr)
1300
{
1301
  if (cpu_state.pc != addr)
1302
    {
1303
      cpu_state.pc         = addr;
1304
      cpu_state.delay_insn = 0;
1305
      pcnext               = addr + 4;
1306
    }
1307
}       /* set_npc () */
1308
 
1309
 
1310
/*---------------------------------------------------------------------------*/
1311
/*!Send a packet acknowledging an exception has occurred
1312
 
1313
   This is only called if there is a client FD to talk to                    */
1314
/*---------------------------------------------------------------------------*/
1315
static void
1316
rsp_report_exception ()
1317
{
1318
  struct rsp_buf  buf;
1319
 
1320
  /* Construct a signal received packet */
1321
  buf.data[0] = 'S';
1322
  buf.data[1] = hexchars[rsp.sigval >> 4];
1323
  buf.data[2] = hexchars[rsp.sigval % 16];
1324
  buf.data[3] = 0;
1325
  buf.len     = strlen (buf.data);
1326
 
1327
  put_packet (&buf);
1328
 
1329
}       /* rsp_report_exception () */
1330
 
1331
 
1332
/*---------------------------------------------------------------------------*/
1333
/*!Handle a RSP continue request
1334
 
1335
   Parse the command to see if there is an address. Uses the underlying
1336
   generic continue function, with EXCEPT_NONE.
1337
 
1338
   @param[in] buf  The full continue packet                                  */
1339
/*---------------------------------------------------------------------------*/
1340
static void
1341
rsp_continue (struct rsp_buf *buf)
1342
{
1343
  unsigned long int  addr;              /* Address to continue from, if any */
1344
 
1345
  if (0 == strcmp ("c", buf->data))
1346
    {
1347
      addr = cpu_state.pc;      /* Default uses current NPC */
1348
    }
1349
  else if (1 != sscanf (buf->data, "c%lx", &addr))
1350
    {
1351
      fprintf (stderr,
1352
               "Warning: RSP continue address %s not recognized: ignored\n",
1353
               buf->data);
1354
      addr = cpu_state.pc;      /* Default uses current NPC */
1355
    }
1356
 
1357
  rsp_continue_generic (addr, EXCEPT_NONE);
1358
 
1359
}       /* rsp_continue () */
1360
 
1361
 
1362
/*---------------------------------------------------------------------------*/
1363
/*!Handle a RSP continue with signal request
1364
 
1365
   Currently null. Will use the underlying generic continue function.
1366
 
1367
   @param[in] buf  The full continue with signal packet                      */
1368
/*---------------------------------------------------------------------------*/
1369
static void
1370
rsp_continue_with_signal (struct rsp_buf *buf)
1371
{
1372
  printf ("RSP continue with signal '%s' received\n", buf->data);
1373
 
1374
}       /* rsp_continue_with_signal () */
1375
 
1376
 
1377
/*---------------------------------------------------------------------------*/
1378
/*!Generic processing of a continue request
1379
 
1380
   The signal may be EXCEPT_NONE if there is no exception to be
1381
   handled. Currently the exception is ignored.
1382
 
1383
   The single step flag is cleared in the debug registers and then the
1384
   processor is unstalled.
1385
 
1386
   @param[in] addr    Address from which to step
1387
   @param[in] except  The exception to use (if any)                          */
1388
/*---------------------------------------------------------------------------*/
1389
static void
1390
rsp_continue_generic (unsigned long int  addr,
1391
                      unsigned long int  except)
1392
{
1393
  /* Set the address as the value of the next program counter */
1394
  set_npc (addr);
1395
 
1396
  /* Clear Debug Reason Register and watchpoint break generation in Debug Mode
1397
     Register 2 */
1398
  cpu_state.sprs[SPR_DRR]   = 0;
1399
  cpu_state.sprs[SPR_DMR2] &= ~SPR_DMR2_WGB;
1400
 
1401
  /* Clear the single step trigger in Debug Mode Register 1 and set traps to be
1402
     handled by the debug unit in the Debug Stop Register */
1403
  cpu_state.sprs[SPR_DMR1] &= ~SPR_DMR1_ST;
1404
  cpu_state.sprs[SPR_DSR]  |= SPR_DSR_TE;
1405
 
1406
  /* Unstall the processor */
1407
  set_stall_state (0);
1408
 
1409
  /* Any signal is cleared. */
1410
  rsp.sigval = TARGET_SIGNAL_NONE;
1411
 
1412
  /* Note the GDB client is now waiting for a reply. */
1413
  rsp.client_waiting = 1;
1414
 
1415
}       /* rsp_continue_generic () */
1416
 
1417
 
1418
/*---------------------------------------------------------------------------*/
1419
/*!Handle a RSP read all registers request
1420
 
1421
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PPC
1422
   (i.e. SPR PPC), NPC (i.e. SPR NPC) and SR (i.e. SPR SR). Each register is
1423
   returned as a sequence of bytes in target endian order.
1424
 
1425
   Each byte is packed as a pair of hex digits.                              */
1426
/*---------------------------------------------------------------------------*/
1427
static void
1428
rsp_read_all_regs ()
1429
{
1430
  struct rsp_buf  buf;                  /* Buffer for the reply */
1431
  int             r;                    /* Register index */
1432
 
1433
  /* The GPRs */
1434
  for (r = 0; r < MAX_GPRS; r++)
1435
    {
1436
      reg2hex (cpu_state.reg[r], &(buf.data[r * 8]));
1437
    }
1438
 
1439
  /* PPC, NPC and SR */
1440
  reg2hex (cpu_state.sprs[SPR_PPC], &(buf.data[PPC_REGNUM * 8]));
1441
  reg2hex (cpu_state.pc,            &(buf.data[NPC_REGNUM * 8]));
1442
  reg2hex (cpu_state.sprs[SPR_SR],  &(buf.data[SR_REGNUM  * 8]));
1443
 
1444
  /* Finalize the packet and send it */
1445
  buf.data[NUM_REGS * 8] = 0;
1446
  buf.len                = NUM_REGS * 8;
1447
 
1448
  put_packet (&buf);
1449
 
1450
}       /* rsp_read_all_regs () */
1451
 
1452
 
1453
/*---------------------------------------------------------------------------*/
1454
/*!Handle a RSP write all registers request
1455
 
1456
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PPC
1457
   (i.e. SPR PPC), NPC (i.e. SPR NPC) and SR (i.e. SPR SR). Each register is
1458
   supplied as a sequence of bytes in target endian order.
1459
 
1460
   Each byte is packed as a pair of hex digits.
1461
 
1462
   @todo There is no error checking at present. Non-hex chars will generate a
1463
         warning message, but there is no other check that the right amount
1464
         of data is present. The result is always "OK".
1465
 
1466
   @param[in] buf  The original packet request.                              */
1467
/*---------------------------------------------------------------------------*/
1468
static void
1469
rsp_write_all_regs (struct rsp_buf *buf)
1470
{
1471
  int             r;                    /* Register index */
1472
 
1473
  /* The GPRs */
1474
  for (r = 0; r < MAX_GPRS; r++)
1475
    {
1476
      cpu_state.reg[r] = hex2reg (&(buf->data[r * 8]));
1477
    }
1478
 
1479
  /* PPC, NPC and SR */
1480
  cpu_state.sprs[SPR_PPC] = hex2reg (&(buf->data[PPC_REGNUM * 8]));
1481
  cpu_state.sprs[SPR_SR]  = hex2reg (&(buf->data[SR_REGNUM  * 8]));
1482
  set_npc (hex2reg (&(buf->data[NPC_REGNUM * 8])));
1483
 
1484
  /* Acknowledge. TODO: We always succeed at present, even if the data was
1485
     defective. */
1486
  put_str_packet ("OK");
1487
 
1488
}       /* rsp_write_all_regs () */
1489
 
1490
 
1491
/*---------------------------------------------------------------------------*/
1492
/*!Handle a RSP read memory (symbolic) request
1493
 
1494
   Syntax is:
1495
 
1496
     m<addr>,<length>:
1497
 
1498
   The response is the bytes, lowest address first, encoded as pairs of hex
1499
   digits.
1500
 
1501
   The length given is the number of bytes to be read.
1502
 
1503
   @note This function reuses buf, so trashes the original command.
1504
 
1505
   @param[in] buf  The command received                                      */
1506
/*---------------------------------------------------------------------------*/
1507
static void
1508
rsp_read_mem (struct rsp_buf *buf)
1509
{
1510
  unsigned int    addr;                 /* Where to read the memory */
1511
  int             len;                  /* Number of bytes to read */
1512
  int             off;                  /* Offset into the memory */
1513
 
1514
  if (2 != sscanf (buf->data, "m%x,%x:", &addr, &len))
1515
    {
1516
      fprintf (stderr, "Warning: Failed to recognize RSP read memory "
1517
               "command: %s\n", buf->data);
1518
      put_str_packet ("E01");
1519
      return;
1520
    }
1521
 
1522
  /* Make sure we won't overflow the buffer (2 chars per byte) */
1523
  if ((len * 2) >= GDB_BUF_MAX)
1524
    {
1525
      fprintf (stderr, "Warning: Memory read %s too large for RSP packet: "
1526
               "truncated\n", buf->data);
1527
      len = (GDB_BUF_MAX - 1) / 2;
1528
    }
1529
 
1530
  /* Refill the buffer with the reply */
1531
  for (off = 0; off < len; off++)
1532
    {
1533
      unsigned char  ch;                /* The byte at the address */
1534
 
1535
      /* Check memory area is valid */
1536
      if (NULL == verify_memoryarea (addr + off))
1537
        {
1538
          /* The error number doesn't matter. The GDB client will substitute
1539
             its own */
1540
          put_str_packet ("E01");
1541
          return;
1542
        }
1543
 
1544
      // Get the memory direct - no translation.
1545
      ch = eval_direct8 (addr + off, 0, 0);
1546
 
1547
      buf->data[off * 2]     = hexchars[ch >>   4];
1548
      buf->data[off * 2 + 1] = hexchars[ch &  0xf];
1549
    }
1550
 
1551
  buf->data[off * 2] = 0;                        /* End of string */
1552
  buf->len           = strlen (buf->data);
1553
  put_packet (buf);
1554
 
1555
}       /* rsp_read_mem () */
1556
 
1557
 
1558
/*---------------------------------------------------------------------------*/
1559
/*!Handle a RSP write memory (symbolic) request
1560
 
1561
   Syntax is:
1562
 
1563
     m<addr>,<length>:<data>
1564
 
1565
   The data is the bytes, lowest address first, encoded as pairs of hex
1566
   digits.
1567
 
1568
   The length given is the number of bytes to be written.
1569
 
1570
   @note This function reuses buf, so trashes the original command.
1571
 
1572
   @param[in] buf  The command received                                      */
1573
/*---------------------------------------------------------------------------*/
1574
static void
1575
rsp_write_mem (struct rsp_buf *buf)
1576
{
1577
  unsigned int    addr;                 /* Where to write the memory */
1578
  int             len;                  /* Number of bytes to write */
1579
  char           *symdat;               /* Pointer to the symboli data */
1580
  int             datlen;               /* Number of digits in symbolic data */
1581
  int             off;                  /* Offset into the memory */
1582
 
1583
  if (2 != sscanf (buf->data, "M%x,%x:", &addr, &len))
1584
    {
1585
      fprintf (stderr, "Warning: Failed to recognize RSP write memory "
1586
               "command: %s\n", buf->data);
1587
      put_str_packet ("E01");
1588
      return;
1589
    }
1590
 
1591
  /* Find the start of the data and check there is the amount we expect. */
1592
  symdat = memchr ((const void *)buf->data, ':', GDB_BUF_MAX) + 1;
1593
  datlen = buf->len - (symdat - buf->data);
1594
 
1595
  /* Sanity check */
1596
  if (len * 2 != datlen)
1597
    {
1598
      fprintf (stderr, "Warning: Write of %d digits requested, but %d digits "
1599
               "supplied: packet ignored\n", len * 2, datlen );
1600
      put_str_packet ("E01");
1601
      return;
1602
    }
1603
 
1604
  /* Write the bytes to memory */
1605
  for (off = 0; off < len; off++)
1606
    {
1607
      if (NULL == verify_memoryarea (addr + off))
1608
        {
1609
          /* The error number doesn't matter. The GDB client will substitute
1610
             its own */
1611
          put_str_packet ("E01");
1612
          return;
1613
        }
1614
      else
1615
        {
1616
          unsigned char  nyb1 = hex (symdat[off * 2]);
1617
          unsigned char  nyb2 = hex (symdat[off * 2 + 1]);
1618
 
1619
          // circumvent the read-only check usually done for mem accesses
1620
          // data is in host order, because that's what set_direct32 needs
1621
          set_program8 (addr + off, (nyb1 << 4) | nyb2);
1622
        }
1623
    }
1624
 
1625
  put_str_packet ("OK");
1626
 
1627
}       /* rsp_write_mem () */
1628
 
1629
 
1630
/*---------------------------------------------------------------------------*/
1631
/*!Read a single register
1632
 
1633
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PC
1634
   (i.e. SPR NPC) and SR (i.e. SPR SR). The register is returned as a
1635
   sequence of bytes in target endian order.
1636
 
1637
   Each byte is packed as a pair of hex digits.
1638
 
1639
   @param[in] buf  The original packet request. Reused for the reply.        */
1640
/*---------------------------------------------------------------------------*/
1641
static void
1642
rsp_read_reg (struct rsp_buf *buf)
1643
{
1644
  unsigned int  regnum;
1645
 
1646
  /* Break out the fields from the data */
1647
  if (1 != sscanf (buf->data, "p%x", &regnum))
1648
    {
1649
      fprintf (stderr, "Warning: Failed to recognize RSP read register "
1650
               "command: %s\n", buf->data);
1651
      put_str_packet ("E01");
1652
      return;
1653
    }
1654
 
1655
  /* Get the relevant register */
1656
  if (regnum < MAX_GPRS)
1657
    {
1658
      reg2hex (cpu_state.reg[regnum], buf->data);
1659
    }
1660
  else if (PPC_REGNUM == regnum)
1661
    {
1662
      reg2hex (cpu_state.sprs[SPR_PPC], buf->data);
1663
    }
1664
  else if (NPC_REGNUM == regnum)
1665
    {
1666
      reg2hex (cpu_state.pc, buf->data);
1667
    }
1668
  else if (SR_REGNUM == regnum)
1669
    {
1670
      reg2hex (cpu_state.sprs[SPR_SR], buf->data);
1671
    }
1672
  else
1673
    {
1674
      /* Error response if we don't know the register */
1675
      fprintf (stderr, "Warning: Attempt to read unknown register 0x%x: "
1676
               "ignored\n", regnum);
1677
      put_str_packet ("E01");
1678
      return;
1679
    }
1680
 
1681
  buf->len = strlen (buf->data);
1682
  put_packet (buf);
1683
 
1684
}       /* rsp_write_reg () */
1685
 
1686
 
1687
/*---------------------------------------------------------------------------*/
1688
/*!Write a single register
1689
 
1690
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PC
1691
   (i.e. SPR NPC) and SR (i.e. SPR SR). The register is specified as a
1692
   sequence of bytes in target endian order.
1693
 
1694
   Each byte is packed as a pair of hex digits.
1695
 
1696
   @param[in] buf  The original packet request.                              */
1697
/*---------------------------------------------------------------------------*/
1698
static void
1699
rsp_write_reg (struct rsp_buf *buf)
1700
{
1701
  unsigned int  regnum;
1702
  char          valstr[9];              /* Allow for EOS on the string */
1703
 
1704
  /* Break out the fields from the data */
1705
  if (2 != sscanf (buf->data, "P%x=%8s", &regnum, valstr))
1706
    {
1707
      fprintf (stderr, "Warning: Failed to recognize RSP write register "
1708
               "command: %s\n", buf->data);
1709
      put_str_packet ("E01");
1710
      return;
1711
    }
1712
 
1713
  /* Set the relevant register */
1714
  if (regnum < MAX_GPRS)
1715
    {
1716
      cpu_state.reg[regnum] = hex2reg (valstr);
1717
    }
1718
  else if (PPC_REGNUM == regnum)
1719
    {
1720
      cpu_state.sprs[SPR_PPC] = hex2reg (valstr);
1721
    }
1722
  else if (NPC_REGNUM == regnum)
1723
    {
1724
      set_npc (hex2reg (valstr));
1725
    }
1726
  else if (SR_REGNUM == regnum)
1727
    {
1728
      cpu_state.sprs[SPR_SR] = hex2reg (valstr);
1729
    }
1730
  else
1731
    {
1732
      /* Error response if we don't know the register */
1733
      fprintf (stderr, "Warning: Attempt to write unknown register 0x%x: "
1734
               "ignored\n", regnum);
1735
      put_str_packet ("E01");
1736
      return;
1737
    }
1738
 
1739
  put_str_packet ("OK");
1740
 
1741
}       /* rsp_write_reg () */
1742
 
1743
 
1744
/*---------------------------------------------------------------------------*/
1745
/*!Handle a RSP query request
1746
 
1747
   @param[in] buf  The request. Reused for any packets that need to be sent
1748
                   back.                                                     */
1749
/*---------------------------------------------------------------------------*/
1750
static void
1751
rsp_query (struct rsp_buf *buf)
1752
{
1753
  if (0 == strcmp ("qC", buf->data))
1754
    {
1755
      /* Return the current thread ID (unsigned hex). A null response
1756
         indicates to use the previously selected thread. We use the constant
1757
         OR1KSIM_TID to represent our single thread of control. */
1758
      sprintf (buf->data, "QC%x", OR1KSIM_TID);
1759
      buf->len = strlen (buf->data);
1760
      put_packet (buf);
1761
    }
1762
  else if (0 == strncmp ("qCRC", buf->data, strlen ("qCRC")))
1763
    {
1764
      /* Return CRC of memory area */
1765
      fprintf (stderr, "Warning: RSP CRC query not supported\n");
1766
      put_str_packet ("E01");
1767
    }
1768
  else if (0 == strcmp ("qfThreadInfo", buf->data))
1769
    {
1770
      /* Return info about active threads. We return just the constant
1771
         OR1KSIM_TID to represent our single thread of control. */
1772
      sprintf (buf->data, "m%x", OR1KSIM_TID);
1773
      buf->len = strlen (buf->data);
1774
      put_packet (buf);
1775
    }
1776
  else if (0 == strcmp ("qsThreadInfo", buf->data))
1777
    {
1778
      /* Return info about more active threads. We have no more, so return the
1779
         end of list marker, 'l' */
1780
      put_str_packet ("l");
1781
    }
1782
  else if (0 == strncmp ("qGetTLSAddr:", buf->data, strlen ("qGetTLSAddr:")))
1783
    {
1784
      /* We don't support this feature */
1785
      put_str_packet ("");
1786
    }
1787
  else if (0 == strncmp ("qL", buf->data, strlen ("qL")))
1788
    {
1789
      /* Deprecated and replaced by 'qfThreadInfo' */
1790
      fprintf (stderr, "Warning: RSP qL deprecated: no info returned\n");
1791
      put_str_packet ("qM001");
1792
    }
1793
  else if (0 == strcmp ("qOffsets", buf->data))
1794
    {
1795
      /* Report any relocation */
1796
      put_str_packet ("Text=0;Data=0;Bss=0");
1797
    }
1798
  else if (0 == strncmp ("qP", buf->data, strlen ("qP")))
1799
    {
1800
      /* Deprecated and replaced by 'qThreadExtraInfo' */
1801
      fprintf (stderr, "Warning: RSP qP deprecated: no info returned\n");
1802
      put_str_packet ("");
1803
    }
1804
  else if (0 == strncmp ("qRcmd,", buf->data, strlen ("qRcmd,")))
1805
    {
1806
      /* This is used to interface to commands to do "stuff" */
1807
      rsp_command (buf);
1808
    }
1809
  else if (0 == strncmp ("qSupported", buf->data, strlen ("qSupported")))
1810
    {
1811
      /* Report a list of the features we support. For now we just ignore any
1812
         supplied specific feature queries, but in the future these may be
1813
         supported as well. Note that the packet size allows for 'G' + all the
1814
         registers sent to us, or a reply to 'g' with all the registers and an
1815
         EOS so the buffer is a well formed string. */
1816
 
1817
      char  reply[GDB_BUF_MAX];
1818
 
1819
      sprintf (reply, "PacketSize=%x", GDB_BUF_MAX);
1820
      put_str_packet (reply);
1821
    }
1822
  else if (0 == strncmp ("qSymbol:", buf->data, strlen ("qSymbol:")))
1823
    {
1824
      /* Offer to look up symbols. Nothing we want (for now). TODO. This just
1825
         ignores any replies to symbols we looked up, but we didn't want to
1826
         do that anyway! */
1827
      put_str_packet ("OK");
1828
    }
1829
  else if (0 == strncmp ("qThreadExtraInfo,", buf->data,
1830
                         strlen ("qThreadExtraInfo,")))
1831
    {
1832
      /* Report that we are runnable, but the text must be hex ASCI
1833
         digits. For now do this by steam, reusing the original packet */
1834
      sprintf (buf->data, "%02x%02x%02x%02x%02x%02x%02x%02x%02x",
1835
               'R', 'u', 'n', 'n', 'a', 'b', 'l', 'e', 0);
1836
      buf->len = strlen (buf->data);
1837
      put_packet (buf);
1838
    }
1839
  else if (0 == strncmp ("qXfer:", buf->data, strlen ("qXfer:")))
1840
    {
1841
      /* For now we support no 'qXfer' requests, but these should not be
1842
         expected, since they were not reported by 'qSupported' */
1843
      fprintf (stderr, "Warning: RSP 'qXfer' not supported: ignored\n");
1844
      put_str_packet ("");
1845
    }
1846
  else
1847
    {
1848
      fprintf (stderr, "Unrecognized RSP query: ignored\n");
1849
    }
1850
}       /* rsp_query () */
1851
 
1852
 
1853
/*---------------------------------------------------------------------------*/
1854
/*!Handle a RSP qRcmd request
1855
 
1856
  The actual command follows the "qRcmd," in ASCII encoded to hex
1857
 
1858
   @param[in] buf  The request in full                                       */
1859
/*---------------------------------------------------------------------------*/
1860
static void
1861
rsp_command (struct rsp_buf *buf)
1862
{
1863
  char  cmd[GDB_BUF_MAX];
1864
 
1865
  hex2ascii (cmd, &(buf->data[strlen ("qRcmd,")]));
1866
 
1867
  /* Work out which command it is */
1868
  if (0 == strncmp ("readspr ", cmd, strlen ("readspr")))
1869
    {
1870
      unsigned int       regno;
1871
 
1872
      /* Parse and return error if we fail */
1873
      if( 1 != sscanf (cmd, "readspr %4x", &regno))
1874
        {
1875
          fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n",
1876
                   cmd);
1877
          put_str_packet ("E01");
1878
          return;
1879
        }
1880
 
1881
      /* SPR out of range */
1882
      if (regno > MAX_SPRS)
1883
        {
1884
          fprintf (stderr, "Warning: qRcmd readspr %x too large: ignored\n",
1885
                   regno);
1886
          put_str_packet ("E01");
1887
          return;
1888
        }
1889
 
1890
      /* Construct the reply */
1891
      sprintf (cmd, "%8lx", (unsigned long int)mfspr (regno));
1892
      ascii2hex (buf->data, cmd);
1893
      buf->len = strlen (buf->data);
1894
      put_packet (buf);
1895
    }
1896
  else if (0 == strncmp ("writespr ", cmd, strlen ("writespr")))
1897
    {
1898
      unsigned int       regno;
1899
      unsigned long int  val;
1900
 
1901
      /* Parse and return error if we fail */
1902
      if( 2 != sscanf (cmd, "writespr %4x %8lx", &regno, &val))
1903
        {
1904
          fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n",
1905
                   cmd);
1906
          put_str_packet ("E01");
1907
          return;
1908
        }
1909
 
1910
      /* SPR out of range */
1911
      if (regno > MAX_SPRS)
1912
        {
1913
          fprintf (stderr, "Warning: qRcmd writespr %x too large: ignored\n",
1914
                   regno);
1915
          put_str_packet ("E01");
1916
          return;
1917
        }
1918
 
1919
      /* Update the SPR and reply "OK" */
1920
      mtspr (regno, val);
1921
      put_str_packet ("OK");
1922
    }
1923
 
1924
}       /* rsp_command () */
1925
 
1926
 
1927
/*---------------------------------------------------------------------------*/
1928
/*!Handle a RSP set request
1929
 
1930
   @param[in] buf  The request                                               */
1931
/*---------------------------------------------------------------------------*/
1932
static void
1933
rsp_set (struct rsp_buf *buf)
1934
{
1935
  if (0 == strncmp ("QPassSignals:", buf->data, strlen ("QPassSignals:")))
1936
    {
1937
      /* Passing signals not supported */
1938
      put_str_packet ("");
1939
    }
1940
  else if ((0 == strncmp ("QTDP",    buf->data, strlen ("QTDP")))   ||
1941
           (0 == strncmp ("QFrame",  buf->data, strlen ("QFrame"))) ||
1942
           (0 == strcmp  ("QTStart", buf->data))                    ||
1943
           (0 == strcmp  ("QTStop",  buf->data))                    ||
1944
           (0 == strcmp  ("QTinit",  buf->data))                    ||
1945
           (0 == strncmp ("QTro",    buf->data, strlen ("QTro"))))
1946
    {
1947
      /* All tracepoint features are not supported. This reply is really only
1948
         needed to 'QTDP', since with that the others should not be
1949
         generated. */
1950
      put_str_packet ("");
1951
    }
1952
  else
1953
    {
1954
      fprintf (stderr, "Unrecognized RSP set request: ignored\n");
1955
    }
1956
}       /* rsp_set () */
1957
 
1958
 
1959
/*---------------------------------------------------------------------------*/
1960
/*!Handle a RSP restart request
1961
 
1962
   For now we just put the program counter back to the one used with the last
1963
   vRun request. There is no point in unstalling the processor, since we'll
1964
   never get control back.                                                   */
1965
/*---------------------------------------------------------------------------*/
1966
static void
1967
rsp_restart ()
1968
{
1969
  set_npc (rsp.start_addr);
1970
 
1971
}       /* rsp_restart () */
1972
 
1973
 
1974
/*---------------------------------------------------------------------------*/
1975
/*!Handle a RSP step request
1976
 
1977
   Parse the command to see if there is an address. Uses the underlying
1978
   generic step function, with EXCEPT_NONE.
1979
 
1980
   @param[in] buf  The full step packet                          */
1981
/*---------------------------------------------------------------------------*/
1982
static void
1983
rsp_step (struct rsp_buf *buf)
1984
{
1985
  unsigned long int  addr;              /* The address to step from, if any */
1986
 
1987
  if (0 == strcmp ("s", buf->data))
1988
    {
1989
      addr = cpu_state.pc;      /* Default uses current NPC */
1990
    }
1991
  else if (1 != sscanf (buf->data, "s%lx", &addr))
1992
    {
1993
      fprintf (stderr,
1994
               "Warning: RSP step address %s not recognized: ignored\n",
1995
               buf->data);
1996
      addr = cpu_state.pc;      /* Default uses current NPC */
1997
    }
1998
 
1999
  rsp_step_generic (addr, EXCEPT_NONE);
2000
 
2001
}       /* rsp_step () */
2002
 
2003
 
2004
/*---------------------------------------------------------------------------*/
2005
/*!Handle a RSP step with signal request
2006
 
2007
   Currently null. Will use the underlying generic step function.
2008
 
2009
   @param[in] buf  The full step with signal packet              */
2010
/*---------------------------------------------------------------------------*/
2011
static void
2012
rsp_step_with_signal (struct rsp_buf *buf)
2013
{
2014
  printf ("RSP step with signal '%s' received\n", buf->data);
2015
 
2016
}       /* rsp_step_with_signal () */
2017
 
2018
 
2019
/*---------------------------------------------------------------------------*/
2020
/*!Generic processing of a step request
2021
 
2022
   The signal may be EXCEPT_NONE if there is no exception to be
2023
   handled. Currently the exception is ignored.
2024
 
2025
   The single step flag is set in the debug registers and then the processor
2026
   is unstalled.
2027
 
2028
   @param[in] addr    Address from which to step
2029
   @param[in] except  The exception to use (if any)                          */
2030
/*---------------------------------------------------------------------------*/
2031
static void
2032
rsp_step_generic (unsigned long int  addr,
2033
                  unsigned long int  except)
2034
{
2035
  /* Set the address as the value of the next program counter */
2036
  set_npc (addr);
2037
 
2038
  /* Clear Debug Reason Register and watchpoint break generation in Debug Mode
2039
     Register 2 */
2040
  cpu_state.sprs[SPR_DRR]   = 0;
2041
  cpu_state.sprs[SPR_DMR2] &= ~SPR_DMR2_WGB;
2042
 
2043
  /* Set the single step trigger in Debug Mode Register 1 and set traps to be
2044
     handled by the debug unit in the Debug Stop Register */
2045
  cpu_state.sprs[SPR_DMR1] |= SPR_DMR1_ST;
2046
  cpu_state.sprs[SPR_DSR]  |= SPR_DSR_TE;
2047
 
2048
  /* Unstall the processor */
2049
  set_stall_state (0);
2050
 
2051
  /* Any signal is cleared. */
2052
  rsp.sigval = TARGET_SIGNAL_NONE;
2053
 
2054
  /* Note the GDB client is now waiting for a reply. */
2055
  rsp.client_waiting = 1;
2056
 
2057
}       /* rsp_step_generic () */
2058
 
2059
 
2060
/*---------------------------------------------------------------------------*/
2061
/*!Handle a RSP 'v' packet
2062
 
2063
   These are commands associated with executing the code on the target
2064
 
2065
   @param[in] buf  The request                                               */
2066
/*---------------------------------------------------------------------------*/
2067
static void
2068
rsp_vpkt (struct rsp_buf *buf)
2069
{
2070
  if (0 == strncmp ("vAttach;", buf->data, strlen ("vAttach;")))
2071
    {
2072
      /* Attaching is a null action, since we have no other process. We just
2073
         return a stop packet (using TRAP) to indicate we are stopped. */
2074
      put_str_packet ("S05");
2075
      return;
2076
    }
2077
  else if (0 == strcmp ("vCont?", buf->data))
2078
    {
2079
      /* For now we don't support this. */
2080
      put_str_packet ("");
2081
      return;
2082
    }
2083
  else if (0 == strncmp ("vCont", buf->data, strlen ("vCont")))
2084
    {
2085
      /* This shouldn't happen, because we've reported non-support via vCont?
2086
         above */
2087
      fprintf (stderr, "Warning: RSP vCont not supported: ignored\n" );
2088
      return;
2089
    }
2090
  else if (0 == strncmp ("vFile:", buf->data, strlen ("vFile:")))
2091
    {
2092
      /* For now we don't support this. */
2093
      fprintf (stderr, "Warning: RSP vFile not supported: ignored\n" );
2094
      put_str_packet ("");
2095
      return;
2096
    }
2097
  else if (0 == strncmp ("vFlashErase:", buf->data, strlen ("vFlashErase:")))
2098
    {
2099
      /* For now we don't support this. */
2100
      fprintf (stderr, "Warning: RSP vFlashErase not supported: ignored\n" );
2101
      put_str_packet ("E01");
2102
      return;
2103
    }
2104
  else if (0 == strncmp ("vFlashWrite:", buf->data, strlen ("vFlashWrite:")))
2105
    {
2106
      /* For now we don't support this. */
2107
      fprintf (stderr, "Warning: RSP vFlashWrite not supported: ignored\n" );
2108
      put_str_packet ("E01");
2109
      return;
2110
    }
2111
  else if (0 == strcmp ("vFlashDone", buf->data))
2112
    {
2113
      /* For now we don't support this. */
2114
      fprintf (stderr, "Warning: RSP vFlashDone not supported: ignored\n" );
2115
      put_str_packet ("E01");
2116
      return;
2117
    }
2118
  else if (0 == strncmp ("vRun;", buf->data, strlen ("vRun;")))
2119
    {
2120
      /* We shouldn't be given any args, but check for this */
2121
      if (buf->len > strlen ("vRun;"))
2122
        {
2123
          fprintf (stderr, "Warning: Unexpected arguments to RSP vRun "
2124
                   "command: ignored\n");
2125
        }
2126
 
2127
      /* Restart the current program. However unlike a "R" packet, "vRun"
2128
         should behave as though it has just stopped. We use signal
2129
         5 (TRAP). */
2130
      rsp_restart ();
2131
      put_str_packet ("S05");
2132
    }
2133
  else
2134
    {
2135
      fprintf (stderr, "Warning: Unknown RSP 'v' packet type %s: ignored\n",
2136
               buf->data);
2137
      put_str_packet ("E01");
2138
      return;
2139
    }
2140
}       /* rsp_vpkt () */
2141
 
2142
 
2143
/*---------------------------------------------------------------------------*/
2144
/*!Handle a RSP write memory (binary) request
2145
 
2146
   Syntax is:
2147
 
2148
     X<addr>,<length>:
2149
 
2150
   Followed by the specified number of bytes as raw binary. Response should be
2151
   "OK" if all copied OK, E<nn> if error <nn> has occurred.
2152
 
2153
   The length given is the number of bytes to be written. However the number
2154
   of data bytes may be greater, since '#', '$' and '}' are escaped by
2155
   preceding them by '}' and oring with 0x20.
2156
 
2157
   @param[in] buf  The command received                                      */
2158
/*---------------------------------------------------------------------------*/
2159
static void
2160
rsp_write_mem_bin (struct rsp_buf *buf)
2161
{
2162
  unsigned int  addr;                   /* Where to write the memory */
2163
  int           len;                    /* Number of bytes to write */
2164
  char         *bindat;                 /* Pointer to the binary data */
2165
  int           off;                    /* Offset to start of binary data */
2166
  int           newlen;                 /* Number of bytes in bin data */
2167
 
2168
  if (2 != sscanf (buf->data, "X%x,%x:", &addr, &len))
2169
    {
2170
      fprintf (stderr, "Warning: Failed to recognize RSP write memory "
2171
               "command: %s\n", buf->data);
2172
      put_str_packet ("E01");
2173
      return;
2174
    }
2175
 
2176
  /* Find the start of the data and "unescape" it */
2177
  bindat = memchr ((const void *)buf->data, ':', GDB_BUF_MAX) + 1;
2178
  off    = bindat - buf->data;
2179
  newlen = rsp_unescape (bindat, buf->len - off);
2180
 
2181
  /* Sanity check */
2182
  if (newlen != len)
2183
    {
2184
      int  minlen = len < newlen ? len : newlen;
2185
 
2186
      fprintf (stderr, "Warning: Write of %d bytes requested, but %d bytes "
2187
               "supplied. %d will be written\n", len, newlen, minlen);
2188
      len = minlen;
2189
    }
2190
 
2191
  /* Write the bytes to memory */
2192
  for (off = 0; off < len; off++)
2193
    {
2194
      if (NULL == verify_memoryarea (addr + off))
2195
        {
2196
          /* The error number doesn't matter. The GDB client will substitute
2197
             its own */
2198
          put_str_packet ("E01");
2199
          return;
2200
        }
2201
      else
2202
        {
2203
          // Circumvent the read-only check usually done for mem accesses
2204
          set_program8 (addr + off, bindat[off]);
2205
        }
2206
    }
2207
 
2208
  put_str_packet ("OK");
2209
 
2210
}       /* rsp_write_mem_bin () */
2211
 
2212
 
2213
/*---------------------------------------------------------------------------*/
2214
/*!Handle a RSP remove breakpoint or matchpoint request
2215
 
2216
   For now only memory breakpoints are implemented, which are implemented by
2217
   substituting a breakpoint at the specified address. The implementation must
2218
   cope with the possibility of duplicate packets.
2219
 
2220
   @todo This doesn't work with icache/immu yet
2221
 
2222
   @param[in] buf  The command received                                      */
2223
/*---------------------------------------------------------------------------*/
2224
static void
2225
rsp_remove_matchpoint (struct rsp_buf *buf)
2226
{
2227
  enum mp_type       type;              /* What sort of matchpoint */
2228
  unsigned long int  addr;              /* Address specified */
2229
  int                len;               /* Matchpoint length (not used) */
2230
  struct mp_entry   *mpe;               /* Info about the replaced instr */
2231
 
2232
  /* Break out the instruction */
2233
  if (3 != sscanf (buf->data, "z%1d,%lx,%1d", (int *)&type, &addr, &len))
2234
    {
2235
      fprintf (stderr, "Warning: RSP matchpoint deletion request not "
2236
               "recognized: ignored\n");
2237
      put_str_packet ("E01");
2238
      return;
2239
    }
2240
 
2241
  /* Sanity check that the length is 4 */
2242
  if (4 != len)
2243
    {
2244
      fprintf (stderr, "Warning: RSP matchpoint deletion length %d not "
2245
               "valid: 4 assumed\n", len);
2246
      len = 4;
2247
    }
2248
 
2249
  /* Sort out the type of matchpoint */
2250
  switch (type)
2251
    {
2252
    case BP_MEMORY:
2253
      /* Memory breakpoint - replace the original instruction. */
2254
      mpe = mp_hash_delete (type, addr);
2255
 
2256
      /* If the BP hasn't yet been deleted, put the original instruction
2257
         back. Don't forget to free the hash table entry afterwards. */
2258
      if (NULL != mpe)
2259
        {
2260
          set_program32 (addr, mpe->instr);
2261
          free (mpe);
2262
        }
2263
 
2264
      put_str_packet ("OK");
2265
 
2266
      return;
2267
 
2268
    case BP_HARDWARE:
2269
      put_str_packet ("");              /* Not supported */
2270
      return;
2271
 
2272
    case WP_WRITE:
2273
      put_str_packet ("");              /* Not supported */
2274
      return;
2275
 
2276
    case WP_READ:
2277
      put_str_packet ("");              /* Not supported */
2278
      return;
2279
 
2280
    case WP_ACCESS:
2281
      put_str_packet ("");              /* Not supported */
2282
      return;
2283
 
2284
    default:
2285
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
2286
               "recognized: ignored\n", type);
2287
      put_str_packet ("E01");
2288
      return;
2289
 
2290
    }
2291
}       /* rsp_remove_matchpoint () */
2292
 
2293
 
2294
/*---------------------------------------------------------------------------*/
2295
/*!Handle a RSP insert breakpoint or matchpoint request
2296
 
2297
   For now only memory breakpoints are implemented, which are implemented by
2298
   substituting a breakpoint at the specified address. The implementation must
2299
   cope with the possibility of duplicate packets.
2300
 
2301
   @todo This doesn't work with icache/immu yet
2302
 
2303
   @param[in] buf  The command received                                      */
2304
/*---------------------------------------------------------------------------*/
2305
static void
2306
rsp_insert_matchpoint (struct rsp_buf *buf)
2307
{
2308
  enum mp_type       type;              /* What sort of matchpoint */
2309
  unsigned long int  addr;              /* Address specified */
2310
  int                len;               /* Matchpoint length (not used) */
2311
 
2312
  /* Break out the instruction */
2313
  if (3 != sscanf (buf->data, "Z%1d,%lx,%1d", (int *)&type, &addr, &len))
2314
    {
2315
      fprintf (stderr, "Warning: RSP matchpoint insertion request not "
2316
               "recognized: ignored\n");
2317
      put_str_packet ("E01");
2318
      return;
2319
    }
2320
 
2321
  /* Sanity check that the length is 4 */
2322
  if (4 != len)
2323
    {
2324
      fprintf (stderr, "Warning: RSP matchpoint insertion length %d not "
2325
               "valid: 4 assumed\n", len);
2326
      len = 4;
2327
    }
2328
 
2329
  /* Sort out the type of matchpoint */
2330
  switch (type)
2331
    {
2332
    case BP_MEMORY:
2333
      /* Memory breakpoint - substitute a TRAP instruction */
2334
      mp_hash_add (type, addr, eval_direct32 (addr, 0, 0));
2335
      set_program32 (addr, OR1K_TRAP_INSTR);
2336
      put_str_packet ("OK");
2337
 
2338
      return;
2339
 
2340
    case BP_HARDWARE:
2341
      put_str_packet ("");              /* Not supported */
2342
      return;
2343
 
2344
    case WP_WRITE:
2345
      put_str_packet ("");              /* Not supported */
2346
      return;
2347
 
2348
    case WP_READ:
2349
      put_str_packet ("");              /* Not supported */
2350
      return;
2351
 
2352
    case WP_ACCESS:
2353
      put_str_packet ("");              /* Not supported */
2354
      return;
2355
 
2356
    default:
2357
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
2358
               "recognized: ignored\n", type);
2359
      put_str_packet ("E01");
2360
      return;
2361
 
2362
    }
2363
 
2364
}       /* rsp_insert_matchpoint () */
2365
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.