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 50

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

powered by: WebSVN 2.1.0

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