OpenCores
URL https://opencores.org/ocsvn/openrisc_2011-10-31/openrisc_2011-10-31/trunk

Subversion Repositories openrisc_2011-10-31

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

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

powered by: WebSVN 2.1.0

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