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

Subversion Repositories or1k_soc_on_altera_embedded_dev_kit

[/] [or1k_soc_on_altera_embedded_dev_kit/] [trunk/] [soc/] [sw/] [adv_jtag_bridge/] [rsp-server.c] - Blame information for rev 21

Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

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