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 51

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

powered by: WebSVN 2.1.0

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