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

Subversion Repositories or1k

[/] [or1k/] [trunk/] [or1ksim/] [debug/] [rsp-server.c] - Blame information for rev 1751

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

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

powered by: WebSVN 2.1.0

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