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

Subversion Repositories adv_debug_sys

[/] [adv_debug_sys/] [trunk/] [Software/] [adv_jtag_bridge/] [rsp-server.c] - Blame information for rev 56

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

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