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

Subversion Repositories adv_debug_sys

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

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

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

powered by: WebSVN 2.1.0

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