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

Subversion Repositories adv_debug_sys

[/] [adv_debug_sys/] [tags/] [ADS_RELEASE_1_1_0/] [Software/] [adv_jtag_bridge/] [rsp-server.c] - Blame information for rev 4

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
#include "chain_commands.h"
46
#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
          read(pipe_fds[0], &bitbucket, 1);  // Clear the byte out and discard
519
          /* 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
          // *** TODO Send a response to GDB indicating the target is not stalled?
737
          //put_str_packet("O");  // Need to hex-encode warning string
738
          fprintf(stderr, "WARNING:  Received GDB command 0x%X (%c) while target running!\n", buf->data[0], buf->data[0]);
739
        }
740
    }
741
 
742
  switch (buf->data[0])
743
    {
744
    case 0x03:
745
      fprintf(stderr, "Warning:  asynchronous BREAK received while target stopped.\n");
746
      return;
747
 
748
    case '!':
749
      /* Request for extended remote mode */
750
      put_str_packet ("OK");
751
      return;
752
 
753
    case '?':
754
      /* Return last signal ID */
755
      rsp_report_exception();
756
      return;
757
 
758
    case 'A':
759
      /* Initialization of argv not supported */
760
      fprintf (stderr, "Warning: RSP 'A' packet not supported: ignored\n");
761
      put_str_packet ("E01");
762
      return;
763
 
764
    case 'b':
765
      /* Setting baud rate is deprecated */
766
      fprintf (stderr, "Warning: RSP 'b' packet is deprecated and not "
767
               "supported: ignored\n");
768
      return;
769
 
770
    case 'B':
771
      /* Breakpoints should be set using Z packets */
772
      fprintf (stderr, "Warning: RSP 'B' packet is deprecated (use 'Z'/'z' "
773
               "packets instead): ignored\n");
774
      return;
775
 
776
    case 'c':
777
      /* Continue */
778
      rsp_continue (buf);
779
      return;
780
 
781
    case 'C':
782
      /* Continue with signal */
783
      rsp_continue_with_signal (buf);
784
      return;
785
 
786
    case 'd':
787
      /* Disable debug using a general query */
788
      fprintf (stderr, "Warning: RSP 'd' packet is deprecated (define a 'Q' "
789
               "packet instead: ignored\n");
790
      return;
791
 
792
    case 'D':
793
      /* Detach GDB. Do this by closing the client. The rules say that
794
         execution should continue. TODO. Is this really then intended
795
         meaning? Or does it just mean that only vAttach will be recognized
796
         after this? */
797
      put_str_packet ("OK");
798
      rsp_client_close ();
799
      set_stall_state (0);
800
      return;
801
 
802
    case 'F':
803
      /* File I/O is not currently supported */
804
      fprintf (stderr, "Warning: RSP file I/O not currently supported: 'F' "
805
               "packet ignored\n");
806
      return;
807
 
808
    case 'g':
809
      rsp_read_all_regs ();
810
      return;
811
 
812
    case 'G':
813
      rsp_write_all_regs (buf);
814
      return;
815
 
816
    case 'H':
817
      /* Set the thread number of subsequent operations. For now ignore
818
         silently and just reply "OK" */
819
      put_str_packet ("OK");
820
      return;
821
 
822
    case 'i':
823
      /* Single instruction step */
824
      rsp_step (buf);
825
      return;
826
 
827
    case 'I':
828
      /* Single instruction step with signal */
829
       rsp_step_with_signal (buf);
830
      return;
831
 
832
    case 'k':
833
      /* Kill request. Do nothing for now. */
834
      return;
835
 
836
    case 'm':
837
      /* Read memory (symbolic) */
838
      rsp_read_mem (buf);
839
      return;
840
 
841
    case 'M':
842
      /* Write memory (symbolic) */
843
      rsp_write_mem (buf);
844
      return;
845
 
846
    case 'p':
847
      /* Read a register */
848
      rsp_read_reg (buf);
849
      return;
850
 
851
    case 'P':
852
      /* Write a register */
853
      rsp_write_reg (buf);
854
      return;
855
 
856
    case 'q':
857
      /* Any one of a number of query packets */
858
      rsp_query (buf);
859
      return;
860
 
861
    case 'Q':
862
      /* Any one of a number of set packets */
863
      rsp_set (buf);
864
      return;
865
 
866
    case 'r':
867
      /* Reset the system. Deprecated (use 'R' instead) */
868
      fprintf (stderr, "Warning: RSP 'r' packet is deprecated (use 'R' "
869
               "packet instead): ignored\n");
870
      return;
871
 
872
    case 'R':
873
      /* Restart the program being debugged. */
874
      rsp_restart ();
875
      return;
876
 
877
    case 's':
878
      /* Single step (one high level instruction). This could be hard without
879
         DWARF2 info */
880
      rsp_step (buf);
881
      return;
882
 
883
    case 'S':
884
      /* Single step (one high level instruction) with signal. This could be
885
         hard without DWARF2 info */
886
      rsp_step_with_signal (buf);
887
      return;
888
 
889
    case 't':
890
      /* Search. This is not well defined in the manual and for now we don't
891
         support it. No response is defined. */
892
      fprintf (stderr, "Warning: RSP 't' packet not supported: ignored\n");
893
      return;
894
 
895
    case 'T':
896
      /* Is the thread alive. We are bare metal, so don't have a thread
897
         context. The answer is always "OK". */
898
      put_str_packet ("OK");
899
      return;
900
 
901
    case 'v':
902
      /* Any one of a number of packets to control execution */
903
      rsp_vpkt (buf);
904
      return;
905
 
906
    case 'X':
907
      /* Write memory (binary) */
908
      rsp_write_mem_bin (buf);
909
      return;
910
 
911
    case 'z':
912
      /* Remove a breakpoint/watchpoint. */
913
      rsp_remove_matchpoint (buf);
914
      return;
915
 
916
    case 'Z':
917
      /* Insert a breakpoint/watchpoint. */
918
      rsp_insert_matchpoint (buf);
919
      return;
920
 
921
    default:
922
      /* Unknown commands are ignored */
923
      fprintf (stderr, "Warning: Unknown RSP request %s\n", buf->data);
924
      return;
925
    }
926
}       /* rsp_client_request () */
927
 
928
 
929
/*---------------------------------------------------------------------------*/
930
/*!Close the server if it is open                                            */
931
/*---------------------------------------------------------------------------*/
932
static void
933
rsp_server_close ()
934
{
935
  // Stop the target handler thread
936
  pthread_mutex_lock(&target_handler_mutex);
937
  target_handler_state = 2;
938
  pthread_mutex_unlock(&target_handler_mutex);
939
 
940
  if (-1 != rsp.server_fd)
941
    {
942
      close (rsp.server_fd);
943
      rsp.server_fd = -1;
944
    }
945
}       /* rsp_server_close () */
946
 
947
 
948
/*---------------------------------------------------------------------------*/
949
/*!Close the client if it is open                                            */
950
/*---------------------------------------------------------------------------*/
951
static void
952
rsp_client_close ()
953
{
954
  unsigned char was_running = 0;
955
 
956
  // If target is running, stop it so we can modify SPRs
957
  pthread_mutex_lock(&rsp_mutex);
958
  was_running = rsp.target_running;
959
  pthread_mutex_unlock(&rsp_mutex);
960
  if(was_running) {
961
    set_stall_state(1);
962
  }
963
 
964
  // Clear the DSR: don't transfer control to the debug unit for any reason
965
  dbg_cpu0_write(SPR_DSR, 0);
966
 
967
  // If target was running, restart it.
968
  if(was_running) {
969
    set_stall_state(0);
970
  }
971
 
972
  // Stop the target handler thread.  MUST BE DONE AFTER THE LAST set_stall_state()!
973
  pthread_mutex_lock(&target_handler_mutex);
974
  target_handler_state = 0;
975
  pthread_mutex_unlock(&target_handler_mutex);
976
 
977
  if (-1 != rsp.client_fd)
978
    {
979
      close (rsp.client_fd);
980
      rsp.client_fd = -1;
981
    }
982
}       /* rsp_client_close () */
983
 
984
 
985
/*---------------------------------------------------------------------------*/
986
/*!Send a packet to the GDB client
987
 
988
   Modeled on the stub version supplied with GDB. Put out the data preceded by
989
   a '$', followed by a '#' and a one byte checksum. '$', '#', '*' and '}' are
990
   escaped by preceding them with '}' and then XORing the character with
991
   0x20.
992
 
993
   @param[in] buf  The data to send                                          */
994
/*---------------------------------------------------------------------------*/
995
static void
996
put_packet (struct rsp_buf *buf)
997
{
998
  int  ch;                              /* Ack char */
999
 
1000
  /* Construct $<packet info>#<checksum>. Repeat until the GDB client
1001
     acknowledges satisfactory receipt. */
1002
  do
1003
    {
1004
      unsigned char checksum = 0;        /* Computed checksum */
1005
      int           count    = 0;        /* Index into the buffer */
1006
 
1007
#if RSP_TRACE
1008
      printf ("Putting %s\n", buf->data);
1009
      fflush (stdout);
1010
#endif
1011
 
1012
      put_rsp_char ('$');               /* Start char */
1013
 
1014
      /* Body of the packet */
1015
      for (count = 0; count < buf->len; count++)
1016
        {
1017
          unsigned char  ch = buf->data[count];
1018
 
1019
          /* Check for escaped chars */
1020
          if (('$' == ch) || ('#' == ch) || ('*' == ch) || ('}' == ch))
1021
            {
1022
              ch       ^= 0x20;
1023
              checksum += (unsigned char)'}';
1024
              put_rsp_char ('}');
1025
            }
1026
 
1027
          checksum += ch;
1028
          put_rsp_char (ch);
1029
        }
1030
 
1031
      put_rsp_char ('#');               /* End char */
1032
 
1033
      /* Computed checksum */
1034
      put_rsp_char (hexchars[checksum >> 4]);
1035
      put_rsp_char (hexchars[checksum % 16]);
1036
 
1037
      /* Check for ack of connection failure */
1038
      ch = get_rsp_char ();
1039
      if (-1 == ch)
1040
        {
1041
          return;                       /* Fail the put silently. */
1042
        }
1043
    }
1044
  while ('+' != ch);
1045
 
1046
}       /* put_packet () */
1047
 
1048
 
1049
/*---------------------------------------------------------------------------*/
1050
/*!Convenience to put a constant string packet
1051
 
1052
   param[in] str  The text of the packet                                     */
1053
/*---------------------------------------------------------------------------*/
1054
static void
1055
put_str_packet (const char *str)
1056
{
1057
  struct rsp_buf  buf;
1058
  int             len = strlen (str);
1059
 
1060
  /* Construct the packet to send, so long as string is not too big,
1061
     otherwise truncate. Add EOS at the end for convenient debug printout */
1062
 
1063
  if (len >= GDB_BUF_MAX)
1064
    {
1065
      fprintf (stderr, "Warning: String %s too large for RSP packet: "
1066
               "truncated\n", str);
1067
      len = GDB_BUF_MAX - 1;
1068
    }
1069
 
1070
  strncpy (buf.data, str, len);
1071
  buf.data[len] = 0;
1072
  buf.len       = len;
1073
 
1074
  put_packet (&buf);
1075
 
1076
}       /* put_str_packet () */
1077
 
1078
 
1079
/*---------------------------------------------------------------------------*/
1080
/*!Get a packet from the GDB client
1081
 
1082
   Modeled on the stub version supplied with GDB. The data is in a static
1083
   buffer. The data should be copied elsewhere if it is to be preserved across
1084
   a subsequent call to get_packet().
1085
 
1086
   Unlike the reference implementation, we don't deal with sequence
1087
   numbers. GDB has never used them, and this implementation is only intended
1088
   for use with GDB 6.8 or later. Sequence numbers were removed from the RSP
1089
   standard at GDB 5.0.
1090
 
1091
   @return  A pointer to the static buffer containing the data                */
1092
/*---------------------------------------------------------------------------*/
1093
static struct rsp_buf *
1094
get_packet ()
1095
{
1096
  static struct rsp_buf  buf;           /* Survives the return */
1097
 
1098
  /* Keep getting packets, until one is found with a valid checksum */
1099
  while (1)
1100
    {
1101
      unsigned char  checksum;          /* The checksum we have computed */
1102
      int            count;             /* Index into the buffer */
1103
      int            ch;                /* Current character */
1104
 
1105
      /* Wait around for the start character ('$'). Ignore all other
1106
         characters */
1107
      ch = get_rsp_char ();
1108
      while (ch != '$')
1109
        {
1110
          if (-1 == ch)
1111
            {
1112
              return  NULL;             /* Connection failed */
1113
            }
1114
 
1115
          // 0x03 is a special case, an out-of-band break when running
1116
          if(ch == 0x03)
1117
            {
1118
              buf.data[0] = ch;
1119
              buf.len     = 1;
1120
              return &buf;
1121
            }
1122
 
1123
          ch = get_rsp_char ();
1124
        }
1125
 
1126
      /* Read until a '#' or end of buffer is found */
1127
      checksum =  0;
1128
      count    =  0;
1129
      while (count < GDB_BUF_MAX - 1)
1130
        {
1131
          ch = get_rsp_char ();
1132
 
1133
          /* Check for connection failure */
1134
          if (-1 == ch)
1135
            {
1136
              return  NULL;
1137
            }
1138
 
1139
          /* If we hit a start of line char begin all over again */
1140
          if ('$' == ch)
1141
            {
1142
              checksum =  0;
1143
              count    =  0;
1144
 
1145
              continue;
1146
            }
1147
 
1148
          /* Break out if we get the end of line char */
1149
          if ('#' == ch)
1150
            {
1151
              break;
1152
            }
1153
 
1154
          /* Update the checksum and add the char to the buffer */
1155
 
1156
          checksum        = checksum + (unsigned char)ch;
1157
          buf.data[count] = (char)ch;
1158
          count           = count + 1;
1159
        }
1160
 
1161
      /* Mark the end of the buffer with EOS - it's convenient for non-binary
1162
         data to be valid strings. */
1163
      buf.data[count] = 0;
1164
      buf.len         = count;
1165
 
1166
      /* If we have a valid end of packet char, validate the checksum */
1167
      if ('#' == ch)
1168
        {
1169
          unsigned char  xmitcsum;      /* The checksum in the packet */
1170
 
1171
          ch = get_rsp_char ();
1172
          if (-1 == ch)
1173
            {
1174
              return  NULL;             /* Connection failed */
1175
            }
1176
          xmitcsum = hex (ch) << 4;
1177
 
1178
          ch = get_rsp_char ();
1179
          if (-1 == ch)
1180
            {
1181
              return  NULL;             /* Connection failed */
1182
            }
1183
 
1184
          xmitcsum += hex (ch);
1185
 
1186
          /* If the checksums don't match print a warning, and put the
1187
             negative ack back to the client. Otherwise put a positive ack. */
1188
          if (checksum != xmitcsum)
1189
            {
1190
              fprintf (stderr, "Warning: Bad RSP checksum: Computed "
1191
                       "0x%02x, received 0x%02x\n", checksum, xmitcsum);
1192
 
1193
              put_rsp_char ('-');       /* Failed checksum */
1194
            }
1195
          else
1196
            {
1197
              put_rsp_char ('+');       /* successful transfer */
1198
              break;
1199
            }
1200
        }
1201
      else
1202
        {
1203
          fprintf (stderr, "Warning: RSP packet overran buffer\n");
1204
        }
1205
    }
1206
 
1207
  return &buf;                          /* Success */
1208
 
1209
}       /* get_packet () */
1210
 
1211
 
1212
/*---------------------------------------------------------------------------*/
1213
/*!Put a single character out onto the client socket
1214
 
1215
   This should only be called if the client is open, but we check for safety.
1216
 
1217
   @param[in] c  The character to put out                                    */
1218
/*---------------------------------------------------------------------------*/
1219
static void
1220
put_rsp_char (char  c)
1221
{
1222
  if (-1 == rsp.client_fd)
1223
    {
1224
      fprintf (stderr, "Warning: Attempt to write '%c' to unopened RSP "
1225
               "client: Ignored\n", c);
1226
      return;
1227
    }
1228
 
1229
  /* Write until successful (we retry after interrupts) or catastrophic
1230
     failure. */
1231
  while (1)
1232
    {
1233
      switch (write (rsp.client_fd, &c, sizeof (c)))
1234
        {
1235
        case -1:
1236
          /* Error: only allow interrupts or would block */
1237
          if ((EAGAIN != errno) && (EINTR != errno))
1238
            {
1239
              fprintf (stderr, "Warning: Failed to write to RSP client: "
1240
                       "Closing client connection: %s\n",
1241
                       strerror (errno));
1242
              rsp_client_close ();
1243
              return;
1244
            }
1245
 
1246
          break;
1247
 
1248
        case 0:
1249
          break;                /* Nothing written! Try again */
1250
 
1251
        default:
1252
          return;               /* Success, we can return */
1253
        }
1254
    }
1255
}       /* put_rsp_char () */
1256
 
1257
 
1258
/*---------------------------------------------------------------------------*/
1259
/*!Get a single character from the client socket
1260
 
1261
   This should only be called if the client is open, but we check for safety.
1262
 
1263
   @return  The character read, or -1 on failure                             */
1264
/*---------------------------------------------------------------------------*/
1265
static int
1266
get_rsp_char ()
1267
{
1268
  unsigned char  c;             /* The character read */
1269
 
1270
  if (-1 == rsp.client_fd)
1271
    {
1272
      fprintf (stderr, "Warning: Attempt to read from unopened RSP "
1273
               "client: Ignored\n");
1274
      return  -1;
1275
    }
1276
 
1277
  /* Read until successful (we retry after interrupts) or catastrophic
1278
     failure. */
1279
  while (1)
1280
    {
1281
      switch (read (rsp.client_fd, &c, sizeof (c)))
1282
        {
1283
        case -1:
1284
          /* Error: only allow interrupts or would block */
1285
          if ((EAGAIN != errno) && (EINTR != errno))
1286
            {
1287
              fprintf (stderr, "Warning: Failed to read from RSP client: "
1288
                       "Closing client connection: %s\n",
1289
                       strerror (errno));
1290
              rsp_client_close ();
1291
              return  -1;
1292
            }
1293
 
1294
          break;
1295
 
1296
        case 0:
1297
          // EOF
1298
          rsp_client_close ();
1299
          return  -1;
1300
 
1301
        default:
1302
          return  c & 0xff;     /* Success, we can return (no sign extend!) */
1303
        }
1304
    }
1305
}       /* get_rsp_char () */
1306
 
1307
 
1308
/*---------------------------------------------------------------------------*/
1309
/*!"Unescape" RSP binary data
1310
 
1311
   '#', '$' and '}' are escaped by preceding them by '}' and oring with 0x20.
1312
 
1313
   This function reverses that, modifying the data in place.
1314
 
1315
   @param[in] data  The array of bytes to convert
1316
   @para[in]  len   The number of bytes to be converted
1317
 
1318
   @return  The number of bytes AFTER conversion                             */
1319
/*---------------------------------------------------------------------------*/
1320
static int
1321
rsp_unescape (char *data,
1322
              int   len)
1323
{
1324
  int  from_off = 0;             /* Offset to source char */
1325
  int  to_off   = 0;             /* Offset to dest char */
1326
 
1327
  while (from_off < len)
1328
    {
1329
      /* Is it escaped */
1330
      if ( '}' == data[from_off])
1331
        {
1332
          from_off++;
1333
          data[to_off] = data[from_off] ^ 0x20;
1334
        }
1335
      else
1336
        {
1337
          data[to_off] = data[from_off];
1338
        }
1339
 
1340
      from_off++;
1341
      to_off++;
1342
    }
1343
 
1344
  return  to_off;
1345
 
1346
}       /* rsp_unescape () */
1347
 
1348
 
1349
/*---------------------------------------------------------------------------*/
1350
/*!Initialize the matchpoint hash table
1351
 
1352
   This is an open hash table, so this function clears all the links to
1353
   NULL.                                                                     */
1354
/*---------------------------------------------------------------------------*/
1355
static void
1356
mp_hash_init ()
1357
{
1358
  int  i;
1359
 
1360
  for (i = 0; i < MP_HASH_SIZE; i++)
1361
    {
1362
      rsp.mp_hash[i] = NULL;
1363
    }
1364
}       /* mp_hash_init () */
1365
 
1366
 
1367
/*---------------------------------------------------------------------------*/
1368
/*!Add an entry to the matchpoint hash table
1369
 
1370
   Add the entry if it wasn't already there. If it was there do nothing. The
1371
   match just be on type and addr. The instr need not match, since if this is
1372
   a duplicate insertion (perhaps due to a lost packet) they will be
1373
   different.
1374
 
1375
   @param[in] type   The type of matchpoint
1376
   @param[in] addr   The address of the matchpoint
1377
   @para[in]  instr  The instruction to associate with the address           */
1378
/*---------------------------------------------------------------------------*/
1379
static void
1380
mp_hash_add (enum mp_type       type,
1381
             unsigned long int  addr,
1382
             unsigned long int  instr)
1383
{
1384
  int              hv    = addr % MP_HASH_SIZE;
1385
  struct mp_entry *curr;
1386
 
1387
  /* See if we already have the entry */
1388
  for(curr = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1389
    {
1390
      if ((type == curr->type) && (addr == curr->addr))
1391
        {
1392
          return;               /* We already have the entry */
1393
        }
1394
    }
1395
 
1396
  /* Insert the new entry at the head of the chain */
1397
  curr = malloc (sizeof (*curr));
1398
 
1399
  curr->type  = type;
1400
  curr->addr  = addr;
1401
  curr->instr = instr;
1402
  curr->next  = rsp.mp_hash[hv];
1403
 
1404
  rsp.mp_hash[hv] = curr;
1405
 
1406
}       /* mp_hash_add () */
1407
 
1408
 
1409
/*---------------------------------------------------------------------------*/
1410
/*!Look up an entry in the matchpoint hash table
1411
 
1412
   The match must be on type AND addr.
1413
 
1414
   @param[in] type   The type of matchpoint
1415
   @param[in] addr   The address of the matchpoint
1416
 
1417
   @return  The entry deleted, or NULL if the entry was not found            */
1418
/*---------------------------------------------------------------------------*/
1419
static struct mp_entry *
1420
mp_hash_lookup (enum mp_type       type,
1421
                unsigned long int  addr)
1422
{
1423
  int              hv   = addr % MP_HASH_SIZE;
1424
  struct mp_entry *curr;
1425
 
1426
  /* Search */
1427
  for (curr = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1428
    {
1429
      if ((type == curr->type) && (addr == curr->addr))
1430
        {
1431
          return  curr;         /* The entry found */
1432
        }
1433
    }
1434
 
1435
  /* Not found */
1436
  return  NULL;
1437
 
1438
}       /* mp_hash_lookup () */
1439
 
1440
 
1441
/*---------------------------------------------------------------------------*/
1442
/*!Delete an entry from the matchpoint hash table
1443
 
1444
   If it is there the entry is deleted from the hash table. If it is not
1445
   there, no action is taken. The match must be on type AND addr.
1446
 
1447
   The usual fun and games tracking the previous entry, so we can delete
1448
   things.
1449
 
1450
   @note  The deletion DOES NOT free the memory associated with the entry,
1451
          since that is returned. The caller should free the memory when they
1452
          have used the information.
1453
 
1454
   @param[in] type   The type of matchpoint
1455
   @param[in] addr   The address of the matchpoint
1456
 
1457
   @return  The entry deleted, or NULL if the entry was not found            */
1458
/*---------------------------------------------------------------------------*/
1459
static struct mp_entry *
1460
mp_hash_delete (enum mp_type       type,
1461
                unsigned long int  addr)
1462
{
1463
  int              hv   = addr % MP_HASH_SIZE;
1464
  struct mp_entry *prev = NULL;
1465
  struct mp_entry *curr;
1466
 
1467
  /* Search */
1468
  for (curr  = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1469
    {
1470
      if ((type == curr->type) && (addr == curr->addr))
1471
        {
1472
          /* Found - delete. Method depends on whether we are the head of
1473
             chain. */
1474
          if (NULL == prev)
1475
            {
1476
              rsp.mp_hash[hv] = curr->next;
1477
            }
1478
          else
1479
            {
1480
              prev->next = curr->next;
1481
            }
1482
 
1483
          return  curr;         /* The entry deleted */
1484
        }
1485
 
1486
      prev = curr;
1487
    }
1488
 
1489
  /* Not found */
1490
  return  NULL;
1491
 
1492
}       /* mp_hash_delete () */
1493
 
1494
 
1495
/*---------------------------------------------------------------------------*/
1496
/*!Utility to give the value of a hex char
1497
 
1498
   @param[in] ch  A character representing a hexadecimal digit. Done as -1,
1499
                  for consistency with other character routines, which can use
1500
                  -1 as EOF.
1501
 
1502
   @return  The value of the hex character, or -1 if the character is
1503
            invalid.                                                         */
1504
/*---------------------------------------------------------------------------*/
1505
static int
1506
hex (int  c)
1507
{
1508
  return  ((c >= 'a') && (c <= 'f')) ? c - 'a' + 10 :
1509
          ((c >= '0') && (c <= '9')) ? c - '0' :
1510
          ((c >= 'A') && (c <= 'F')) ? c - 'A' + 10 : -1;
1511
 
1512
}       /* hex () */
1513
 
1514
 
1515
/*---------------------------------------------------------------------------*/
1516
/*!Convert a register to a hex digit string
1517
 
1518
   The supplied 32-bit value is converted to an 8 digit hex string according
1519
   the target endianism. It is null terminated for convenient printing.
1520
 
1521
   @param[in]  val  The value to convert
1522
   @param[out] buf  The buffer for the text string                           */
1523
/*---------------------------------------------------------------------------*/
1524
static void
1525
reg2hex (unsigned long int  val,
1526
         char              *buf)
1527
{
1528
  int  n;                       /* Counter for digits */
1529
 
1530
  for (n = 0; n < 8; n++)
1531
    {
1532
#ifdef WORDSBIGENDIAN
1533
      int  nyb_shift = n * 4;
1534
#else
1535
      int  nyb_shift = 28 - (n * 4);
1536
#endif
1537
      buf[n] = hexchars[(val >> nyb_shift) & 0xf];
1538
    }
1539
 
1540
  buf[8] = 0;                    /* Useful to terminate as string */
1541
 
1542
}       /* reg2hex () */
1543
 
1544
 
1545
/*---------------------------------------------------------------------------*/
1546
/*!Convert a hex digit string to a register value
1547
 
1548
   The supplied 8 digit hex string is converted to a 32-bit value according
1549
   the target endianism
1550
 
1551
   @param[in] buf  The buffer with the hex string
1552
 
1553
   @return  The value to convert                                             */
1554
/*---------------------------------------------------------------------------*/
1555
static unsigned long int
1556
hex2reg (char *buf)
1557
{
1558
  int                n;         /* Counter for digits */
1559
  unsigned long int  val = 0;    /* The result */
1560
 
1561
  for (n = 0; n < 8; n++)
1562
    {
1563
#ifdef WORDSBIGENDIAN
1564
      int  nyb_shift = n * 4;
1565
#else
1566
      int  nyb_shift = 28 - (n * 4);
1567
#endif
1568
      val |= hex (buf[n]) << nyb_shift;
1569
    }
1570
 
1571
  return val;
1572
 
1573
}       /* hex2reg () */
1574
 
1575
 
1576
/*---------------------------------------------------------------------------*/
1577
/*!Convert an ASCII character string to pairs of hex digits
1578
 
1579
   Both source and destination are null terminated.
1580
 
1581
   @param[out] dest  Buffer to store the hex digit pairs (null terminated)
1582
   @param[in]  src   The ASCII string (null terminated)                      */
1583
/*---------------------------------------------------------------------------*/
1584
static void  ascii2hex (char *dest,
1585
                        char *src)
1586
{
1587
  int  i;
1588
 
1589
  /* Step through converting the source string */
1590
  for (i = 0; src[i] != '\0'; i++)
1591
    {
1592
      char  ch = src[i];
1593
 
1594
      dest[i * 2]     = hexchars[ch >> 4 & 0xf];
1595
      dest[i * 2 + 1] = hexchars[ch      & 0xf];
1596
    }
1597
 
1598
  dest[i * 2] = '\0';
1599
 
1600
}       /* ascii2hex () */
1601
 
1602
 
1603
/*---------------------------------------------------------------------------*/
1604
/*!Convert pairs of hex digits to an ASCII character string
1605
 
1606
   Both source and destination are null terminated.
1607
 
1608
   @param[out] dest  The ASCII string (null terminated)
1609
   @param[in]  src   Buffer holding the hex digit pairs (null terminated)    */
1610
/*---------------------------------------------------------------------------*/
1611
static void  hex2ascii (char *dest,
1612
                        char *src)
1613
{
1614
  int  i;
1615
 
1616
  /* Step through convering the source hex digit pairs */
1617
  for (i = 0; src[i * 2] != '\0' && src[i * 2 + 1] != '\0'; i++)
1618
    {
1619
      dest[i] = ((hex (src[i * 2]) & 0xf) << 4) | (hex (src[i * 2 + 1]) & 0xf);
1620
    }
1621
 
1622
  dest[i] = '\0';
1623
 
1624
}       /* hex2ascii () */
1625
 
1626
 
1627
/*---------------------------------------------------------------------------*/
1628
/*!Set the program counter
1629
 
1630
   This sets the value in the NPC SPR. Not completely trivial, since this is
1631
   actually cached in cpu_state.pc. Any reset of the NPC also involves
1632
   clearing the delay state and setting the pcnext global.
1633
 
1634
   Only actually do this if the requested address is different to the current
1635
   NPC (avoids clearing the delay pipe).
1636
 
1637
   @param[in] addr  The address to use                                       */
1638
/*---------------------------------------------------------------------------*/
1639
static unsigned int set_npc (unsigned long int  addr)
1640
{
1641
  int errcode;
1642
 
1643
  errcode = dbg_cpu0_write(SPR_NPC, addr);
1644
  cached_npc = addr;
1645
  use_cached_npc = 1;
1646
 
1647
  /*  This was done in the simulator.  Is any of this necessary on the hardware?  --NAY
1648
    if (cpu_state.pc != addr)
1649
    {
1650
    cpu_state.pc         = addr;
1651
    cpu_state.delay_insn = 0;
1652
    pcnext               = addr + 4;
1653
    }
1654
  */
1655
  return errcode;
1656
}       /* set_npc () */
1657
 
1658
 
1659
/*---------------------------------------------------------------------------*/
1660
/*!Send a packet acknowledging an exception has occurred
1661
 
1662
   This is only called if there is a client FD to talk to                    */
1663
/*---------------------------------------------------------------------------*/
1664
static void
1665
rsp_report_exception ()
1666
{
1667
  struct rsp_buf  buf;
1668
 
1669
  /* Construct a signal received packet */
1670
  buf.data[0] = 'S';
1671
  buf.data[1] = hexchars[rsp.sigval >> 4];
1672
  buf.data[2] = hexchars[rsp.sigval % 16];
1673
  buf.data[3] = 0;
1674
  buf.len     = strlen (buf.data);
1675
 
1676
  put_packet (&buf);
1677
 
1678
}       /* rsp_report_exception () */
1679
 
1680
 
1681
/*---------------------------------------------------------------------------*/
1682
/*!Handle a RSP continue request
1683
 
1684
   Parse the command to see if there is an address. Uses the underlying
1685
   generic continue function, with EXCEPT_NONE.
1686
 
1687
   @param[in] buf  The full continue packet                                  */
1688
/*---------------------------------------------------------------------------*/
1689
static void
1690
rsp_continue (struct rsp_buf *buf)
1691
{
1692
  unsigned long int  addr;              /* Address to continue from, if any */
1693
 
1694
  if (strncmp(buf->data, "c", 2))
1695
    {
1696
      if(1 != sscanf (buf->data, "c%lx", &addr))
1697
        {
1698
          fprintf (stderr,
1699
                   "Warning: RSP continue address %s not recognized: ignored\n",
1700
                   buf->data);
1701
        }
1702
      else
1703
        {
1704
          /* Set the address as the value of the next program counter */
1705
          // TODO Is support for this really that simple?  --NAY
1706
          set_npc (addr);
1707
        }
1708
    }
1709
 
1710
  rsp_continue_generic (EXCEPT_NONE);
1711
 
1712
}       /* rsp_continue () */
1713
 
1714
 
1715
/*---------------------------------------------------------------------------*/
1716
/*!Handle a RSP continue with signal request
1717
 
1718
   Currently null. Will use the underlying generic continue function.
1719
 
1720
   @param[in] buf  The full continue with signal packet                      */
1721
/*---------------------------------------------------------------------------*/
1722
static void
1723
rsp_continue_with_signal (struct rsp_buf *buf)
1724
{
1725
  printf ("RSP continue with signal '%s' received\n", buf->data);
1726
 
1727
}       /* rsp_continue_with_signal () */
1728
 
1729
 
1730
/*---------------------------------------------------------------------------*/
1731
/*!Generic processing of a continue request
1732
 
1733
   The signal may be EXCEPT_NONE if there is no exception to be
1734
   handled. Currently the exception is ignored.
1735
 
1736
   The single step flag is cleared in the debug registers and then the
1737
   processor is unstalled.
1738
 
1739
   @param[in] addr    Address from which to step
1740
   @param[in] except  The exception to use (if any)                          */
1741
/*---------------------------------------------------------------------------*/
1742
static void
1743
rsp_continue_generic (unsigned long int  except)
1744
{
1745
  unsigned long tmp;
1746
 
1747
  /* Clear Debug Reason Register and watchpoint break generation in Debug Mode
1748
     Register 2 */
1749
  dbg_cpu0_write(SPR_DRR, 0);
1750
  dbg_cpu0_read(SPR_DMR2, &tmp);
1751
  tmp &= ~SPR_DMR2_WGB;
1752
  dbg_cpu0_write(SPR_DMR2, tmp);
1753
 
1754
  /* Clear the single step trigger in Debug Mode Register 1 and set traps to be
1755
     handled by the debug unit in the Debug Stop Register */
1756
  dbg_cpu0_read(SPR_DMR1, &tmp);
1757
  tmp &= ~(SPR_DMR1_ST|SPR_DMR1_BT); // clear single-step and trap-on-branch
1758
  dbg_cpu0_write(SPR_DMR1, tmp);
1759
 
1760
  // *** TODO Is there ever a situation where the DSR will not be set to give us control on a TRAP?  --NAY
1761
 
1762
  /* Unstall the processor (also starts the target handler thread) */
1763
  set_stall_state (0);
1764
 
1765
  /* Note the GDB client is now waiting for a reply. */
1766
  rsp.client_waiting = 1;
1767
  rsp.single_step_mode = 0;
1768
 
1769
}       /* rsp_continue_generic () */
1770
 
1771
 
1772
/*---------------------------------------------------------------------------*/
1773
/*!Handle a RSP read all registers request
1774
 
1775
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PPC
1776
   (i.e. SPR PPC), NPC (i.e. SPR NPC) and SR (i.e. SPR SR). Each register is
1777
   returned as a sequence of bytes in target endian order.
1778
 
1779
   Each byte is packed as a pair of hex digits.                              */
1780
/*---------------------------------------------------------------------------*/
1781
static void
1782
rsp_read_all_regs ()
1783
{
1784
  struct rsp_buf  buf;                  /* Buffer for the reply */
1785
  int             r;                    /* Register index */
1786
  unsigned long regbuf[MAX_GPRS];
1787
  unsigned int errcode = APP_ERR_NONE;
1788
 
1789
  // Read all the GPRs in a single burst, for efficiency
1790
  errcode = dbg_cpu0_read_block(SPR_GPR_BASE, regbuf, MAX_GPRS);
1791
 
1792
  /* Format the GPR data for output */
1793
  for (r = 0; r < MAX_GPRS; r++)
1794
    {
1795
      reg2hex(regbuf[r], &(buf.data[r * 8]));
1796
    }
1797
 
1798
  /* PPC, NPC and SR have consecutive addresses, read in one burst */
1799
  errcode |= dbg_cpu0_read_block(SPR_NPC, regbuf, 3);
1800
 
1801
  // Note that reg2hex adds a NULL terminator; as such, they must be
1802
  // put in buf.data in numerical order:  PPC, NPC, SR
1803
  reg2hex(regbuf[2], &(buf.data[PPC_REGNUM * 8]));
1804
 
1805
  if(use_cached_npc == 1) {  // Hackery to work around CPU hardware quirk 
1806
    reg2hex(cached_npc, &(buf.data[NPC_REGNUM * 8]));
1807
  }
1808
  else {
1809
    reg2hex(regbuf[0], &(buf.data[NPC_REGNUM * 8]));
1810
  }
1811
 
1812
  reg2hex(regbuf[1], &(buf.data[SR_REGNUM  * 8]));
1813
 
1814
  //fprintf(stderr, "Read SPRs:  0x%08X, 0x%08X, 0x%08X\n", regbuf[0], regbuf[1], regbuf[2]);
1815
 
1816
  /*
1817
  dbg_cpu0_read(SPR_PPC, &tmp);
1818
  reg2hex(tmp, &(buf.data[PPC_REGNUM * 8]));
1819
 
1820
  if(use_cached_npc == 1) {  // Hackery to work around CPU hardware quirk
1821
    tmp = cached_npc;
1822
  }
1823
  else {
1824
    dbg_cpu0_read(SPR_NPC, &tmp);
1825
  }
1826
  reg2hex(tmp, &(buf.data[NPC_REGNUM * 8]));
1827
 
1828
  dbg_cpu0_read(SPR_SR, &tmp);
1829
  reg2hex(tmp, &(buf.data[SR_REGNUM  * 8]));
1830
  */
1831
 
1832
  if(errcode == APP_ERR_NONE) {
1833
    /* Finalize the packet and send it */
1834
    buf.data[NUM_REGS * 8] = 0;
1835
    buf.len                = NUM_REGS * 8;
1836
    put_packet (&buf);
1837
  }
1838
  else {
1839
    fprintf(stderr, "Error while reading all registers: %s\n", get_err_string(errcode));
1840
    put_str_packet("E01");
1841
  }
1842
 
1843
}       /* rsp_read_all_regs () */
1844
 
1845
 
1846
/*---------------------------------------------------------------------------*/
1847
/*!Handle a RSP write all registers request
1848
 
1849
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PPC
1850
   (i.e. SPR PPC), NPC (i.e. SPR NPC) and SR (i.e. SPR SR). Each register is
1851
   supplied as a sequence of bytes in target endian order.
1852
 
1853
   Each byte is packed as a pair of hex digits.
1854
 
1855
   @todo There is no error checking at present. Non-hex chars will generate a
1856
         warning message, but there is no other check that the right amount
1857
         of data is present. The result is always "OK".
1858
 
1859
   @param[in] buf  The original packet request.                              */
1860
/*---------------------------------------------------------------------------*/
1861
static void
1862
rsp_write_all_regs (struct rsp_buf *buf)
1863
{
1864
  int             r;                    /* Register index */
1865
  unsigned long regbuf[MAX_GPRS];
1866
  unsigned int errcode;
1867
 
1868
  /* The GPRs */
1869
  for (r = 0; r < MAX_GPRS; r++)
1870
    {
1871
      // Set up the data for a burst access
1872
      regbuf[r] = hex2reg (&(buf->data[r * 8]));
1873
    }
1874
 
1875
  errcode = dbg_cpu0_write_block(SPR_GPR_BASE, regbuf, MAX_GPRS);
1876
 
1877
  /* PPC, NPC and SR */
1878
  regbuf[0] = hex2reg (&(buf->data[NPC_REGNUM * 8]));
1879
  regbuf[1] = hex2reg (&(buf->data[SR_REGNUM  * 8]));
1880
  regbuf[2] = hex2reg (&(buf->data[PPC_REGNUM * 8]));
1881
 
1882
  errcode |= dbg_cpu0_write_block(SPR_NPC, regbuf, 3);
1883
 
1884
  /*
1885
  tmp = hex2reg (&(buf->data[PPC_REGNUM * 8]));
1886
  dbg_cpu0_write(SPR_PPC, tmp);
1887
 
1888
  tmp = hex2reg (&(buf->data[SR_REGNUM  * 8]));
1889
  dbg_cpu0_write(SPR_SR, tmp);
1890
 
1891
  tmp = hex2reg (&(buf->data[NPC_REGNUM * 8]));
1892
  dbg_cpu0_write(SPR_NPC, tmp);
1893
  */
1894
 
1895
  if(errcode == APP_ERR_NONE)
1896
    put_str_packet ("OK");
1897
  else {
1898
    fprintf(stderr, "Error while writing all registers: %s\n", get_err_string(errcode));
1899
    put_str_packet("E01");
1900
  }
1901
 
1902
}       /* rsp_write_all_regs () */
1903
 
1904
 
1905
/*---------------------------------------------------------------------------*/
1906
/*!Handle a RSP read memory (symbolic) request
1907
 
1908
   Syntax is:
1909
 
1910
     m<addr>,<length>:
1911
 
1912
   The response is the bytes, lowest address first, encoded as pairs of hex
1913
   digits.
1914
 
1915
   The length given is the number of bytes to be read.
1916
 
1917
   @note This function reuses buf, so trashes the original command.
1918
 
1919
   @param[in] buf  The command received                                      */
1920
/*---------------------------------------------------------------------------*/
1921
static void
1922
rsp_read_mem (struct rsp_buf *buf)
1923
{
1924
  unsigned int    addr;                 /* Where to read the memory */
1925
  int             len;                  /* Number of bytes to read */
1926
  int             off;                  /* Offset into the memory */
1927
  unsigned int errcode = APP_ERR_NONE;
1928
 
1929
  if (2 != sscanf (buf->data, "m%x,%x:", &addr, &len))
1930
    {
1931
      fprintf (stderr, "Warning: Failed to recognize RSP read memory "
1932
               "command: %s\n", buf->data);
1933
      put_str_packet ("E01");
1934
      return;
1935
    }
1936
 
1937
  /* Make sure we won't overflow the buffer (2 chars per byte) */
1938
  if ((len * 2) >= GDB_BUF_MAX)
1939
    {
1940
      fprintf (stderr, "Warning: Memory read %s too large for RSP packet: "
1941
               "truncated\n", buf->data);
1942
      len = (GDB_BUF_MAX - 1) / 2;
1943
    }
1944
 
1945
  // Do the memory read into a temporary buffer
1946
  unsigned char *tmpbuf = (unsigned char *) malloc(len);  // *** TODO check return, don't always malloc (use realloc)
1947
  errcode = dbg_wb_read_block8(addr, tmpbuf, len);
1948
 
1949
 
1950
  /* Refill the buffer with the reply */
1951
  for (off = 0; off < len; off++)
1952
    {
1953
      unsigned char  ch;                /* The byte at the address */
1954
 
1955
      /* Check memory area is valid. Not really possible without knowing hardware configuration. */
1956
 
1957
      // Get the memory direct - no translation.
1958
      ch = tmpbuf[off];
1959
      buf->data[off * 2]     = hexchars[ch >>   4];
1960
      buf->data[off * 2 + 1] = hexchars[ch &  0xf];
1961
    }
1962
 
1963
  free(tmpbuf);
1964
 
1965
  if(errcode == APP_ERR_NONE) {
1966
    buf->data[off * 2] = 0;                      /* End of string */
1967
    buf->len           = strlen (buf->data);
1968
    put_packet (buf);
1969
  }
1970
  else {
1971
    fprintf(stderr, "Error reading memory: %s\n", get_err_string(errcode));
1972
    put_str_packet("E01");
1973
  }
1974
 
1975
}       /* rsp_read_mem () */
1976
 
1977
 
1978
/*---------------------------------------------------------------------------*/
1979
/*!Handle a RSP write memory (symbolic) request
1980
 
1981
   Syntax is:
1982
 
1983
     m<addr>,<length>:<data>
1984
 
1985
   The data is the bytes, lowest address first, encoded as pairs of hex
1986
   digits.
1987
 
1988
   The length given is the number of bytes to be written.
1989
 
1990
   @note This function reuses buf, so trashes the original command.
1991
 
1992
   @param[in] buf  The command received                                      */
1993
/*---------------------------------------------------------------------------*/
1994
static void
1995
rsp_write_mem (struct rsp_buf *buf)
1996
{
1997
  unsigned int    addr;                 /* Where to write the memory */
1998
  int             len;                  /* Number of bytes to write */
1999
  char           *symdat;               /* Pointer to the symboli data */
2000
  int             datlen;               /* Number of digits in symbolic data */
2001
  int             off;                  /* Offset into the memory */
2002
  unsigned int    errcode;
2003
 
2004
  if (2 != sscanf (buf->data, "M%x,%x:", &addr, &len))
2005
    {
2006
      fprintf (stderr, "Warning: Failed to recognize RSP write memory "
2007
               "command: %s\n", buf->data);
2008
      put_str_packet ("E01");
2009
      return;
2010
    }
2011
 
2012
  /* Find the start of the data and check there is the amount we expect. */
2013
  symdat = memchr ((const void *)buf->data, ':', GDB_BUF_MAX) + 1;
2014
  datlen = buf->len - (symdat - buf->data);
2015
 
2016
  /* Sanity check */
2017
  if (len * 2 != datlen)
2018
    {
2019
      fprintf (stderr, "Warning: Write of %d digits requested, but %d digits "
2020
               "supplied: packet ignored\n", len * 2, datlen );
2021
      put_str_packet ("E01");
2022
      return;
2023
    }
2024
 
2025
  /* Write the bytes to memory */
2026
  // Put all the data into a single buffer, so it can be burst-written via JTAG.
2027
  // One burst is much faster than many single-byte transactions.
2028
  unsigned char *tmpbuf = (unsigned char *) malloc(len);
2029
  for (off = 0; off < len; off++)
2030
    {
2031
      unsigned char  nyb1 = hex (symdat[off * 2]);
2032
      unsigned char  nyb2 = hex (symdat[off * 2 + 1]);
2033
      tmpbuf[off] = (nyb1 << 4) | nyb2;
2034
    }
2035
 
2036
  errcode = dbg_wb_write_block8(addr, tmpbuf, len);
2037
  free(tmpbuf);
2038
 
2039
  /* Can't really check if the memory addresses are valid on hardware. */
2040
  if(errcode == APP_ERR_NONE) {
2041
    put_str_packet ("OK");
2042
  }
2043
  else {
2044
    fprintf(stderr, "Error writing memory: %s\n", get_err_string(errcode));
2045
    put_str_packet("E01");
2046
  }
2047
 
2048
}       /* rsp_write_mem () */
2049
 
2050
 
2051
/*---------------------------------------------------------------------------*/
2052
/*!Read a single register
2053
 
2054
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PC
2055
   (i.e. SPR NPC) and SR (i.e. SPR SR). The register is returned as a
2056
   sequence of bytes in target endian order.
2057
 
2058
   Each byte is packed as a pair of hex digits.
2059
 
2060
   @param[in] buf  The original packet request. Reused for the reply.        */
2061
/*---------------------------------------------------------------------------*/
2062
static void
2063
rsp_read_reg (struct rsp_buf *buf)
2064
{
2065
  unsigned int  regnum;
2066
  unsigned long tmp;
2067
  unsigned int errcode = APP_ERR_NONE;
2068
 
2069
  /* Break out the fields from the data */
2070
  if (1 != sscanf (buf->data, "p%x", &regnum))
2071
    {
2072
      fprintf (stderr, "Warning: Failed to recognize RSP read register "
2073
               "command: \'%s\'\n", buf->data);
2074
      put_str_packet ("E01");
2075
      return;
2076
    }
2077
 
2078
  /* Get the relevant register */
2079
  if (regnum < MAX_GPRS)
2080
    {
2081
      errcode = dbg_cpu0_read(SPR_GPR_BASE+regnum, &tmp);
2082
    }
2083
  else if (PPC_REGNUM == regnum)
2084
    {
2085
      errcode = dbg_cpu0_read(SPR_PPC, &tmp);
2086
    }
2087
  else if (NPC_REGNUM == regnum)
2088
    {
2089
      if(use_cached_npc) {
2090
        tmp = cached_npc;
2091
      } else {
2092
        errcode = dbg_cpu0_read(SPR_NPC, &tmp);
2093
      }
2094
    }
2095
  else if (SR_REGNUM == regnum)
2096
    {
2097
      errcode = dbg_cpu0_read(SPR_SR, &tmp);
2098
    }
2099
  else
2100
    {
2101
      /* Error response if we don't know the register */
2102
      fprintf (stderr, "Warning: Attempt to read unknown register 0x%x: "
2103
               "ignored\n", regnum);
2104
      put_str_packet ("E01");
2105
      return;
2106
    }
2107
 
2108
  if(errcode == APP_ERR_NONE) {
2109
    reg2hex(tmp, buf->data);
2110
    buf->len = strlen (buf->data);
2111
    put_packet (buf);
2112
  }
2113
  else {
2114
    fprintf(stderr, "Error reading register: %s\n", get_err_string(errcode));
2115
    put_str_packet("E01");
2116
  }
2117
 
2118
}       /* rsp_read_reg () */
2119
 
2120
 
2121
/*---------------------------------------------------------------------------*/
2122
/*!Write a single register
2123
 
2124
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PC
2125
   (i.e. SPR NPC) and SR (i.e. SPR SR). The register is specified as a
2126
   sequence of bytes in target endian order.
2127
 
2128
   Each byte is packed as a pair of hex digits.
2129
 
2130
   @param[in] buf  The original packet request.                              */
2131
/*---------------------------------------------------------------------------*/
2132
static void
2133
rsp_write_reg (struct rsp_buf *buf)
2134
{
2135
  unsigned int  regnum;
2136
  char          valstr[9];              /* Allow for EOS on the string */
2137
  unsigned int  errcode = APP_ERR_NONE;
2138
 
2139
  /* Break out the fields from the data */
2140
  if (2 != sscanf (buf->data, "P%x=%8s", &regnum, valstr))
2141
    {
2142
      fprintf (stderr, "Warning: Failed to recognize RSP write register "
2143
               "command: %s\n", buf->data);
2144
      put_str_packet ("E01");
2145
      return;
2146
    }
2147
 
2148
  /* Set the relevant register.  Must translate between GDB register numbering and hardware reg. numbers. */
2149
  if (regnum < MAX_GPRS)
2150
    {
2151
      errcode = dbg_cpu0_write(SPR_GPR_BASE+regnum, hex2reg(valstr));
2152
    }
2153
  else if (PPC_REGNUM == regnum)
2154
    {
2155
      errcode = dbg_cpu0_write(SPR_PPC, hex2reg(valstr));
2156
    }
2157
  else if (NPC_REGNUM == regnum)
2158
    {
2159
      errcode = set_npc (hex2reg (valstr));
2160
    }
2161
  else if (SR_REGNUM == regnum)
2162
    {
2163
      errcode = dbg_cpu0_write(SPR_SR, hex2reg(valstr));
2164
    }
2165
  else
2166
    {
2167
      /* Error response if we don't know the register */
2168
      fprintf (stderr, "Warning: Attempt to write unknown register 0x%x: "
2169
               "ignored\n", regnum);
2170
      put_str_packet ("E01");
2171
      return;
2172
    }
2173
 
2174
  if(errcode == APP_ERR_NONE) {
2175
    put_str_packet ("OK");
2176
  }
2177
  else {
2178
    fprintf(stderr, "Error writing register: %s\n", get_err_string(errcode));
2179
    put_str_packet("E01");
2180
  }
2181
 
2182
}       /* rsp_write_reg () */
2183
 
2184
 
2185
/*---------------------------------------------------------------------------*/
2186
/*!Handle a RSP query request
2187
 
2188
   @param[in] buf  The request                                               */
2189
/*---------------------------------------------------------------------------*/
2190
static void
2191
rsp_query (struct rsp_buf *buf)
2192
{
2193
  if (0 == strcmp ("qC", buf->data))
2194
    {
2195
      /* Return the current thread ID (unsigned hex). A null response
2196
         indicates to use the previously selected thread. Since we do not
2197
         support a thread concept, this is the appropriate response. */
2198
      put_str_packet ("");
2199
    }
2200
  else if (0 == strncmp ("qCRC", buf->data, strlen ("qCRC")))
2201
    {
2202
      /* Return CRC of memory area */
2203
      fprintf (stderr, "Warning: RSP CRC query not supported\n");
2204
      put_str_packet ("E01");
2205
    }
2206
  else if (0 == strcmp ("qfThreadInfo", buf->data))
2207
    {
2208
      /* Return info about active threads. We return just '-1' */
2209
      put_str_packet ("m-1");
2210
    }
2211
  else if (0 == strcmp ("qsThreadInfo", buf->data))
2212
    {
2213
      /* Return info about more active threads. We have no more, so return the
2214
         end of list marker, 'l' */
2215
      put_str_packet ("l");
2216
    }
2217
  else if (0 == strncmp ("qGetTLSAddr:", buf->data, strlen ("qGetTLSAddr:")))
2218
    {
2219
      /* We don't support this feature */
2220
      put_str_packet ("");
2221
    }
2222
  else if (0 == strncmp ("qL", buf->data, strlen ("qL")))
2223
    {
2224
      /* Deprecated and replaced by 'qfThreadInfo' */
2225
      fprintf (stderr, "Warning: RSP qL deprecated: no info returned\n");
2226
      put_str_packet ("qM001");
2227
    }
2228
  else if (0 == strcmp ("qOffsets", buf->data))
2229
    {
2230
      /* Report any relocation */
2231
      put_str_packet ("Text=0;Data=0;Bss=0");
2232
    }
2233
  else if (0 == strncmp ("qP", buf->data, strlen ("qP")))
2234
    {
2235
      /* Deprecated and replaced by 'qThreadExtraInfo' */
2236
      fprintf (stderr, "Warning: RSP qP deprecated: no info returned\n");
2237
      put_str_packet ("");
2238
    }
2239
  else if (0 == strncmp ("qRcmd,", buf->data, strlen ("qRcmd,")))
2240
    {
2241
      /* This is used to interface to commands to do "stuff" */
2242
      rsp_command (buf);
2243
    }
2244
  else if (0 == strncmp ("qSupported", buf->data, strlen ("qSupported")))
2245
    {
2246
      /* Report a list of the features we support. For now we just ignore any
2247
         supplied specific feature queries, but in the future these may be
2248
         supported as well. Note that the packet size allows for 'G' + all the
2249
         registers sent to us, or a reply to 'g' with all the registers and an
2250
         EOS so the buffer is a well formed string. */
2251
 
2252
      char  reply[GDB_BUF_MAX];
2253
 
2254
      sprintf (reply, "PacketSize=%x", GDB_BUF_MAX);
2255
      put_str_packet (reply);
2256
    }
2257
  else if (0 == strncmp ("qSymbol:", buf->data, strlen ("qSymbol:")))
2258
    {
2259
      /* Offer to look up symbols. Nothing we want (for now). TODO. This just
2260
         ignores any replies to symbols we looked up, but we didn't want to
2261
         do that anyway! */
2262
      put_str_packet ("OK");
2263
    }
2264
  else if (0 == strncmp ("qThreadExtraInfo,", buf->data,
2265
                         strlen ("qThreadExtraInfo,")))
2266
    {
2267
      /* Report that we are runnable, but the text must be hex ASCI
2268
         digits. For now do this by steam, reusing the original packet */
2269
      sprintf (buf->data, "%02x%02x%02x%02x%02x%02x%02x%02x%02x",
2270
               'R', 'u', 'n', 'n', 'a', 'b', 'l', 'e', 0);
2271
      buf->len = strlen (buf->data);
2272
      put_packet (buf);
2273
    }
2274
  else if (0 == strncmp ("qXfer:", buf->data, strlen ("qXfer:")))
2275
    {
2276
      /* For now we support no 'qXfer' requests, but these should not be
2277
         expected, since they were not reported by 'qSupported' */
2278
      fprintf (stderr, "Warning: RSP 'qXfer' not supported: ignored\n");
2279
      put_str_packet ("");
2280
    }
2281
  else
2282
    {
2283
      fprintf (stderr, "Unrecognized RSP query: ignored\n");
2284
    }
2285
}       /* rsp_query () */
2286
 
2287
 
2288
/*---------------------------------------------------------------------------*/
2289
/*!Handle a RSP qRcmd request
2290
 
2291
  The actual command follows the "qRcmd," in ASCII encoded to hex
2292
 
2293
   @param[in] buf  The request in full                                       */
2294
/*---------------------------------------------------------------------------*/
2295
static void
2296
rsp_command (struct rsp_buf *buf)
2297
{
2298
  char  cmd[GDB_BUF_MAX];
2299
  unsigned long tmp;
2300
 
2301
  hex2ascii (cmd, &(buf->data[strlen ("qRcmd,")]));
2302
 
2303
  /* Work out which command it is */
2304
  if (0 == strncmp ("readspr ", cmd, strlen ("readspr")))
2305
    {
2306
      unsigned int       regno;
2307
 
2308
      /* Parse and return error if we fail */
2309
      if( 1 != sscanf (cmd, "readspr %4x", &regno))
2310
        {
2311
          fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n",
2312
                   cmd);
2313
          put_str_packet ("E01");
2314
          return;
2315
        }
2316
 
2317
      /* SPR out of range */
2318
      if (regno > MAX_SPRS)
2319
        {
2320
          fprintf (stderr, "Warning: qRcmd readspr %x too large: ignored\n",
2321
                   regno);
2322
          put_str_packet ("E01");
2323
          return;
2324
        }
2325
 
2326
      /* Construct the reply */
2327
      dbg_cpu0_read(regno, &tmp);  // TODO Check return value of all hardware accesses
2328
      sprintf (cmd, "%8lx", tmp);
2329
      ascii2hex (buf->data, cmd);
2330
      buf->len = strlen (buf->data);
2331
      put_packet (buf);
2332
    }
2333
  else if (0 == strncmp ("writespr ", cmd, strlen ("writespr")))
2334
    {
2335
      unsigned int       regno;
2336
      unsigned long int  val;
2337
 
2338
      /* Parse and return error if we fail */
2339
      if( 2 != sscanf (cmd, "writespr %4x %8lx", &regno, &val))
2340
        {
2341
          fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n",
2342
                   cmd);
2343
          put_str_packet ("E01");
2344
          return;
2345
        }
2346
 
2347
      /* SPR out of range */
2348
      if (regno > MAX_SPRS)
2349
        {
2350
          fprintf (stderr, "Warning: qRcmd writespr %x too large: ignored\n",
2351
                   regno);
2352
          put_str_packet ("E01");
2353
          return;
2354
        }
2355
 
2356
      /* Update the SPR and reply "OK" */
2357
      dbg_cpu0_write(regno, val);
2358
      put_str_packet ("OK");
2359
    }
2360
 
2361
}       /* rsp_command () */
2362
 
2363
 
2364
/*---------------------------------------------------------------------------*/
2365
/*!Handle a RSP set request
2366
 
2367
   @param[in] buf  The request                                               */
2368
/*---------------------------------------------------------------------------*/
2369
static void
2370
rsp_set (struct rsp_buf *buf)
2371
{
2372
  if (0 == strncmp ("QPassSignals:", buf->data, strlen ("QPassSignals:")))
2373
    {
2374
      /* Passing signals not supported */
2375
      put_str_packet ("");
2376
    }
2377
  else if ((0 == strncmp ("QTDP",    buf->data, strlen ("QTDP")))   ||
2378
           (0 == strncmp ("QFrame",  buf->data, strlen ("QFrame"))) ||
2379
           (0 == strcmp  ("QTStart", buf->data))                    ||
2380
           (0 == strcmp  ("QTStop",  buf->data))                    ||
2381
           (0 == strcmp  ("QTinit",  buf->data))                    ||
2382
           (0 == strncmp ("QTro",    buf->data, strlen ("QTro"))))
2383
    {
2384
      /* All tracepoint features are not supported. This reply is really only
2385
         needed to 'QTDP', since with that the others should not be
2386
         generated. */
2387
      put_str_packet ("");
2388
    }
2389
  else
2390
    {
2391
      fprintf (stderr, "Unrecognized RSP set request: ignored\n");
2392
    }
2393
}       /* rsp_set () */
2394
 
2395
 
2396
/*---------------------------------------------------------------------------*/
2397
/*!Handle a RSP restart request
2398
 
2399
   For now we just put the program counter back to the one used with the last
2400
   vRun request.                                                             */
2401
/*---------------------------------------------------------------------------*/
2402
static void
2403
rsp_restart ()
2404
{
2405
  set_npc (rsp.start_addr);
2406
 
2407
}       /* rsp_restart () */
2408
 
2409
 
2410
/*---------------------------------------------------------------------------*/
2411
/*!Handle a RSP step request
2412
 
2413
   Parse the command to see if there is an address. Uses the underlying
2414
   generic step function, with EXCEPT_NONE.
2415
 
2416
   @param[in] buf  The full step packet                          */
2417
/*---------------------------------------------------------------------------*/
2418
static void
2419
rsp_step (struct rsp_buf *buf)
2420
{
2421
  unsigned long int  addr;              /* The address to step from, if any */
2422
 
2423
  if(strncmp(buf->data, "s", 2))
2424
    {
2425
      if(1 != sscanf (buf->data, "s%lx", &addr))
2426
        {
2427
          fprintf (stderr,
2428
                   "Warning: RSP step address %s not recognized: ignored\n",
2429
                   buf->data);
2430
        }
2431
      else
2432
        {
2433
          /* Set the address as the value of the next program counter */
2434
          // TODO  Is implementing this really just this simple?
2435
          //set_npc (addr);
2436
        }
2437
    }
2438
 
2439
  rsp_step_generic (EXCEPT_NONE);
2440
 
2441
}       /* rsp_step () */
2442
 
2443
 
2444
/*---------------------------------------------------------------------------*/
2445
/*!Handle a RSP step with signal request
2446
 
2447
   Currently null. Will use the underlying generic step function.
2448
 
2449
   @param[in] buf  The full step with signal packet              */
2450
/*---------------------------------------------------------------------------*/
2451
static void
2452
rsp_step_with_signal (struct rsp_buf *buf)
2453
{
2454
  int val;
2455
  printf ("RSP step with signal '%s' received\n", buf->data);
2456
  val = strtoul(&buf->data[1], NULL, 10);
2457
  rsp_step_generic(val);
2458
}       /* rsp_step_with_signal () */
2459
 
2460
 
2461
/*---------------------------------------------------------------------------*/
2462
/*!Generic processing of a step request
2463
 
2464
   The signal may be EXCEPT_NONE if there is no exception to be
2465
   handled. Currently the exception is ignored.
2466
 
2467
   The single step flag is set in the debug registers and then the processor
2468
   is unstalled.
2469
 
2470
   @param[in] addr    Address from which to step
2471
   @param[in] except  The exception to use (if any)                          */
2472
/*---------------------------------------------------------------------------*/
2473
static void
2474
rsp_step_generic (unsigned long int  except)
2475
{
2476
  unsigned long tmp;
2477
 
2478
  /* Clear Debug Reason Register and watchpoint break generation in Debug Mode
2479
     Register 2 */
2480
  tmp = 0;
2481
  dbg_cpu0_write(SPR_DRR, tmp);  // *** TODO Check return value of all hardware accesses
2482
  dbg_cpu0_read(SPR_DMR2, &tmp);
2483
  if(tmp & SPR_DMR2_WGB) {
2484
    tmp &= ~SPR_DMR2_WGB;
2485
    dbg_cpu0_write(SPR_DMR2, tmp);
2486
  }
2487
 
2488
  /* Set the single step trigger in Debug Mode Register 1 and set traps to be
2489
     handled by the debug unit in the Debug Stop Register */
2490
  if(!rsp.single_step_mode)
2491
    {
2492
      dbg_cpu0_read(SPR_DMR1, &tmp);
2493
      tmp |= SPR_DMR1_ST|SPR_DMR1_BT;
2494
      dbg_cpu0_write(SPR_DMR1, tmp);
2495
      dbg_cpu0_read(SPR_DSR, &tmp);
2496
      if(!(tmp & SPR_DSR_TE)) {
2497
        tmp |= SPR_DSR_TE;
2498
        dbg_cpu0_write(SPR_DSR, tmp);
2499
      }
2500
      rsp.single_step_mode = 1;
2501
    }
2502
 
2503
  /* Unstall the processor */
2504
  set_stall_state (0);
2505
 
2506
  /* Note the GDB client is now waiting for a reply. */
2507
  rsp.client_waiting = 1;
2508
 
2509
}       /* rsp_step_generic () */
2510
 
2511
 
2512
/*---------------------------------------------------------------------------*/
2513
/*!Handle a RSP 'v' packet
2514
 
2515
   These are commands associated with executing the code on the target
2516
 
2517
   @param[in] buf  The request                                               */
2518
/*---------------------------------------------------------------------------*/
2519
static void
2520
rsp_vpkt (struct rsp_buf *buf)
2521
{
2522
  if (0 == strncmp ("vAttach;", buf->data, strlen ("vAttach;")))
2523
    {
2524
      /* Attaching is a null action, since we have no other process. We just
2525
         return a stop packet (using TRAP) to indicate we are stopped. */
2526
      put_str_packet ("S05");
2527
      return;
2528
    }
2529
  else if (0 == strcmp ("vCont?", buf->data))
2530
    {
2531
      /* For now we don't support this. */
2532
      put_str_packet ("");
2533
      return;
2534
    }
2535
  else if (0 == strncmp ("vCont", buf->data, strlen ("vCont")))
2536
    {
2537
      /* This shouldn't happen, because we've reported non-support via vCont?
2538
         above */
2539
      fprintf (stderr, "Warning: RSP vCont not supported: ignored\n" );
2540
      return;
2541
    }
2542
  else if (0 == strncmp ("vFile:", buf->data, strlen ("vFile:")))
2543
    {
2544
      /* For now we don't support this. */
2545
      fprintf (stderr, "Warning: RSP vFile not supported: ignored\n" );
2546
      put_str_packet ("");
2547
      return;
2548
    }
2549
  else if (0 == strncmp ("vFlashErase:", buf->data, strlen ("vFlashErase:")))
2550
    {
2551
      /* For now we don't support this. */
2552
      fprintf (stderr, "Warning: RSP vFlashErase not supported: ignored\n" );
2553
      put_str_packet ("E01");
2554
      return;
2555
    }
2556
  else if (0 == strncmp ("vFlashWrite:", buf->data, strlen ("vFlashWrite:")))
2557
    {
2558
      /* For now we don't support this. */
2559
      fprintf (stderr, "Warning: RSP vFlashWrite not supported: ignored\n" );
2560
      put_str_packet ("E01");
2561
      return;
2562
    }
2563
  else if (0 == strcmp ("vFlashDone", buf->data))
2564
    {
2565
      /* For now we don't support this. */
2566
      fprintf (stderr, "Warning: RSP vFlashDone not supported: ignored\n" );
2567
      put_str_packet ("E01");
2568
      return;
2569
    }
2570
  else if (0 == strncmp ("vRun;", buf->data, strlen ("vRun;")))
2571
    {
2572
      /* We shouldn't be given any args, but check for this */
2573
      if (buf->len > strlen ("vRun;"))
2574
        {
2575
          fprintf (stderr, "Warning: Unexpected arguments to RSP vRun "
2576
                   "command: ignored\n");
2577
        }
2578
 
2579
      /* Restart the current program. However unlike a "R" packet, "vRun"
2580
         should behave as though it has just stopped. We use signal
2581
         5 (TRAP). */
2582
      rsp_restart ();
2583
      put_str_packet ("S05");
2584
    }
2585
  else
2586
    {
2587
      fprintf (stderr, "Warning: Unknown RSP 'v' packet type %s: ignored\n",
2588
               buf->data);
2589
      put_str_packet ("E01");
2590
      return;
2591
    }
2592
}       /* rsp_vpkt () */
2593
 
2594
 
2595
/*---------------------------------------------------------------------------*/
2596
/*!Handle a RSP write memory (binary) request
2597
 
2598
   Syntax is:
2599
 
2600
     X<addr>,<length>:
2601
 
2602
   Followed by the specified number of bytes as raw binary. Response should be
2603
   "OK" if all copied OK, E<nn> if error <nn> has occurred.
2604
 
2605
   The length given is the number of bytes to be written. However the number
2606
   of data bytes may be greater, since '#', '$' and '}' are escaped by
2607
   preceding them by '}' and oring with 0x20.
2608
 
2609
   @param[in] buf  The command received                                      */
2610
/*---------------------------------------------------------------------------*/
2611
static void
2612
rsp_write_mem_bin (struct rsp_buf *buf)
2613
{
2614
  unsigned int  addr;                   /* Where to write the memory */
2615
  int           len;                    /* Number of bytes to write */
2616
  char         *bindat;                 /* Pointer to the binary data */
2617
  int           off;                    /* Offset to start of binary data */
2618
  int           newlen;                 /* Number of bytes in bin data */
2619
  unsigned int  errcode;
2620
 
2621
  if (2 != sscanf (buf->data, "X%x,%x:", &addr, &len))
2622
    {
2623
      fprintf (stderr, "Warning: Failed to recognize RSP write memory "
2624
               "command: %s\n", buf->data);
2625
      put_str_packet ("E01");
2626
      return;
2627
    }
2628
 
2629
  /* Find the start of the data and "unescape" it */
2630
  bindat = memchr ((const void *)buf->data, ':', GDB_BUF_MAX) + 1;
2631
  off    = bindat - buf->data;
2632
  newlen = rsp_unescape (bindat, buf->len - off);
2633
 
2634
  /* Sanity check */
2635
  if (newlen != len)
2636
    {
2637
      int  minlen = len < newlen ? len : newlen;
2638
 
2639
      fprintf (stderr, "Warning: Write of %d bytes requested, but %d bytes "
2640
               "supplied. %d will be written\n", len, newlen, minlen);
2641
      len = minlen;
2642
    }
2643
 
2644
  /* Write the bytes to memory */
2645
  errcode = dbg_wb_write_block8(addr, bindat, len);
2646
 
2647
  // We can't really verify if the memory target address exists or not.
2648
  // Don't write to non-existant memory unless your system wishbone implementation
2649
  // has a hardware bus timeout.
2650
  if(errcode == APP_ERR_NONE) {
2651
    put_str_packet ("OK");
2652
  }
2653
  else {
2654
    fprintf(stderr, "Error writing memory: %s\n", get_err_string(errcode));
2655
    put_str_packet("E01");
2656
  }
2657
 
2658
}       /* rsp_write_mem_bin () */
2659
 
2660
 
2661
/*---------------------------------------------------------------------------*/
2662
/*!Handle a RSP remove breakpoint or matchpoint request
2663
 
2664
   For now only memory breakpoints are implemented, which are implemented by
2665
   substituting a breakpoint at the specified address. The implementation must
2666
   cope with the possibility of duplicate packets.
2667
 
2668
   @todo This doesn't work with icache/immu yet
2669
 
2670
   @param[in] buf  The command received                                      */
2671
/*---------------------------------------------------------------------------*/
2672
static void
2673
rsp_remove_matchpoint (struct rsp_buf *buf)
2674
{
2675
  enum mp_type       type;              /* What sort of matchpoint */
2676
  unsigned long int  addr;              /* Address specified */
2677
  int                len;               /* Matchpoint length (not used) */
2678
  struct mp_entry   *mpe;               /* Info about the replaced instr */
2679
  unsigned long instbuf[1];
2680
 
2681
  /* Break out the instruction */
2682
  if (3 != sscanf (buf->data, "z%1d,%lx,%1d", (int *)&type, &addr, &len))
2683
    {
2684
      fprintf (stderr, "Warning: RSP matchpoint deletion request not "
2685
               "recognized: ignored\n");
2686
      put_str_packet ("E01");
2687
      return;
2688
    }
2689
 
2690
  /* Sanity check that the length is 4 */
2691
  if (4 != len)
2692
    {
2693
      fprintf (stderr, "Warning: RSP matchpoint deletion length %d not "
2694
               "valid: 4 assumed\n", len);
2695
      len = 4;
2696
    }
2697
 
2698
  /* Sort out the type of matchpoint */
2699
  switch (type)
2700
    {
2701
    case BP_MEMORY:
2702
      /* Memory breakpoint - replace the original instruction. */
2703
      mpe = mp_hash_delete (type, addr);
2704
 
2705
      /* If the BP hasn't yet been deleted, put the original instruction
2706
         back. Don't forget to free the hash table entry afterwards. */
2707
      if (NULL != mpe)
2708
        {
2709
          instbuf[0] = mpe->instr;
2710
          dbg_wb_write_block32(addr, instbuf, 1);  // *** TODO Check return value
2711
          free (mpe);
2712
        }
2713
 
2714
      put_str_packet ("OK");
2715
 
2716
      return;
2717
 
2718
    case BP_HARDWARE:
2719
      put_str_packet ("");              /* Not supported */
2720
      return;
2721
 
2722
    case WP_WRITE:
2723
      put_str_packet ("");              /* Not supported */
2724
      return;
2725
 
2726
    case WP_READ:
2727
      put_str_packet ("");              /* Not supported */
2728
      return;
2729
 
2730
    case WP_ACCESS:
2731
      put_str_packet ("");              /* Not supported */
2732
      return;
2733
 
2734
    default:
2735
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
2736
               "recognized: ignored\n", type);
2737
      put_str_packet ("E01");
2738
      return;
2739
 
2740
    }
2741
}       /* rsp_remove_matchpoint () */
2742
 
2743
 
2744
/*---------------------------------------------------------------------------*/
2745
/*!Handle a RSP insert breakpoint or matchpoint request
2746
 
2747
   For now only memory breakpoints are implemented, which are implemented by
2748
   substituting a breakpoint at the specified address. The implementation must
2749
   cope with the possibility of duplicate packets.
2750
 
2751
   @todo This doesn't work with icache/immu yet
2752
 
2753
   @param[in] buf  The command received                                      */
2754
/*---------------------------------------------------------------------------*/
2755
static void
2756
rsp_insert_matchpoint (struct rsp_buf *buf)
2757
{
2758
  enum mp_type       type;              /* What sort of matchpoint */
2759
  unsigned long int  addr;              /* Address specified */
2760
  int                len;               /* Matchpoint length (not used) */
2761
  unsigned long instbuf[1];
2762
 
2763
  /* Break out the instruction */
2764
  if (3 != sscanf (buf->data, "Z%1d,%lx,%1d", (int *)&type, &addr, &len))
2765
    {
2766
      fprintf (stderr, "Warning: RSP matchpoint insertion request not "
2767
               "recognized: ignored\n");
2768
      put_str_packet ("E01");
2769
      return;
2770
    }
2771
 
2772
  /* Sanity check that the length is 4 */
2773
  if (4 != len)
2774
    {
2775
      fprintf (stderr, "Warning: RSP matchpoint insertion length %d not "
2776
               "valid: 4 assumed\n", len);
2777
      len = 4;
2778
    }
2779
 
2780
  /* Sort out the type of matchpoint */
2781
  switch (type)
2782
    {
2783
    case BP_MEMORY:
2784
      /* Memory breakpoint - substitute a TRAP instruction */
2785
      dbg_wb_read_block32(addr, instbuf, 1);  // Get the old instruction.  *** TODO Check return value
2786
      mp_hash_add (type, addr, instbuf[0]);
2787
      instbuf[0] = OR1K_TRAP_INSTR;  // Set the TRAP instruction
2788
      dbg_wb_write_block32(addr, instbuf, 1);  // *** TODO Check return value
2789
      put_str_packet ("OK");
2790
 
2791
      return;
2792
 
2793
    case BP_HARDWARE:
2794
      put_str_packet ("");              /* Not supported */
2795
      return;
2796
 
2797
    case WP_WRITE:
2798
      put_str_packet ("");              /* Not supported */
2799
      return;
2800
 
2801
    case WP_READ:
2802
      put_str_packet ("");              /* Not supported */
2803
      return;
2804
 
2805
    case WP_ACCESS:
2806
      put_str_packet ("");              /* Not supported */
2807
      return;
2808
 
2809
    default:
2810
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
2811
               "recognized: ignored\n", type);
2812
      put_str_packet ("E01");
2813
      return;
2814
 
2815
    }
2816
 
2817
}       /* rsp_insert_matchpoint () */
2818
 
2819
 
2820
// Additions from this point on were added solely to handle hardware,
2821
// and did not come from simulator interface code.
2822
///////////////////////////////////////////////////////////////////////////
2823
//
2824
//  Thread to poll for break on remote processor.
2825
///////////////////////////////////////////////////////////////////////////
2826
 
2827
void *target_handler(void *arg)
2828
{
2829
  unsigned char target_status = 0;
2830
  int retval = APP_ERR_NONE;
2831
  char string[] = "a";  // We send this through the pipe.  Content is unimportant.
2832
  unsigned int local_state = 0;
2833
 
2834
  while(1)
2835
    {
2836
      // Block on condition for GO or DETACH signal
2837
      pthread_mutex_lock(&target_handler_mutex);
2838
      if(target_handler_state == 0)
2839
        {
2840
          pthread_cond_wait(&target_handler_cond, &target_handler_mutex);
2841
        }
2842
 
2843
      // if detach, exit thread
2844
      if(target_handler_state == 2)  // 2 = DETACH
2845
        {
2846
          target_handler_state = 0;
2847
          pthread_mutex_unlock(&target_handler_mutex);
2848
          return arg;
2849
        }
2850
 
2851
      local_state = target_handler_state;
2852
      pthread_mutex_unlock(&target_handler_mutex);
2853
 
2854
 
2855
 
2856
      if(local_state == 1)  // Then start target polling loop, but keep checking for DETACH.  State 1 == GO
2857
        {
2858
          while(1)
2859
            {
2860
              // non-blocking check for DETACH signal
2861
              pthread_mutex_lock(&target_handler_mutex);
2862
              if(target_handler_state == 2)  // state 2 == DETACH
2863
                {
2864
                  pthread_mutex_unlock(&target_handler_mutex);
2865
                  return arg;
2866
                }
2867
              pthread_mutex_unlock(&target_handler_mutex);
2868
 
2869
              // Poll target hardware
2870
              retval = dbg_cpu0_read_ctrl(0, &target_status);
2871
              if(retval != APP_ERR_NONE)
2872
                fprintf(stderr, "ERROR 0x%X while polling target CPU status\n", retval);
2873
              else {
2874
                if(target_status & 0x01)  // Did we get the stall bit?  Bit 0 is STALL bit.
2875
                  {
2876
                    // clear the RUNNING flag
2877
                    pthread_mutex_lock(&rsp_mutex);
2878
                    rsp.target_running = 0;
2879
                    pthread_mutex_unlock(&rsp_mutex);
2880
 
2881
                    // Log the exception so it can be sent back to GDB
2882
                    unsigned long drrval;
2883
                    dbg_cpu0_read(SPR_DRR, &drrval);  // Read the DRR, find out why we stopped
2884
                    rsp_exception(drrval);  // Send it to be translated and stored
2885
 
2886
                    // Send message to GDB handler thread via socket (so it can break out of its poll())
2887
                    int ret = write(pipe_fds[1], string, 1);
2888
                    if(!ret) {
2889
                      fprintf(stderr, "Warning: target monitor write() to pipe returned 0\n");
2890
                    }
2891
                    else if(ret < 0) {
2892
                      perror("Error in target monitor write to pipe: ");
2893
                    }
2894
 
2895
                    // Set our own state back to STOP
2896
                    pthread_mutex_lock(&target_handler_mutex);
2897
                    target_handler_state = 0;
2898
                    pthread_mutex_unlock(&target_handler_mutex);
2899
 
2900
                    break;  // Stop polling, block on the next GO/DETACH
2901
                  }
2902
              }
2903
 
2904
              usleep(250000);  // wait 1/4 second before polling again.
2905
            }
2906
        }
2907
 
2908
      else
2909
        {
2910
          fprintf(stderr, "Unknown command 0x%X received by target handler thread\n", local_state);
2911
          pthread_mutex_lock(&target_handler_mutex);  // Set our own state back to STOP
2912
          target_handler_state = 0;
2913
          pthread_mutex_unlock(&target_handler_mutex);
2914
        }
2915
    }
2916
 
2917
  return arg;
2918
}
2919
 
2920
 
2921
 
2922
 
2923
void set_stall_state(int stall)
2924
{
2925
  int retval = 0;
2926
  unsigned char data = (stall>0)? 1:0;
2927
  unsigned char stalled = 0;
2928
 
2929
  // Set the 'running' variable, if necessary.  Do this before actually starting the CPU.
2930
  // The 'running' variable prevents us from responding to most GDB requests while the
2931
  // CPU is running.
2932
  // We don't ever set the 'running' bit to 0 here.  Instead, we stall the CPU hardware, and let
2933
  // the target handler thread detect the stall, then signal us to send a message up to
2934
  // GDB and clear the 'running' bit.
2935
  if(stall == 0)
2936
    {
2937
      use_cached_npc = 0;
2938
      pthread_mutex_lock(&rsp_mutex);
2939
      rsp.target_running = 1;
2940
      pthread_mutex_unlock(&rsp_mutex);
2941
    }
2942
 
2943
  // Actually start or stop the CPU hardware
2944
  retval = dbg_cpu0_write_ctrl(0, data);  // 0x01 is the STALL command bit
2945
  if(retval != APP_ERR_NONE)
2946
    fprintf(stderr, "ERROR 0x%X sending async STALL to target.\n", retval);
2947
 
2948
  dbg_cpu0_read_ctrl(0, &stalled);
2949
  /*
2950
    if (!(stalled & 0x1)) {
2951
    printf("or1k is not stalled!\n");
2952
    }
2953
 
2954
    fprintf(stderr, "Set STALL to %i\n", data);
2955
  */
2956
 
2957
  // Wake up the target handler thread to poll for a new STALL
2958
  if(stall == 0)
2959
    {
2960
      pthread_mutex_lock(&target_handler_mutex);
2961
      target_handler_state = 1;
2962
      pthread_cond_signal(&target_handler_cond);
2963
      pthread_mutex_unlock(&target_handler_mutex);
2964
    }
2965
 
2966
  return;
2967
}

powered by: WebSVN 2.1.0

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