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

Subversion Repositories or1k_old

[/] [or1k_old/] [trunk/] [or_debug_proxy/] [src/] [gdb.c] - Blame information for rev 1782

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1779 julius
/*$$HEADER*/
2
/******************************************************************************/
3
/*                                                                            */
4
/*                    H E A D E R   I N F O R M A T I O N                     */
5
/*                                                                            */
6
/******************************************************************************/
7
 
8
// Project Name                   : OpenRISC Debug Proxy
9
// File Name                      : gdb.c
10
// Prepared By                    : jb, rmd
11
// Project Start                  : 2008-10-01
12
 
13
/*$$COPYRIGHT NOTICE*/
14
/******************************************************************************/
15
/*                                                                            */
16
/*                      C O P Y R I G H T   N O T I C E                       */
17
/*                                                                            */
18
/******************************************************************************/
19
/*
20
  This library is free software; you can redistribute it and/or
21
  modify it under the terms of the GNU Lesser General Public
22
  License as published by the Free Software Foundation;
23
  version 2.1 of the License, a copy of which is available from
24
  http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt.
25
 
26
  This library is distributed in the hope that it will be useful,
27
  but WITHOUT ANY WARRANTY; without even the implied warranty of
28
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
29
  Lesser General Public License for more details.
30
 
31
  You should have received a copy of the GNU Lesser General Public
32
  License along with this library; if not, write to the Free Software
33
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
34
*/
35
 
36
/*$$DESCRIPTION*/
37
/******************************************************************************/
38
/*                                                                            */
39
/*                           D E S C R I P T I O N                            */
40
/*                                                                            */
41
/******************************************************************************/
42
//
43
// Implements GDB stub for OpenRISC debug proxy.
44
//
45
 
46
 
47
/*$$CHANGE HISTORY*/
48
/******************************************************************************/
49
/*                                                                            */
50
/*                         C H A N G E  H I S T O R Y                         */
51
/*                                                                            */
52
/******************************************************************************/
53
 
54
// Date         Version Description
55
//------------------------------------------------------------------------
56
// 081101               Imported code from "jp" project                 jb
57
// 090219               Adapted code from Jeremy Bennett's RSP server
58
//                      for the or1ksim project.                       rmb
59
// 090304               Finished RSP server code import, added extra
60
//                      functions, adding stability when debugging on
61
//                      a remote target.                                jb
62
 
63
#ifdef CYGWIN_COMPILE
64
 
65
#else
66
// linux includes                  
67
#include <time.h>
68
#endif
69
 
70
#include <stdio.h>
71
#include <ctype.h>
72
#include <string.h>
73
#include <stdlib.h>
74
#include <unistd.h>
75
#include <stdarg.h>
76
 
77
/* Libraries for JTAG proxy server.  */
78
#include <sys/stat.h>
79
#include <sys/types.h>
80
#include <sys/socket.h>
81
#include <netinet/in.h>
82
#include <sys/ioctl.h>
83
#include <sys/select.h>
84
#include <sys/poll.h>
85
#include <fcntl.h>
86
#include <netdb.h>
87
#include <netinet/tcp.h>
88
#include <signal.h>
89
#include <inttypes.h>
90
#include <errno.h>
91
#include <arpa/inet.h>
92
 
93
 
94
/*! Name of the Or1ksim RSP service */
95
#define OR1KSIM_RSP_SERVICE  "or1ksim-rsp"
96
 
97
#include "gdb.h" /* partially copied from gdb/config/or1k */
98
#include "or_debug_proxy.h"
99
 
100
#define MAX_GPRS    (32)
101
 
102
/* Indices of GDB registers that are not GPRs. Must match GDB settings! */
103
#define PPC_REGNUM  (MAX_GPRS + 0)      /*!< Previous PC */
104
#define NPC_REGNUM  (MAX_GPRS + 1)      /*!< Next PC */
105
#define SR_REGNUM   (MAX_GPRS + 2)      /*!< Supervision Register */
106
#define NUM_REGS    (MAX_GPRS + 3)      /*!< Total GDB registers */
107
 
108
/* OR1k CPU registers address */
109
#define NPC_CPU_REG_ADD         0x10                                                    /* Next PC */
110
#define SR_CPU_REG_ADD          0x11                                                    /* Supervision Register */
111
#define PPC_CPU_REG_ADD         0x12                                                    /* Previous PC */
112
#define DMR1_CPU_REG_ADD        ((6 << 11) + 16)        /* Debug Mode Register 1 (DMR1) 0x3010 */
113
#define DMR2_CPU_REG_ADD        ((6 << 11) + 17)        /* Debug Mode Register 2 (DMR2) 0x3011 */
114
#define DSR_CPU_REG_ADD         ((6 << 11) + 20)        /* Debug Stop Register (DSR) 0x3014 */
115
#define DRR_CPU_REG_ADD         ((6 << 11) + 21)        /* Debug Reason Register (DRR) 0x3015 */
116
 
117
/*! Trap instruction for OR32 */
118
#define OR1K_TRAP_INSTR  0x21000001
119
 
120
/*! The maximum number of characters in inbound/outbound buffers.  The largest
121
    packets are the 'G' packet, which must hold the 'G' and all the registers
122
    with two hex digits per byte and the 'g' reply, which must hold all the
123
    registers, and (in our implementation) an end-of-string (0)
124
    character. Adding the EOS allows us to print out the packet as a
125
    string. So at least NUMREGBYTES*2 + 1 (for the 'G' or the EOS) are needed
126
    for register packets */
127
#define GDB_BUF_MAX  ((NUM_REGS) * 8 + 1)
128
 
129
/*! Size of the matchpoint hash table. Largest prime < 2^10 */
130
#define MP_HASH_SIZE  1021
131
 
132
/* Definition of special-purpose registers (SPRs). */
133
#define MAX_SPRS (0x10000)
134
 
135
#define SPR_DMR1_ST                     0x00400000  /* Single-step trace*/
136
#define SPR_DMR2_WGB            0x003ff000  /* Watchpoints generating breakpoint */
137
#define SPR_DSR_TE                              0x00002000  /* Trap exception */
138
 
139
#define WORDSBIGENDIAN_N
140
 
141
/* Definition of OR1K exceptions */
142
#define EXCEPT_NONE     0x0000
143
#define EXCEPT_RESET    0x0100
144
#define EXCEPT_BUSERR   0x0200
145
#define EXCEPT_DPF      0x0300
146
#define EXCEPT_IPF      0x0400
147
#define EXCEPT_TICK     0x0500
148
#define EXCEPT_ALIGN    0x0600
149
#define EXCEPT_ILLEGAL  0x0700
150
#define EXCEPT_INT      0x0800
151
#define EXCEPT_DTLBMISS 0x0900
152
#define EXCEPT_ITLBMISS 0x0a00
153
#define EXCEPT_RANGE    0x0b00
154
#define EXCEPT_SYSCALL  0x0c00
155
#define EXCEPT_FPE      0x0d00
156
#define EXCEPT_TRAP     0x0e00
157
 
158
// Changed to #defines from static const int's due to compile error
159
// DRR (Debug Reason Register) Bits
160
#define SPR_DRR_RSTE  0x00000001  //!< Reset
161
#define SPR_DRR_BUSEE 0x00000002  //!< Bus error
162
#define SPR_DRR_DPFE  0x00000004  //!< Data page fault
163
#define SPR_DRR_IPFE  0x00000008  //!< Insn page fault
164
#define SPR_DRR_TTE   0x00000010  //!< Tick timer
165
#define SPR_DRR_AE    0x00000020  //!< Alignment
166
#define SPR_DRR_IIE   0x00000040  //!< Illegal instruction
167
#define SPR_DRR_IE    0x00000080  //!< Interrupt
168
#define SPR_DRR_DME   0x00000100  //!< DTLB miss
169
#define SPR_DRR_IME   0x00000200  //!< ITLB miss
170
#define SPR_DRR_RE    0x00000400  //!< Range fault
171
#define SPR_DRR_SCE   0x00000800  //!< System call
172
#define SPR_DRR_FPE   0x00001000  //!< Floating point
173
#define SPR_DRR_TE    0x00002000  //!< Trap
174
 
175
 
176
/*! Definition of GDB target signals. Data taken from the GDB 6.8
177
    source. Only those we use defined here. The exact meaning of
178
    signal number is defined by the header `include/gdb/signals.h'
179
    in the GDB source code. For an explanation of what each signal
180
    means, see target_signal_to_string.*/
181
enum target_signal {
182
  TARGET_SIGNAL_NONE =  0,
183
  TARGET_SIGNAL_INT  =  2,
184
  TARGET_SIGNAL_ILL  =  4,
185
  TARGET_SIGNAL_TRAP =  5,
186
  TARGET_SIGNAL_FPE  =  8,
187
  TARGET_SIGNAL_BUS  = 10,
188
  TARGET_SIGNAL_SEGV = 11,
189
  TARGET_SIGNAL_ALRM = 14,
190
  TARGET_SIGNAL_USR2 = 31,
191
  TARGET_SIGNAL_PWR  = 32
192
};
193
 
194
/*! String to map hex digits to chars */
195
static const char hexchars[]="0123456789abcdef";
196
 
197
 
198
//! Is the NPC cached?
199
 
200
//! Setting the NPC flushes the pipeline, so subsequent reads will return
201
//! zero until the processor has refilled the pipeline. This will not be
202
//! happening if the processor is stalled (as it is when GDB had control),
203
//! so we must cache the NPC. As soon as the processor is unstalled, this
204
//! cached value becomes invalid. So we must track the stall state, and if
205
//! appropriate cache the NPC.
206
enum stallStates {
207
  STALLED,
208
  UNSTALLED,
209
  UNKNOWN
210
} stallState;
211
 
212
int      npcIsCached;           //!< Is the NPC cached - should be bool
213
uint32_t  npcCachedValue;               //!< Cached value of the NPC
214
 
215
 
216
 
217
 
218
/************************
219
   JTAG Server Routines
220
************************/
221
int serverIP = 0;
222
int serverPort = 0;
223
int server_fd = 0;
224
int gdb_fd = 0;
225
 
226
static int tcp_level = 0;
227
 
228
/* global to store what chain the debug unit is currently connected to
229
(not the JTAG TAP, but the onchip debug module has selected) */
230
int gdb_chain = -1;
231
 
232
/*! Data structure for RSP buffers. Can't be null terminated, since it may
233
  include zero bytes */
234
struct rsp_buf
235
{
236
  char  data[GDB_BUF_MAX];
237
  int   len;
238
};
239
 
240
/*! Enumeration of different types of matchpoint. These have explicit values
241
    matching the second digit of 'z' and 'Z' packets. */
242
enum mp_type {
243
  BP_MEMORY   = 0,               // software-breakpoint Z0  break 
244
  BP_HARDWARE = 1,              // hardware-breakpoint Z1  hbreak 
245
  WP_WRITE    = 2,              // write-watchpoint    Z2  watch  
246
  WP_READ     = 3,              // read-watchpoint     Z3  rwatch  
247
  WP_ACCESS   = 4                       // access-watchpoint   Z4  awatch
248
};
249
 
250
/*! Data structure for a matchpoint hash table entry */
251
struct mp_entry
252
{
253
  enum mp_type       type;              /*!< Type of matchpoint */
254
  uint32_t  addr;               /*!< Address with the matchpoint */
255
  uint32_t  instr;              /*!< Substituted instruction */
256
  struct mp_entry   *next;              /*!< Next entry with this hash */
257
};
258
 
259
/*! Central data for the RSP connection */
260
static struct
261
{
262
  int                           client_waiting; /*!< Is client waiting a response? */
263
// Not used  int                proto_num;              /*!< Number of the protocol used */
264
  int                client_fd;         /*!< FD for talking to GDB */
265
  int               sigval;                     /*!< GDB signal for any exception */
266
  uint32_t start_addr;  /*!< Start of last run */
267
  struct mp_entry   *mp_hash[MP_HASH_SIZE];     /*!< Matchpoint hash table */
268
} rsp;
269
 
270
/* Forward declarations of static functions */
271
static char *printTime(void);
272
static int gdb_read(void*, int);
273
static int gdb_write(void*, int);
274
static void ProtocolClean(int, int32_t);
275
static void GDBRequest(void);
276
static void rsp_interrupt();
277
static unsigned char rsp_peek();
278
static struct rsp_buf *get_packet (void);
279
static void rsp_init (void);
280
static void set_npc (uint32_t  addr);
281
static uint32_t get_npc();
282
static void rsp_check_for_exception();
283
static int check_for_exception_vector(uint32_t ppc);
284
static void rsp_exception (uint32_t  except);
285
static int get_rsp_char (void);
286
static int hex (int  c);
287
static void rsp_get_client (void);
288
static void rsp_client_request (void);
289
static void rsp_client_close (void);
290
static void client_close (char err);
291
static void     put_str_packet (const char *str);
292
static void rsp_report_exception (void);
293
static void put_packet (struct rsp_buf *p_buf);
294
static void send_rsp_str (unsigned char *data, int len);
295
static void rsp_query (struct rsp_buf *p_buf);
296
static void rsp_vpkt (struct rsp_buf *p_buf);
297
static void     rsp_step (struct rsp_buf *p_buf);
298
static void     rsp_step_with_signal (struct rsp_buf *p_buf);
299
static void     rsp_step_generic (uint32_t  addr, uint32_t  except);
300
static void rsp_continue (struct rsp_buf *p_buf);
301
static void     rsp_continue_with_signal (struct rsp_buf *p_buf);
302
static void     rsp_continue_generic (uint32_t  addr, uint32_t  except);
303
static void rsp_read_all_regs (void);
304
static void rsp_write_all_regs (struct rsp_buf *p_buf);
305
static void rsp_read_mem (struct rsp_buf *p_buf);
306
static void rsp_write_mem (struct rsp_buf *p_buf);
307
static void rsp_write_mem_bin (struct rsp_buf *p_buf);
308
static int rsp_unescape (char *data, int len);
309
static void rsp_read_reg (struct rsp_buf *p_buf);
310
static void rsp_write_reg (struct rsp_buf *p_buf);
311
static void mp_hash_init (void);
312
static void     mp_hash_add (enum mp_type type, uint32_t  addr, uint32_t  instr);
313
static struct mp_entry * mp_hash_lookup (enum mp_type type, uint32_t  addr);
314
static struct mp_entry * mp_hash_delete (enum mp_type type,     uint32_t  addr);
315
static void rsp_remove_matchpoint (struct rsp_buf *p_buf);
316
static void rsp_insert_matchpoint (struct rsp_buf *p_buf);
317
static void rsp_command (struct rsp_buf *p_buf);
318
static void rsp_set (struct rsp_buf *p_buf);
319
static void rsp_restart (void);
320
static void  ascii2hex (char *dest,char *src);
321
static void  hex2ascii (char *dest,     char *src);
322
static uint32_t hex2reg (char *p_buf);
323
static void     reg2hex (uint32_t  val, char *p_buf);
324
static void swap_buf(char* p_buf, int len);
325
static void set_stall_state (int state);
326
static void gdb_ensure_or1k_stalled();
327
static int gdb_set_chain(int chain);
328
static int gdb_write_reg(uint32_t adr, uint32_t data);
329
static int gdb_read_reg(uint32_t adr, uint32_t *data);
330
static int gdb_write_block(uint32_t adr, uint32_t *data, int len);
331
static int gdb_read_block(uint32_t adr, uint32_t *data, int len);
332
 
333
char *printTime(void)
334
{
335
  time_t tid;
336
  struct tm *strtm;
337
  static char timeBuf[20];
338
 
339
  time(&tid);
340
  strtm = localtime(&tid);
341
  sprintf(timeBuf,"[%.02d:%.02d:%.02d] ",strtm->tm_hour,strtm->tm_min,strtm->tm_sec);
342
  return timeBuf;
343
}
344
 
345
/*---------------------------------------------------------------------------*/
346
/*!Initialize the Remote Serial Protocol connection
347
 
348
   Set up the central data structures.                                       */
349
/*---------------------------------------------------------------------------*/
350
void
351
rsp_init (void)
352
{
353
  /* Clear out the central data structure */
354
  rsp.client_waiting =  0;               /* GDB client is not waiting for us */
355
  rsp.client_fd      = -1;              /* i.e. invalid */
356
  rsp.sigval         = 0;                /* No exception */
357
  rsp.start_addr     = EXCEPT_RESET;    /* Default restart point */
358
 
359
  /* Set up the matchpoint hash table */
360
  mp_hash_init ();
361
 
362
  /* RSP always starts stalled as though we have just reset the processor. */
363
  rsp_exception (EXCEPT_TRAP);
364
 
365
  /* Setup the NPC caching variables */
366
  stallState = STALLED;
367
  // Force a caching of the NPC
368
  npcIsCached = 0;
369
  get_npc();
370
 
371
}       /* rsp_init () */
372
 
373
/*---------------------------------------------------------------------------*/
374
/*!Look for action on RSP
375
 
376
   This function is called when the processor has stalled, which, except for
377
   initialization, must be due to an interrupt.
378
 
379
   If we have no RSP client, we get one. We can make no progress until the
380
   client is available.
381
 
382
   Then if the cause is an exception following a step or continue command, and
383
   the exception not been notified to GDB, a packet reporting the cause of the
384
   exception is sent.
385
 
386
   The next client request is then processed.                                */
387
/*---------------------------------------------------------------------------*/
388
void
389
handle_rsp (void)
390
{
391
  uint32_t              temp_uint32;
392
 
393
  rsp_init();
394
 
395
  while (1){
396
          /* If we have no RSP client, wait until we get one. */
397
          while (-1 == rsp.client_fd)
398
          {
399
            rsp_get_client ();
400
            rsp.client_waiting = 0;              /* No longer waiting */
401
          }
402
 
403
          /* If we have an unacknowledged exception tell the GDB client. If this
404
             exception was a trap due to a memory breakpoint, then adjust the NPC. */
405
          if (rsp.client_waiting)
406
          {
407
 
408
            // Check for exception
409
            rsp_check_for_exception();
410
 
411
            if(DEBUG_GDB)
412
              {
413
                gdb_read_reg(PPC_CPU_REG_ADD, &temp_uint32);
414
                printf("PPC is currently 0x%08x\n", temp_uint32);
415
              }
416
 
417
            // Get the PPC to check if we've hit a software breakpoint
418
            gdb_read_reg(PPC_CPU_REG_ADD, &temp_uint32);
419
 
420
            if ((TARGET_SIGNAL_TRAP == rsp.sigval) && (NULL != mp_hash_lookup (BP_MEMORY, temp_uint32)))
421
              {
422
                if (stallState != STALLED)
423
                  // This is a quick fix for a strange situation seen in some of the simulators where
424
                  // the sw bp would be detected, but the stalled state variable wasn't updated correctly
425
                  // indicating that last time it checked, it wasn't set but the processor has now hit the
426
                  // breakpoint. So run rsp_check_for_exception() to bring everything up to date.
427
                  rsp_check_for_exception();
428
 
429
                if(DEBUG_GDB) printf("Software breakpoint hit at 0x%08x. Rolling back NPC to this instruction\n", temp_uint32);
430
 
431
                set_npc (temp_uint32);
432
 
433
                rsp_report_exception();
434
                rsp.client_waiting = 0;          /* No longer waiting */
435
              }
436
            else if(stallState == STALLED) {
437
              // If we're here, the thing has stalled, but not because of a breakpoint we set
438
              // report back the exception
439
 
440
              rsp_report_exception();
441
              rsp.client_waiting = 0;            /* No longer waiting */
442
 
443
            }
444
            // Check if PPC is at a known exception vector
445
            // (Illegal inst., unaligned access, etc.)
446
            else if (check_for_exception_vector(temp_uint32))
447
              {
448
                rsp_report_exception();
449
                rsp.client_waiting = 0;
450
              }
451
 
452
            if (rsp.client_waiting)
453
              sleep(1);
454
 
455
          }
456
 
457
 
458
 
459
          // See if there's any incoming data from the client by peeking at the socket
460
          if (rsp_peek() > 0)
461
            {
462
              if (rsp_peek() == 0x03 && (stallState != STALLED)) // ETX, end of text control char
463
                {
464
                  // Got an interrupt command from GDB, this function should
465
                  // pull the packet off the socket and stall the processor.
466
                  // and then send a stop reply packet with signal TARGET_SIGNAL_NONE
467
                  rsp_interrupt();
468
                  rsp.client_waiting = 0;
469
                }
470
              else if (rsp.client_waiting == 0)
471
                {
472
                  // Default handling of data from the client:
473
                  /* Get a RSP client request */
474
                  rsp_client_request ();
475
                }
476
            } /* end if (rsp_peek() > 0) */
477
        }
478
}       /* handle_rsp () */
479
 
480
 
481
/*
482
  Check if processor is stalled - if it is, read the DRR
483
  and return the target signal code
484
*/
485
static void rsp_check_for_exception()
486
{
487
 
488
  unsigned char stalled;
489
  uint32_t drr;
490
  err = dbg_cpu0_read_ctrl(0, &stalled);                          /* check if we're stalled */
491
 
492
  if (!(stalled & 0x01))
493
    {
494
      // Processor not stalled. Just return;
495
      return;
496
    }
497
 
498
  if (DEBUG_GDB) printf("rsp_check_for_exception() detected processor was stalled\nChecking DRR\n");
499
 
500
  // We're stalled
501
  stallState = STALLED;
502
  npcIsCached = 0;
503
 
504
  gdb_set_chain(SC_RISC_DEBUG);
505
 
506
  // Now read the DRR (Debug Reason Register)
507
  gdb_read_reg(DRR_CPU_REG_ADD, &drr);
508
 
509
  if (DEBUG_GDB) printf("DRR: 0x%08x\n", drr);
510
 
511
  switch ((int)(drr&0xffffffff))
512
    {
513
    case SPR_DRR_RSTE:  rsp.sigval = TARGET_SIGNAL_PWR;  break;
514
    case SPR_DRR_BUSEE: rsp.sigval = TARGET_SIGNAL_BUS;  break;
515
    case SPR_DRR_DPFE:  rsp.sigval = TARGET_SIGNAL_SEGV; break;
516
    case SPR_DRR_IPFE:  rsp.sigval = TARGET_SIGNAL_SEGV; break;
517
    case SPR_DRR_TTE:   rsp.sigval = TARGET_SIGNAL_ALRM; break;
518
    case SPR_DRR_AE:    rsp.sigval = TARGET_SIGNAL_BUS;  break;
519
    case SPR_DRR_IIE:   rsp.sigval = TARGET_SIGNAL_ILL;  break;
520
    case SPR_DRR_IE:    rsp.sigval = TARGET_SIGNAL_INT;  break;
521
    case SPR_DRR_DME:   rsp.sigval = TARGET_SIGNAL_SEGV; break;
522
    case SPR_DRR_IME:   rsp.sigval = TARGET_SIGNAL_SEGV; break;
523
    case SPR_DRR_RE:    rsp.sigval = TARGET_SIGNAL_FPE;  break;
524
    case SPR_DRR_SCE:   rsp.sigval = TARGET_SIGNAL_USR2; break;
525
    case SPR_DRR_FPE:   rsp.sigval = TARGET_SIGNAL_FPE;  break;
526
    case SPR_DRR_TE:    rsp.sigval = TARGET_SIGNAL_TRAP; break;
527
 
528
    default:
529
      // This must be the case of single step (which does not set DRR)
530
      rsp.sigval = TARGET_SIGNAL_TRAP; break;
531
    }
532
 
533
  if (DEBUG_GDB) printf("rsp.sigval: 0x%x\n", rsp.sigval);
534
 
535
  return;
536
}
537
 
538
/*---------------------------------------------------------------------------*/
539
/*!Check if PPC is in an exception vector that halts program flow
540
 
541
Compare the provided PPC with known exception vectors that are fatal
542
to a program's execution. Call rsp_exception(ppc) to set the appropriate
543
sigval and return.
544
 
545
@param[in] ppc  Value of current PPC, as read from debug unit
546
@return: 1 if we set a sigval and should return control to GDB, else 0       */
547
/*---------------------------------------------------------------------------*/
548
static int
549
check_for_exception_vector(uint32_t ppc)
550
{
551
  switch(ppc)
552
    {
553
      // The following should return sigvals to GDB for processing
554
    case EXCEPT_BUSERR:
555
    case EXCEPT_ALIGN:
556
    case EXCEPT_ILLEGAL:
557
    case EXCEPT_TRAP:     if(DEBUG_GDB)
558
                            printf("PPC at exception address\n");
559
                          rsp_exception(ppc);
560
                          return 1;
561
 
562
    default:
563
      return 0;
564
    }
565
  return 1;
566
}
567
 
568
/*---------------------------------------------------------------------------*/
569
/*!Note an exception for future processing
570
 
571
   The simulator has encountered an exception. Record it here, so that a
572
   future call to handle_exception will report it back to the client. The
573
   signal is supplied in Or1ksim form and recorded in GDB form.
574
 
575
   We flag up a warning if an exception is already pending, and ignore the
576
   earlier exception.
577
 
578
   @param[in] except  The exception (Or1ksim form)                           */
579
/*---------------------------------------------------------------------------*/
580
void
581
rsp_exception (uint32_t  except)
582
{
583
  int  sigval;                  /* GDB signal equivalent to exception */
584
 
585
  switch (except)
586
    {
587
    case EXCEPT_RESET:    sigval = TARGET_SIGNAL_PWR;  break;
588
    case EXCEPT_BUSERR:   sigval = TARGET_SIGNAL_BUS;  break;
589
    case EXCEPT_DPF:      sigval = TARGET_SIGNAL_SEGV; break;
590
    case EXCEPT_IPF:      sigval = TARGET_SIGNAL_SEGV; break;
591
    case EXCEPT_TICK:     sigval = TARGET_SIGNAL_ALRM; break;
592
    case EXCEPT_ALIGN:    sigval = TARGET_SIGNAL_BUS;  break;
593
    case EXCEPT_ILLEGAL:  sigval = TARGET_SIGNAL_ILL;  break;
594
    case EXCEPT_INT:      sigval = TARGET_SIGNAL_INT;  break;
595
    case EXCEPT_DTLBMISS: sigval = TARGET_SIGNAL_SEGV; break;
596
    case EXCEPT_ITLBMISS: sigval = TARGET_SIGNAL_SEGV; break;
597
    case EXCEPT_RANGE:    sigval = TARGET_SIGNAL_FPE;  break;
598
    case EXCEPT_SYSCALL:  sigval = TARGET_SIGNAL_USR2; break;
599
    case EXCEPT_FPE:      sigval = TARGET_SIGNAL_FPE;  break;
600
    case EXCEPT_TRAP:     sigval = TARGET_SIGNAL_TRAP; break;
601
 
602
    default:
603
      fprintf (stderr, "Warning: Unknown RSP exception %u: Ignored\n", except);
604
      return;
605
    }
606
 
607
  if ((0 != rsp.sigval) && (sigval != rsp.sigval))
608
    {
609
      fprintf (stderr, "Warning: RSP signal %d received while signal "
610
               "%d pending: Pending exception replaced\n", sigval, rsp.sigval);
611
    }
612
 
613
  rsp.sigval         = sigval;          /* Save the signal value */
614
 
615
}       /* rsp_exception () */
616
 
617
 
618
/*---------------------------------------------------------------------------*/
619
/*!Get a new client connection.
620
 
621
   Blocks until the client connection is available.
622
 
623
   A lot of this code is copied from remote_open in gdbserver remote-utils.c.
624
 
625
   This involves setting up a socket to listen on a socket for attempted
626
   connections from a single GDB instance (we couldn't be talking to multiple
627
   GDBs at once!).
628
 
629
   The service is specified either as a port number in the Or1ksim configuration
630
   (parameter rsp_port in section debug, default 51000) or as a service name
631
   in the constant OR1KSIM_RSP_SERVICE.
632
 
633
   The protocol used for communication is specified in OR1KSIM_RSP_PROTOCOL. */
634
/*---------------------------------------------------------------------------*/
635
static void
636
rsp_get_client (void)
637
{
638
  int                 tmp_fd;           /* Temporary descriptor for socket */
639
  int                 optval;           /* Socket options */
640
  struct sockaddr_in  sock_addr;        /* Socket address */
641
  socklen_t           len;              /* Size of the socket address */
642
 
643
  /* 0 is used as the RSP port number to indicate that we should use the
644
     service name instead. */
645
  if (0 == serverPort)
646
  {
647
    struct servent *service = getservbyname (OR1KSIM_RSP_SERVICE, "tcp");
648
    if (NULL == service)
649
      {
650
        fprintf (stderr, "Warning: RSP unable to find service \"%s\": %s\n",
651
                 OR1KSIM_RSP_SERVICE, strerror (errno));
652
        return;
653
      }
654
    serverPort = ntohs (service->s_port);
655
  }
656
 
657
  /* Open a socket on which we'll listen for clients */
658
  tmp_fd = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
659
  if (tmp_fd < 0)
660
    {
661
      fprintf (stderr, "ERROR: Cannot open RSP socket\n");
662
      exit (0);
663
    }
664
 
665
  /* Allow rapid reuse of the port on this socket */
666
  optval = 1;
667
  setsockopt (tmp_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval,
668
              sizeof (optval));
669
 
670
  /* Bind the port to the socket */
671
  sock_addr.sin_family      = PF_INET;
672
  sock_addr.sin_port        = htons (serverPort);
673
  sock_addr.sin_addr.s_addr = INADDR_ANY;
674
  if (bind (tmp_fd, (struct sockaddr *) &sock_addr, sizeof (sock_addr)))
675
    {
676
      fprintf (stderr, "ERROR: Cannot bind to RSP socket\n");
677
      exit (0);
678
    }
679
 
680
  /* Listen for (at most one) client */
681
  if (0 != listen (tmp_fd, 1))
682
    {
683
      fprintf (stderr, "ERROR: Cannot listen on RSP socket\n");
684
      exit (0);
685
    }
686
 
687
  printf("Waiting for gdb connection on localhost:%d\n", serverPort);
688
  fflush (stdout);
689
 
690
  printf("Press CTRL+c to exit.\n");
691
  fflush (stdout);
692
 
693
  /* Accept a client which connects */
694
  len = sizeof (sock_addr);
695
  rsp.client_fd = accept (tmp_fd, (struct sockaddr *)&sock_addr, &len);
696
 
697
  if (-1 == rsp.client_fd)
698
  {
699
    fprintf (stderr, "Warning: Failed to accept RSP client\n");
700
    return;
701
  }
702
 
703
  /* Enable TCP keep alive process */
704
  optval = 1;
705
  setsockopt (rsp.client_fd, SOL_SOCKET, SO_KEEPALIVE, (char *)&optval,
706
              sizeof (optval));
707
 
708
  /* Set socket to be non-blocking */
709
 
710
  /* We do this because when we're given a continue, or step
711
     instruction,command we set the processor stall off, then instnatly check
712
     if it's stopped. If it hasn't then we drop through and wait for input
713
     from GDB. Obviously this will cause problems when it will stop after we
714
     do the check. So now, rsp_peek() has been implemented to simply check if
715
     there's an incoming command from GDB (only interested in interrupt
716
     commands), otherwise it returns back to and poll the processor's PPC and
717
     stall bit. It can only do this if the socket is non-blocking.
718
 
719
     At first test, simply adding this line appeared to give no problems with
720
     the existing code. No "simulation" of blocking behaviour on the
721
     non-blocking socket was required (in the event that a read/write throws
722
     back a EWOULDBLOCK error, as was looked to be the case in the previous
723
     GDB handling code) -- Julius
724
  */
725
  if (ioctl(rsp.client_fd, FIONBIO, (char *)&optval) > 0 )
726
    {
727
      perror("ioctl() failed");
728
      close(rsp.client_fd);
729
      close(tmp_fd);
730
      exit(0);
731
    }
732
 
733
  /* Don't delay small packets, for better interactive response (disable
734
     Nagel's algorithm) */
735
  optval = 1;
736
  setsockopt (rsp.client_fd, IPPROTO_TCP, TCP_NODELAY, (char *)&optval,
737
              sizeof (optval));
738
 
739
  /* Socket is no longer needed */
740
  close (tmp_fd);                       /* No longer need this */
741
  signal (SIGPIPE, SIG_IGN);            /* So we don't exit if client dies */
742
 
743
  printf ("Remote debugging from host %s\n", inet_ntoa (sock_addr.sin_addr));
744
}       /* rsp_get_client () */
745
 
746
 
747
/*---------------------------------------------------------------------------*/
748
/*!Deal with a request from the GDB client session
749
 
750
   In general, apart from the simplest requests, this function replies on
751
   other functions to implement the functionality.                           */
752
/*---------------------------------------------------------------------------*/
753
static void rsp_client_request (void)
754
{
755
  struct rsp_buf *p_buf = get_packet ();        /* Message sent to us */
756
 
757
  // Null packet means we hit EOF or the link was closed for some other
758
  // reason. Close the client and return
759
  if (NULL == p_buf)
760
    {
761
      rsp_client_close ();
762
      return;
763
    }
764
 
765
  if (DEBUG_GDB){
766
    printf("%s-----------------------------------------------------\n", printTime());
767
    printf ("Packet received %s: %d chars\n", p_buf->data, p_buf->len );
768
    fflush (stdout);
769
  }
770
 
771
  switch (p_buf->data[0])
772
    {
773
    case '!':
774
      /* Request for extended remote mode */
775
      put_str_packet ("OK"); // OK = supports and has enabled extended mode.
776
      return;
777
 
778
    case '?':
779
      /* Return last signal ID */
780
      rsp_report_exception();
781
      return;
782
 
783
    case 'A':
784
      /* Initialization of argv not supported */
785
      fprintf (stderr, "Warning: RSP 'A' packet not supported: ignored\n");
786
      put_str_packet ("E01");
787
      return;
788
 
789
    case 'b':
790
      /* Setting baud rate is deprecated */
791
      fprintf (stderr, "Warning: RSP 'b' packet is deprecated and not "
792
               "supported: ignored\n");
793
      return;
794
 
795
    case 'B':
796
      /* Breakpoints should be set using Z packets */
797
      fprintf (stderr, "Warning: RSP 'B' packet is deprecated (use 'Z'/'z' "
798
               "packets instead): ignored\n");
799
      return;
800
 
801
    case 'c':
802
      /* Continue */
803
      rsp_continue (p_buf);
804
      return;
805
 
806
    case 'C':
807
      /* Continue with signal */
808
      rsp_continue_with_signal (p_buf);
809
      return;
810
 
811
    case 'd':
812
      /* Disable debug using a general query */
813
      fprintf (stderr, "Warning: RSP 'd' packet is deprecated (define a 'Q' "
814
               "packet instead: ignored\n");
815
      return;
816
 
817
    case 'D':
818
      /* Detach GDB. Do this by closing the client. The rules say that
819
         execution should continue. TODO. Is this really then intended
820
         meaning? Or does it just mean that only vAttach will be recognized
821
         after this? */
822
      put_str_packet ("OK");
823
      rsp_client_close ();
824
      set_stall_state (0);
825
      return;
826
 
827
    case 'F':
828
      /* File I/O is not currently supported */
829
      fprintf (stderr, "Warning: RSP file I/O not currently supported: 'F' "
830
               "packet ignored\n");
831
      return;
832
 
833
    case 'g':
834
      rsp_read_all_regs ();
835
      return;
836
 
837
    case 'G':
838
      rsp_write_all_regs (p_buf);
839
      return;
840
 
841
    case 'H':
842
      /* Set the thread number of subsequent operations. For now ignore
843
            silently and just reply "OK" */
844
      put_str_packet ("OK");
845
      return;
846
 
847
    case 'i':
848
      /* Single instruction step */
849
      fprintf (stderr, "Warning: RSP cycle stepping not supported: target "
850
               "stopped immediately\n");
851
      rsp.client_waiting = 1;                   /* Stop reply will be sent */
852
      return;
853
 
854
    case 'I':
855
      /* Single instruction step with signal */
856
      fprintf (stderr, "Warning: RSP cycle stepping not supported: target "
857
               "stopped immediately\n");
858
      rsp.client_waiting = 1;                   /* Stop reply will be sent */
859
      return;
860
 
861
    case 'k':
862
      /* Kill request. Do nothing for now. */
863
      return;
864
 
865
    case 'm':
866
      /* Read memory (symbolic) */
867
      rsp_read_mem (p_buf);
868
      return;
869
 
870
    case 'M':
871
      /* Write memory (symbolic) */
872
      rsp_write_mem (p_buf);
873
      return;
874
 
875
    case 'p':
876
      /* Read a register */
877
      rsp_read_reg (p_buf);
878
      return;
879
 
880
    case 'P':
881
      /* Write a register */
882
      rsp_write_reg (p_buf);
883
      return;
884
 
885
    case 'q':
886
      /* Any one of a number of query packets */
887
      rsp_query (p_buf);
888
      return;
889
 
890
    case 'Q':
891
      /* Any one of a number of set packets */
892
      rsp_set (p_buf);
893
      return;
894
 
895
    case 'r':
896
      /* Reset the system. Deprecated (use 'R' instead) */
897
      fprintf (stderr, "Warning: RSP 'r' packet is deprecated (use 'R' "
898
               "packet instead): ignored\n");
899
      return;
900
 
901
    case 'R':
902
      /* Restart the program being debugged. */
903
      rsp_restart ();
904
      return;
905
 
906
    case 's':
907
      /* Single step (one high level instruction). This could be hard without
908
                        DWARF2 info */
909
      rsp_step (p_buf);
910
      return;
911
 
912
    case 'S':
913
      /* Single step (one high level instruction) with signal. This could be
914
                        hard without DWARF2 info */
915
      rsp_step_with_signal (p_buf);
916
      return;
917
 
918
    case 't':
919
      /* Search. This is not well defined in the manual and for now we don't
920
                        support it. No response is defined. */
921
      fprintf (stderr, "Warning: RSP 't' packet not supported: ignored\n");
922
      return;
923
 
924
    case 'T':
925
      /* Is the thread alive. We are bare metal, so don't have a thread
926
                        context. The answer is always "OK". */
927
      put_str_packet ("OK");
928
      return;
929
 
930
    case 'v':
931
      /* Any one of a number of packets to control execution */
932
      rsp_vpkt (p_buf);
933
      return;
934
 
935
    case 'X':
936
      /* Write memory (binary) */
937
      rsp_write_mem_bin (p_buf);
938
      return;
939
 
940
    case 'z':
941
      /* Remove a breakpoint/watchpoint. */
942
      rsp_remove_matchpoint (p_buf);
943
      return;
944
 
945
    case 'Z':
946
      /* Insert a breakpoint/watchpoint. */
947
      rsp_insert_matchpoint (p_buf);
948
      return;
949
 
950
    default:
951
      /* Unknown commands are ignored */
952
      fprintf (stderr, "Warning: Unknown RSP request %s\n", p_buf->data);
953
      return;
954
    }
955
}       /* rsp_client_request () */
956
 
957
 
958
/*---------------------------------------------------------------------------*/
959
/*!Close the connection to the client if it is open                          */
960
/*---------------------------------------------------------------------------*/
961
static void
962
rsp_client_close (void)
963
{
964
  if (-1 != rsp.client_fd)
965
    {
966
      close (rsp.client_fd);
967
      rsp.client_fd = -1;
968
    }
969
}       /* rsp_client_close () */
970
 
971
 
972
/*---------------------------------------------------------------------------*/
973
/*!Send a packet to the GDB client
974
 
975
   Modeled on the stub version supplied with GDB. Put out the data preceded by
976
   a '$', followed by a '#' and a one byte checksum. '$', '#', '*' and '}' are
977
   escaped by preceding them with '}' and then XORing the character with
978
   0x20.
979
 
980
   @param[in] p_buf  The data to send                                          */
981
/*---------------------------------------------------------------------------*/
982
static void
983
put_packet (struct rsp_buf *p_buf)
984
{
985
  unsigned char  data[GDB_BUF_MAX * 2];
986
  int   len;
987
  int   ch;                             /* Ack char */
988
 
989
  /* Construct $<packet info>#<checksum>. Repeat until the GDB client
990
     acknowledges satisfactory receipt. */
991
  do
992
  {
993
    unsigned char checksum = 0;  /* Computed checksum */
994
    int           count    = 0;  /* Index into the buffer */
995
 
996
    if (DEBUG_GDB_DUMP_DATA){
997
      printf ("Putting %s\n\n", p_buf->data);
998
      fflush (stdout);
999
    }
1000
 
1001
    len = 0;
1002
    data[len++] =  '$';                 /* Start char */
1003
 
1004
    /* Body of the packet */
1005
    for (count = 0; count < p_buf->len; count++)
1006
                {
1007
                  unsigned char  ch = p_buf->data[count];
1008
 
1009
                  /* Check for escaped chars */
1010
                  if (('$' == ch) || ('#' == ch) || ('*' == ch) || ('}' == ch))
1011
                    {
1012
                      ch       ^= 0x20;
1013
                      checksum += (unsigned char)'}';
1014
                                        data[len++] =  '}';
1015
                    }
1016
 
1017
                  checksum += ch;
1018
                        data[len++] =  ch;
1019
                }
1020
 
1021
                data[len++] =  '#';                     /* End char */
1022
 
1023
    /* Computed checksum */
1024
    data[len++] =       (hexchars[checksum >> 4]);
1025
                data[len++] =   (hexchars[checksum % 16]);
1026
 
1027
                send_rsp_str ((unsigned char *) &data, len);
1028
 
1029
    /* Check for ack of connection failure */
1030
    ch = get_rsp_char ();
1031
    if (0 > ch)
1032
                {
1033
                  return;                       /* Fail the put silently. */
1034
                }
1035
  }
1036
  while ('+' != ch);
1037
 
1038
}       /* put_packet () */
1039
 
1040
 
1041
/*---------------------------------------------------------------------------*/
1042
/*!Convenience to put a constant string packet
1043
 
1044
   param[in] str  The text of the packet                                     */
1045
/*---------------------------------------------------------------------------*/
1046
static void
1047
put_str_packet (const char *str)
1048
{
1049
  struct rsp_buf  buffer;
1050
  int    len = strlen (str);
1051
 
1052
  /* Construct the packet to send, so long as string is not too big,
1053
     otherwise truncate. Add EOS at the end for convenient debug printout */
1054
 
1055
  if (len >= GDB_BUF_MAX)
1056
    {
1057
      fprintf (stderr, "Warning: String %s too large for RSP packet: "
1058
               "truncated\n", str);
1059
      len = GDB_BUF_MAX - 1;
1060
    }
1061
 
1062
  strncpy (buffer.data, str, len);
1063
  buffer.data[len] = 0;
1064
  buffer.len       = len;
1065
 
1066
  put_packet (&buffer);
1067
 
1068
}       /* put_str_packet () */
1069
 
1070
 
1071
/*---------------------------------------------------------------------------*/
1072
/*!Get a packet from the GDB client
1073
 
1074
   Modeled on the stub version supplied with GDB. The data is in a static
1075
   buffer. The data should be copied elsewhere if it is to be preserved across
1076
   a subsequent call to get_packet().
1077
 
1078
   Unlike the reference implementation, we don't deal with sequence
1079
   numbers. GDB has never used them, and this implementation is only intended
1080
   for use with GDB 6.8 or later. Sequence numbers were removed from the RSP
1081
   standard at GDB 5.0.
1082
 
1083
   @return  A pointer to the static buffer containing the data                */
1084
/*---------------------------------------------------------------------------*/
1085
static struct rsp_buf *
1086
get_packet (void)
1087
{
1088
  static struct rsp_buf  buf;           /* Survives the return */
1089
 
1090
  /* Keep getting packets, until one is found with a valid checksum */
1091
  while (1)
1092
        {
1093
                unsigned char checksum;         /* The checksum we have computed */
1094
                int           count;                    /* Index into the buffer */
1095
                int                     ch;                                     /* Current character */
1096
 
1097
    /* Wait around for the start character ('$'). Ignore all other
1098
          characters */
1099
    ch = get_rsp_char ();
1100
 
1101
    while (ch != '$')
1102
                {
1103
                  if (-1 == ch)
1104
                    {
1105
                      return  NULL;             /* Connection failed */
1106
                    }
1107
 
1108
                  ch = get_rsp_char ();
1109
 
1110
                  // Potentially handle an interrupt character (0x03) here                
1111
                }
1112
 
1113
    /* Read until a '#' or end of buffer is found */
1114
    checksum =  0;
1115
    count    =  0;
1116
    while (count < GDB_BUF_MAX - 1)
1117
                {
1118
                  ch = get_rsp_char ();
1119
 
1120
                  if(rsp.client_waiting && DEBUG_GDB)
1121
                    {
1122
                      printf("%x\n",ch);
1123
                    }
1124
 
1125
 
1126
                  /* Check for connection failure */
1127
                  if (0 > ch)
1128
                    {
1129
                      return  NULL;
1130
                    }
1131
 
1132
                  /* If we hit a start of line char begin all over again */
1133
                  if ('$' == ch)
1134
                    {
1135
                      checksum =  0;
1136
                      count    =  0;
1137
 
1138
                      continue;
1139
                    }
1140
 
1141
                  /* Break out if we get the end of line char */
1142
                  if ('#' == ch)
1143
                    {
1144
                      break;
1145
                    }
1146
 
1147
                  /* Update the checksum and add the char to the buffer */
1148
 
1149
                  checksum        = checksum + (unsigned char)ch;
1150
                  buf.data[count] = (char)ch;
1151
                  count           = count + 1;
1152
                }
1153
 
1154
    /* Mark the end of the buffer with EOS - it's convenient for non-binary
1155
          data to be valid strings. */
1156
    buf.data[count] = 0;
1157
    buf.len         = count;
1158
 
1159
    /* If we have a valid end of packet char, validate the checksum */
1160
    if ('#' == ch)
1161
                {
1162
                  unsigned char  xmitcsum;      /* The checksum in the packet */
1163
 
1164
                  ch = get_rsp_char ();
1165
                  if (0 > ch)
1166
                    {
1167
                      return  NULL;             /* Connection failed */
1168
                    }
1169
                  xmitcsum = hex (ch) << 4;
1170
 
1171
                  ch = get_rsp_char ();
1172
                  if (0 > ch)
1173
                    {
1174
                      return  NULL;             /* Connection failed */
1175
                    }
1176
 
1177
                  xmitcsum += hex (ch);
1178
 
1179
                  /* If the checksums don't match print a warning, and put the
1180
                     negative ack back to the client. Otherwise put a positive ack. */
1181
                  if (checksum != xmitcsum)
1182
                    {
1183
                      fprintf (stderr, "Warning: Bad RSP checksum: Computed "
1184
                               "0x%02x, received 0x%02x\n", checksum, xmitcsum);
1185
 
1186
                                        ch = '-';
1187
                      send_rsp_str ((unsigned char *) &ch, 1);  /* Failed checksum */
1188
                    }
1189
                  else
1190
                    {
1191
                                        ch = '+';
1192
                      send_rsp_str ((unsigned char *) &ch, 1);  /* successful transfer */
1193
                      break;
1194
                    }
1195
                }
1196
    else
1197
                {
1198
                  fprintf (stderr, "Warning: RSP packet overran buffer\n");
1199
                }
1200
  }
1201
  return &buf;                          /* Success */
1202
}       /* get_packet () */
1203
 
1204
 
1205
/*---------------------------------------------------------------------------*/
1206
/*!Put a single character out onto the client socket
1207
 
1208
   This should only be called if the client is open, but we check for safety.
1209
 
1210
   @param[in] c  The character to put out                                    */
1211
/*---------------------------------------------------------------------------*/
1212
static void
1213
send_rsp_str (unsigned char *data, int len)
1214
{
1215
  if (-1 == rsp.client_fd)
1216
    {
1217
      fprintf (stderr, "Warning: Attempt to write '%s' to unopened RSP "
1218
               "client: Ignored\n", data);
1219
      return;
1220
    }
1221
 
1222
  /* Write until successful (we retry after interrupts) or catastrophic
1223
     failure. */
1224
  while (1)
1225
    {
1226
      switch (write (rsp.client_fd, data, len))
1227
                        {
1228
                        case -1:
1229
                          /* Error: only allow interrupts or would block */
1230
                          if ((EAGAIN != errno) && (EINTR != errno))
1231
                            {
1232
                              fprintf (stderr, "Warning: Failed to write to RSP client: "
1233
                                       "Closing client connection: %s\n",
1234
                                       strerror (errno));
1235
                              rsp_client_close ();
1236
                              return;
1237
                            }
1238
 
1239
                          break;
1240
 
1241
                        case 0:
1242
                          break;                /* Nothing written! Try again */
1243
 
1244
                        default:
1245
                          return;               /* Success, we can return */
1246
                        }
1247
    }
1248
}       /* send_rsp_str () */
1249
 
1250
 
1251
/*---------------------------------------------------------------------------*/
1252
/*!Get a single character from the client socket
1253
 
1254
   This should only be called if the client is open, but we check for safety.
1255
 
1256
   @return  The character read, or -1 on failure                             */
1257
/*---------------------------------------------------------------------------*/
1258
static int
1259
get_rsp_char ()
1260
{
1261
  if (-1 == rsp.client_fd)
1262
    {
1263
      fprintf (stderr, "Warning: Attempt to read from unopened RSP "
1264
               "client: Ignored\n");
1265
      return  -1;
1266
    }
1267
 
1268
  /* Non-blocking read until successful (we retry after interrupts) or
1269
     catastrophic failure. */
1270
  while (1)
1271
    {
1272
      unsigned char  c;
1273
 
1274
      switch (read (rsp.client_fd, &c, sizeof (c)))
1275
        {
1276
        case -1:
1277
          /* Error: only allow interrupts */
1278
          if ((EAGAIN != errno) && (EINTR != errno))
1279
            {
1280
              fprintf (stderr, "Warning: Failed to read from RSP client: "
1281
                       "Closing client connection: %s\n",
1282
                       strerror (errno));
1283
              rsp_client_close ();
1284
              return  -1;
1285
            }
1286
 
1287
          break;
1288
 
1289
        case 0:
1290
          // EOF
1291
          rsp_client_close ();
1292
          return  -1;
1293
 
1294
        default:
1295
          return  c & 0xff; /* Success, we can return (no sign extend!) */
1296
        }
1297
    }
1298
}       /* get_rsp_char () */
1299
 
1300
/*---------------------------------------------------------------------------*/
1301
/* !Peek at data coming into server from GDB
1302
 
1303
   Useful for polling for ETX (0x3) chars being sent when GDB wants to
1304
   interrupt
1305
 
1306
   @return the char we peeked, 0 otherwise                                   */
1307
/*---------------------------------------------------------------------------*/
1308
static unsigned char
1309
rsp_peek()
1310
{
1311
  /*
1312
  if (-1 == rsp.client_fd)
1313
    {
1314
      fprintf (stderr, "Warning: Attempt to read from unopened RSP "
1315
               "client: Ignored\n");
1316
      return  -1;
1317
    }
1318
  */
1319
  unsigned char  c;
1320
  int n;
1321
  // Using recv here instead of read becuase we can pass the MSG_PEEK
1322
  // flag, which lets us look at what's on the socket, without actually
1323
  // taking it off
1324
 
1325
  //if (DEBUG_GDB) 
1326
  //  printf("peeking at GDB socket...\n");
1327
  n = recv (rsp.client_fd, &c, sizeof (c), MSG_PEEK);
1328
  //if (DEBUG_GDB) 
1329
  //  printf("peeked, got n=%d, c=0x%x\n",n, c);
1330
 
1331
  if (n == 0)
1332
    return 0;
1333
  else
1334
    return c;
1335
 
1336
  //  return c;
1337
}
1338
 
1339
/*---------------------------------------------------------------------------*/
1340
/*!Handle an interrupt from GDB
1341
 
1342
 Detect an interrupt from GDB and stall the processor                        */
1343
/*---------------------------------------------------------------------------*/
1344
static void
1345
rsp_interrupt()
1346
{
1347
  unsigned char  c;
1348
 
1349
  if (read (rsp.client_fd, &c, sizeof (c)) <= 0)
1350
    {
1351
      // Had issues, just return
1352
      return;
1353
    }
1354
 
1355
  // Ensure this is a ETX control char (0x3), currently, we only call this
1356
  // function when we've peeked and seen it, otherwise, ignore, return and pray
1357
  // things go back to normal...
1358
  if (c != 0x03)
1359
    {
1360
      printf("Warning: Interrupt character expected but not found on socket.\n");
1361
      return;
1362
    }
1363
 
1364
  // Otherwise, it's an interrupt packet, stall the processor, and upon return
1365
  // to the main handle_rsp() loop, it will inform GDB.
1366
 
1367
  if (DEBUG_GDB) printf("Interrupt received from GDB. Stalling processor.\n");
1368
 
1369
  set_stall_state (1);
1370
 
1371
  // Send a stop reply response, manually set rsp.sigval to TARGET_SIGNAL_NONE
1372
  rsp.sigval = TARGET_SIGNAL_NONE;
1373
  rsp_report_exception();
1374
  rsp.client_waiting = 0;                /* No longer waiting */
1375
 
1376
  return;
1377
 
1378
}
1379
 
1380
 
1381
/*---------------------------------------------------------------------------*/
1382
/*!"Unescape" RSP binary data
1383
 
1384
   '#', '$' and '}' are escaped by preceding them by '}' and oring with 0x20.
1385
 
1386
   This function reverses that, modifying the data in place.
1387
 
1388
   @param[in] data  The array of bytes to convert
1389
   @para[in]  len   The number of bytes to be converted
1390
 
1391
   @return  The number of bytes AFTER conversion                             */
1392
/*---------------------------------------------------------------------------*/
1393
static int
1394
rsp_unescape (char *data,
1395
              int   len)
1396
{
1397
  int  from_off = 0;             /* Offset to source char */
1398
  int  to_off   = 0;             /* Offset to dest char */
1399
 
1400
  while (from_off < len)
1401
    {
1402
      /* Is it escaped */
1403
      if ( '}' == data[from_off])
1404
                        {
1405
                          from_off++;
1406
                          data[to_off] = data[from_off] ^ 0x20;
1407
                        }
1408
                  else
1409
                        {
1410
                          data[to_off] = data[from_off];
1411
                        }
1412
 
1413
      from_off++;
1414
      to_off++;
1415
    }
1416
 
1417
  return  to_off;
1418
 
1419
}       /* rsp_unescape () */
1420
 
1421
 
1422
/*---------------------------------------------------------------------------*/
1423
/*!Initialize the matchpoint hash table
1424
 
1425
   This is an open hash table, so this function clears all the links to
1426
   NULL.                                                                     */
1427
/*---------------------------------------------------------------------------*/
1428
static void
1429
mp_hash_init (void)
1430
{
1431
  int  i;
1432
 
1433
  for (i = 0; i < MP_HASH_SIZE; i++)
1434
    {
1435
      rsp.mp_hash[i] = NULL;
1436
    }
1437
}       /* mp_hash_init () */
1438
 
1439
 
1440
/*---------------------------------------------------------------------------*/
1441
/*!Add an entry to the matchpoint hash table
1442
 
1443
   Add the entry if it wasn't already there. If it was there do nothing. The
1444
   match just be on type and addr. The instr need not match, since if this is
1445
   a duplicate insertion (perhaps due to a lost packet) they will be
1446
   different.
1447
 
1448
   @param[in] type   The type of matchpoint
1449
   @param[in] addr   The address of the matchpoint
1450
   @para[in]  instr  The instruction to associate with the address           */
1451
/*---------------------------------------------------------------------------*/
1452
static void
1453
mp_hash_add (enum mp_type type,
1454
             uint32_t  addr,
1455
             uint32_t  instr)
1456
{
1457
  int              hv    = addr % MP_HASH_SIZE;
1458
  struct mp_entry *curr;
1459
 
1460
  /* See if we already have the entry */
1461
  for(curr = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1462
  {
1463
    if ((type == curr->type) && (addr == curr->addr))
1464
                {
1465
                  return;               /* We already have the entry */
1466
                }
1467
  }
1468
 
1469
  /* Insert the new entry at the head of the chain */
1470
  curr = (struct mp_entry*) malloc (sizeof (*curr));
1471
 
1472
  curr->type  = type;
1473
  curr->addr  = addr;
1474
  curr->instr = instr;
1475
  curr->next  = rsp.mp_hash[hv];
1476
 
1477
  rsp.mp_hash[hv] = curr;
1478
 
1479
}       /* mp_hash_add () */
1480
 
1481
 
1482
/*---------------------------------------------------------------------------*/
1483
/*!Look up an entry in the matchpoint hash table
1484
 
1485
   The match must be on type AND addr.
1486
 
1487
   @param[in] type   The type of matchpoint
1488
   @param[in] addr   The address of the matchpoint
1489
 
1490
   @return  The entry deleted, or NULL if the entry was not found            */
1491
/*---------------------------------------------------------------------------*/
1492
static struct mp_entry * mp_hash_lookup (enum mp_type type,     uint32_t addr)
1493
{
1494
  int    hv = addr % MP_HASH_SIZE;
1495
  struct mp_entry *curr;
1496
 
1497
  /* Search */
1498
  for (curr = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1499
  {
1500
    if ((type == curr->type) && (addr == curr->addr))
1501
                {
1502
                  return  curr;         /* The entry found */
1503
                }
1504
  }
1505
 
1506
  /* Not found */
1507
  return  NULL;
1508
 
1509
}       /* mp_hash_lookup () */
1510
 
1511
 
1512
/*---------------------------------------------------------------------------*/
1513
/*!Delete an entry from the matchpoint hash table
1514
 
1515
   If it is there the entry is deleted from the hash table. If it is not
1516
   there, no action is taken. The match must be on type AND addr.
1517
 
1518
   The usual fun and games tracking the previous entry, so we can delete
1519
   things.
1520
 
1521
   @note  The deletion DOES NOT free the memory associated with the entry,
1522
          since that is returned. The caller should free the memory when they
1523
          have used the information.
1524
 
1525
   @param[in] type   The type of matchpoint
1526
   @param[in] addr   The address of the matchpoint
1527
 
1528
   @return  The entry deleted, or NULL if the entry was not found            */
1529
/*---------------------------------------------------------------------------*/
1530
static struct mp_entry *
1531
mp_hash_delete (enum mp_type       type,
1532
                uint32_t  addr)
1533
{
1534
  int              hv   = addr % MP_HASH_SIZE;
1535
  struct mp_entry *prev = NULL;
1536
  struct mp_entry *curr;
1537
 
1538
  /* Search */
1539
  for (curr  = rsp.mp_hash[hv]; NULL != curr; curr = curr->next)
1540
    {
1541
      if ((type == curr->type) && (addr == curr->addr))
1542
        {
1543
          /* Found - delete. Method depends on whether we are the head of
1544
             chain. */
1545
          if (NULL == prev)
1546
            {
1547
              rsp.mp_hash[hv] = curr->next;
1548
            }
1549
          else
1550
            {
1551
              prev->next = curr->next;
1552
            }
1553
 
1554
          return  curr;         /* The entry deleted */
1555
        }
1556
 
1557
      prev = curr;
1558
    }
1559
 
1560
  /* Not found */
1561
  return  NULL;
1562
 
1563
}       /* mp_hash_delete () */
1564
 
1565
 
1566
/*---------------------------------------------------------------------------*/
1567
/*!Utility to give the value of a hex char
1568
 
1569
   @param[in] ch  A character representing a hexadecimal digit. Done as -1,
1570
                  for consistency with other character routines, which can use
1571
                  -1 as EOF.
1572
 
1573
   @return  The value of the hex character, or -1 if the character is
1574
            invalid.                                                         */
1575
/*---------------------------------------------------------------------------*/
1576
static int hex (int  c)
1577
{
1578
  return  ((c >= 'a') && (c <= 'f')) ? c - 'a' + 10 :
1579
          ((c >= '0') && (c <= '9')) ? c - '0' :
1580
          ((c >= 'A') && (c <= 'F')) ? c - 'A' + 10 : -1;
1581
 
1582
}       /* hex () */
1583
 
1584
 
1585
/*---------------------------------------------------------------------------*/
1586
/*!Convert a register to a hex digit string
1587
 
1588
   The supplied 32-bit value is converted to an 8 digit hex string according
1589
   the target endianism. It is null terminated for convenient printing.
1590
 
1591
   @param[in]  val  The value to convert
1592
   @param[out] p_buf  The buffer for the text string                           */
1593
/*---------------------------------------------------------------------------*/
1594
static void
1595
reg2hex (uint32_t  val, char *p_buf)
1596
{
1597
  int  n;                       /* Counter for digits */
1598
        int  nyb_shift;
1599
 
1600
  for (n = 0; n < 8; n++)
1601
    {
1602
#ifdef WORDSBIGENDIAN
1603
      if(n%2==0){
1604
        nyb_shift = n * 4 + 4;
1605
                        }
1606
                        else{
1607
                                nyb_shift = n * 4 - 4;
1608
                        }
1609
#else
1610
      nyb_shift = 28 - (n * 4);
1611
#endif
1612
      p_buf[n] = hexchars[(val >> nyb_shift) & 0xf];
1613
    }
1614
 
1615
  p_buf[8] = 0;                  /* Useful to terminate as string */
1616
 
1617
}       /* reg2hex () */
1618
 
1619
 
1620
/*---------------------------------------------------------------------------*/
1621
/*!Convert a hex digit string to a register value
1622
 
1623
   The supplied 8 digit hex string is converted to a 32-bit value according
1624
   the target endianism
1625
 
1626
   @param[in] p_buf  The buffer with the hex string
1627
 
1628
   @return  The value to convert                                             */
1629
/*---------------------------------------------------------------------------*/
1630
static uint32_t
1631
hex2reg (char *p_buf)
1632
{
1633
  int                n;         /* Counter for digits */
1634
  uint32_t  val = 0;     /* The result */
1635
 
1636
  for (n = 0; n < 8; n++)
1637
    {
1638
#ifdef WORDSBIGENDIAN
1639
      int  nyb_shift = n * 4;
1640
#else
1641
      int  nyb_shift = 28 - (n * 4);
1642
#endif
1643
      val |= hex (p_buf[n]) << nyb_shift;
1644
    }
1645
 
1646
  return val;
1647
 
1648
}       /* hex2reg () */
1649
 
1650
 
1651
/*---------------------------------------------------------------------------*/
1652
/*!Convert an ASCII character string to pairs of hex digits
1653
 
1654
   Both source and destination are null terminated.
1655
 
1656
   @param[out] dest  Buffer to store the hex digit pairs (null terminated)
1657
   @param[in]  src   The ASCII string (null terminated)                      */
1658
/*---------------------------------------------------------------------------*/
1659
static void  ascii2hex (char *dest,
1660
                        char *src)
1661
{
1662
  int  i;
1663
 
1664
  /* Step through converting the source string */
1665
  for (i = 0; src[i] != '\0'; i++)
1666
    {
1667
      char  ch = src[i];
1668
 
1669
      dest[i * 2]     = hexchars[ch >> 4 & 0xf];
1670
      dest[i * 2 + 1] = hexchars[ch      & 0xf];
1671
    }
1672
 
1673
  dest[i * 2] = '\0';
1674
 
1675
}       /* ascii2hex () */
1676
 
1677
 
1678
/*---------------------------------------------------------------------------*/
1679
/*!Convert pairs of hex digits to an ASCII character string
1680
 
1681
   Both source and destination are null terminated.
1682
 
1683
   @param[out] dest  The ASCII string (null terminated)
1684
   @param[in]  src   Buffer holding the hex digit pairs (null terminated)    */
1685
/*---------------------------------------------------------------------------*/
1686
static void  hex2ascii (char *dest,
1687
                        char *src)
1688
{
1689
  int  i;
1690
 
1691
  /* Step through convering the source hex digit pairs */
1692
  for (i = 0; src[i * 2] != '\0' && src[i * 2 + 1] != '\0'; i++)
1693
    {
1694
      dest[i] = ((hex (src[i * 2]) & 0xf) << 4) | (hex (src[i * 2 + 1]) & 0xf);
1695
    }
1696
 
1697
  dest[i] = '\0';
1698
 
1699
}       /* hex2ascii () */
1700
 
1701
 
1702
/*---------------------------------------------------------------------------*/
1703
/*!Set the program counter
1704
 
1705
   This sets the value in the NPC SPR. Not completely trivial, since this is
1706
   actually cached in cpu_state.pc. Any reset of the NPC also involves
1707
   clearing the delay state and setting the pcnext global.
1708
 
1709
   Only actually do this if the requested address is different to the current
1710
   NPC (avoids clearing the delay pipe).
1711
 
1712
   @param[in] addr  The address to use                                       */
1713
/*---------------------------------------------------------------------------*/
1714
static void
1715
set_npc (uint32_t  addr)
1716
{
1717
 
1718
  // First set the chain 
1719
  gdb_set_chain(SC_RISC_DEBUG); /* 1 RISC Debug Interface chain */
1720
 
1721
 
1722
  if (addr != get_npc())
1723
  {
1724
 
1725
    gdb_write_reg(NPC_CPU_REG_ADD, addr);
1726
 
1727
    if (STALLED == stallState)
1728
      {
1729
        if (DEBUG_GDB) printf("set_npc(): New NPC value (0x%08x) written and locally cached \n", addr);
1730
        npcCachedValue = addr;
1731
        npcIsCached = 1;
1732
      }
1733
    else
1734
      {
1735
        if (DEBUG_GDB) printf("set_npc(): New NPC value (0x%08x) written \n", addr);
1736
        npcIsCached = 0;
1737
      }
1738
 
1739
 
1740
  }
1741
  else
1742
    return;
1743
 
1744
 
1745
}       /* set_npc () */
1746
 
1747
 
1748
//! Read the value of the Next Program Counter (a SPR)
1749
 
1750
//! Setting the NPC flushes the pipeline, so subsequent reads will return
1751
//! zero until the processor has refilled the pipeline. This will not be
1752
//! happening if the processor is stalled (as it is when GDB had control),
1753
//! so we must cache the NPC. As soon as the processor is unstalled, this
1754
//! cached value becomes invalid.
1755
 
1756
//! If we are stalled and the value has been cached, use it. If we are stalled
1757
//! and the value has not been cached, cache it (for efficiency) and use
1758
//! it. Otherwise read the corresponding SPR.
1759
 
1760
//! @return  The value of the NPC
1761
static uint32_t get_npc ()
1762
{
1763
  uint32_t current_npc;
1764
 
1765
  if (STALLED == stallState)
1766
    {
1767
      if (npcIsCached == 0)
1768
        {
1769
          err = gdb_set_chain(SC_RISC_DEBUG);
1770
          err = gdb_read_reg(NPC_CPU_REG_ADD, &npcCachedValue);
1771
          if(err > 0){
1772
            printf("Error %d reading NPC\n", err);
1773
            rsp_client_close ();
1774
            return 0;
1775
          }
1776
          if (DEBUG_GDB) printf("get_npc(): caching newly read NPC value (0x%08x)\n",npcCachedValue);
1777
 
1778
 
1779
          npcIsCached    = 1;
1780
        }
1781
      else
1782
        if (DEBUG_GDB) printf("get_npc(): reading cached NPC value (0x%08x)\n",npcCachedValue);
1783
 
1784
      return  npcCachedValue;
1785
    }
1786
  else
1787
    {
1788
      err = gdb_read_reg(NPC_CPU_REG_ADD, &current_npc);
1789
      if(err > 0){
1790
        printf("Error %d reading NPC\n", err);
1791
        rsp_client_close ();
1792
        return 0;
1793
      }
1794
      return current_npc;
1795
 
1796
    }
1797
}       // get_npc ()
1798
 
1799
 
1800
 
1801
/*---------------------------------------------------------------------------*/
1802
/*!Send a packet acknowledging an exception has occurred
1803
 
1804
   This is only called if there is a client FD to talk to                    */
1805
/*---------------------------------------------------------------------------*/
1806
static void
1807
rsp_report_exception (void)
1808
{
1809
  struct rsp_buf  buffer;
1810
 
1811
  /* Construct a signal received packet */
1812
  buffer.data[0] = 'S';
1813
  buffer.data[1] = hexchars[rsp.sigval >> 4];
1814
  buffer.data[2] = hexchars[rsp.sigval % 16];
1815
  buffer.data[3] = 0;
1816
  buffer.len     = strlen (buffer.data);
1817
 
1818
  put_packet (&buffer);
1819
 
1820
}       /* rsp_report_exception () */
1821
 
1822
 
1823
/*---------------------------------------------------------------------------*/
1824
/*!Handle a RSP continue request
1825
 
1826
   Parse the command to see if there is an address. Uses the underlying
1827
   generic continue function, with EXCEPT_NONE.
1828
 
1829
   @param[in] p_buf  The full continue packet                                  */
1830
/*---------------------------------------------------------------------------*/
1831
static void
1832
rsp_continue (struct rsp_buf *p_buf)
1833
{
1834
  uint32_t  addr;               /* Address to continue from, if any */
1835
 
1836
  // First set the chain 
1837
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
1838
 
1839
  // Make sure the processor is stalled
1840
  gdb_ensure_or1k_stalled();
1841
 
1842
  if(err > 0){
1843
    printf("Error %d to set RISC Debug Interface chain in the CONTINUE command 'c'\n", err);
1844
    rsp_client_close ();
1845
    return;
1846
  }
1847
 
1848
  if (0 == strcmp ("c", p_buf->data))
1849
  {
1850
    // Arc Sim Code -->   addr = cpu_state.pc;  /* Default uses current NPC */
1851
    /* ---------- NPC ---------- */
1852
    addr = get_npc();
1853
  }
1854
  else if (1 != sscanf (p_buf->data, "c%x", &addr))
1855
  {
1856
    fprintf (stderr,
1857
       "Warning: RSP continue address %s not recognized: ignored\n",
1858
       p_buf->data);
1859
 
1860
    // Arc Sim Code -->   addr = cpu_state.pc;  /* Default uses current NPC */
1861
    /* ---------- NPC ---------- */
1862
    addr = get_npc();
1863
  }
1864
 
1865
  if (DEBUG_GDB) printf("rsp_continue() --> Read NPC = 0x%08x\n", addr);
1866
 
1867
  rsp_continue_generic (addr, EXCEPT_NONE);
1868
 
1869
}       /* rsp_continue () */
1870
 
1871
 
1872
/*---------------------------------------------------------------------------*/
1873
/*!Handle a RSP continue with signal request
1874
 
1875
   Currently null. Will use the underlying generic continue function.
1876
 
1877
   @param[in] p_buf  The full continue with signal packet                      */
1878
/*---------------------------------------------------------------------------*/
1879
static void
1880
rsp_continue_with_signal (struct rsp_buf *p_buf)
1881
{
1882
  printf ("RSP continue with signal '%s' received\n", p_buf->data);
1883
 
1884
}       /* rsp_continue_with_signal () */
1885
 
1886
 
1887
/*---------------------------------------------------------------------------*/
1888
/*!Generic processing of a continue request
1889
 
1890
   The signal may be EXCEPT_NONE if there is no exception to be
1891
   handled. Currently the exception is ignored.
1892
 
1893
   The single step flag is cleared in the debug registers and then the
1894
   processor is unstalled.
1895
 
1896
   @param[in] addr    Address from which to step
1897
   @param[in] except  The exception to use (if any)                          */
1898
/*---------------------------------------------------------------------------*/
1899
static void
1900
rsp_continue_generic (uint32_t  addr,
1901
                      uint32_t  except)
1902
{
1903
  uint32_t              temp_uint32;
1904
 
1905
  /* Set the address as the value of the next program counter */
1906
  set_npc (addr);
1907
 
1908
  /* Clear Debug Reason Register (DRR) 0x3015 */
1909
  // Arc sim --> cpu_state.sprs[SPR_DRR]   = 0;
1910
  if(gdb_write_reg(DRR_CPU_REG_ADD, 0)) printf("Error write to DRR register\n");
1911
 
1912
  /* Clear watchpoint break generation in Debug Mode Register 2 (DMR2) 0x3011 */
1913
  // Arc sim --> cpu_state.sprs[SPR_DMR2] &= ~SPR_DMR2_WGB;
1914
  if(gdb_read_reg(DMR2_CPU_REG_ADD, &temp_uint32)) printf("Error read from DMR2 register\n");
1915
  temp_uint32 &= ~SPR_DMR2_WGB;
1916
  if(gdb_write_reg(DMR2_CPU_REG_ADD, temp_uint32)) printf("Error write to DMR2 register\n");
1917
 
1918
  /* Clear the single step trigger in Debug Mode Register 1 (DMR1) Register 0x3010 */
1919
  // Arc sim --> cpu_state.sprs[SPR_DMR1] &= ~SPR_DMR1_ST;
1920
  if(gdb_read_reg(DMR1_CPU_REG_ADD, &temp_uint32)) printf("Error read from DMR1 register\n");
1921
  temp_uint32 &= ~SPR_DMR1_ST;
1922
  if(gdb_write_reg(DMR1_CPU_REG_ADD, temp_uint32)) printf("Error write to DMR1 register\n");
1923
 
1924
  /* Set traps to be handled by the debug unit in the Debug Stop Register (DSR) Register 0x3014 */
1925
  // Arc sim --> cpu_state.sprs[SPR_DSR]  |= SPR_DSR_TE;
1926
  if(gdb_read_reg(DSR_CPU_REG_ADD, &temp_uint32)) printf("Error read from DSR register\n");
1927
  temp_uint32 |= SPR_DSR_TE;
1928
  if(gdb_write_reg(DSR_CPU_REG_ADD, temp_uint32)) printf("Error write to DSR register\n");
1929
 
1930
  /* Unstall the processor */
1931
  set_stall_state (0);
1932
 
1933
  /* Note the GDB client is now waiting for a reply. */
1934
  rsp.client_waiting = 1;
1935
 
1936
}       /* rsp_continue_generic () */
1937
 
1938
 
1939
/*---------------------------------------------------------------------------*/
1940
/*!Handle a RSP read all registers request
1941
 
1942
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PPC
1943
   (i.e. SPR PPC), NPC (i.e. SPR NPC) and SR (i.e. SPR SR). Each register is
1944
   returned as a sequence of bytes in target endian order.
1945
 
1946
   Each byte is packed as a pair of hex digits.                              */
1947
/*---------------------------------------------------------------------------*/
1948
static void
1949
rsp_read_all_regs (void)
1950
{
1951
  struct rsp_buf  buffer;                       /* Buffer for the reply */
1952
  int             r;                            /* Register index */
1953
  uint32_t   temp_uint32;
1954
 
1955
  // Make sure the processor is stalled
1956
  gdb_ensure_or1k_stalled();
1957
 
1958
  // First set the chain 
1959
  gdb_set_chain(SC_RISC_DEBUG); /* 1 RISC Debug Interface chain */
1960
 
1961
 
1962
  // Read all GPRs
1963
  for (r = 0; r < MAX_GPRS; r++){
1964
 
1965
    err = gdb_read_reg(0x400 + r, &temp_uint32);
1966
    if(err > 0){
1967
      if (DEBUG_GDB) printf("Error %d in gdb_read_reg at reg. %d\n", err, r);
1968
      put_str_packet ("E01");
1969
      return;
1970
    }
1971
    reg2hex (temp_uint32, &(buffer.data[r * 8]));
1972
 
1973
    if (DEBUG_GDB_DUMP_DATA){
1974
      switch(r % 4)
1975
        {
1976
        case 0:
1977
          printf("gpr%02d   0x%08x  ", r, temp_uint32);
1978
          break;
1979
        case 1:
1980
        case 2:
1981
          printf("0x%08x  ", temp_uint32);
1982
          break;
1983
        case 3:
1984
          printf("0x%08x\n", temp_uint32);
1985
          break;
1986
        default:
1987
          break;
1988
        }
1989
    }
1990
 
1991
  }
1992
  /* ---------- PPC ---------- */
1993
  err = gdb_read_reg(PPC_CPU_REG_ADD, &temp_uint32);
1994
  if(err > 0){
1995
        if (DEBUG_GDB) printf("Error %d in gdb_read_reg read --> PPC\n", err);
1996
        put_str_packet ("E01");
1997
        return;
1998
  }
1999
  reg2hex (temp_uint32, &(buffer.data[PPC_REGNUM * 8]));
2000
  if (DEBUG_GDB_DUMP_DATA)      printf("PPC     0x%08x\n", temp_uint32);
2001
  /* ---------- NPC ---------- */
2002
  temp_uint32 = get_npc();
2003
  /*
2004
  err = gdb_read_reg(NPC_CPU_REG_ADD, &temp_uint32);
2005
  if(err > 0){
2006
        if (DEBUG_GDB) printf("Error %d in gdb_read_reg read --> NPC\n", err);
2007
        put_str_packet ("E01");
2008
        return;
2009
  }
2010
  */
2011
  reg2hex (temp_uint32, &(buffer.data[NPC_REGNUM * 8]));
2012
  if (DEBUG_GDB_DUMP_DATA)      printf("NPC     0x%08x\n", temp_uint32);
2013
  /* ---------- SR ---------- */
2014
  err = gdb_read_reg(SR_CPU_REG_ADD, &temp_uint32);
2015
  if(err > 0){
2016
        if (DEBUG_GDB) printf("Error %d in gdb_read_reg read --> SP\n", err);
2017
        put_str_packet ("E01");
2018
        return;
2019
  }
2020
  reg2hex (temp_uint32, &(buffer.data[SR_REGNUM * 8]));
2021
        if (DEBUG_GDB_DUMP_DATA)        printf("SR      0x%08x\n", temp_uint32);
2022
 
2023
  /* Finalize the packet and send it */
2024
  buffer.data[NUM_REGS * 8] = 0;
2025
  buffer.len                = NUM_REGS * 8;
2026
 
2027
  put_packet (&buffer);
2028
        return;
2029
}       /* rsp_read_all_regs () */
2030
 
2031
 
2032
/*---------------------------------------------------------------------------*/
2033
/*!Handle a RSP write all registers request
2034
 
2035
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PPC
2036
   (i.e. SPR PPC), NPC (i.e. SPR NPC) and SR (i.e. SPR SR). Each register is
2037
   supplied as a sequence of bytes in target endian order.
2038
 
2039
   Each byte is packed as a pair of hex digits.
2040
 
2041
   @todo There is no error checking at present. Non-hex chars will generate a
2042
         warning message, but there is no other check that the right amount
2043
         of data is present. The result is always "OK".
2044
 
2045
   @param[in] p_buf  The original packet request.                              */
2046
/*---------------------------------------------------------------------------*/
2047
static void
2048
rsp_write_all_regs (struct rsp_buf *p_buf)
2049
{
2050
  uint32_t  regnum;                             /* Register index */
2051
  // char          valstr[9];           /* Allow for EOS on the string */
2052
 
2053
  // /* Check for valid data */
2054
  // if (0 != (strcmp ("G", p_buf->data)) && (GDB_BUF_MAX != strlen(p_buf->data)))
2055
  // {
2056
  //   fprintf (stderr, "Warning: Failed to recognize RSP write register "
2057
  //      "command: %s\n", p_buf->data);
2058
  //   // put_str_packet ("E01");
2059
  //   return;
2060
  // }
2061
 
2062
  // Make sure the processor is stalled
2063
  gdb_ensure_or1k_stalled();
2064
 
2065
  // First set the chain 
2066
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
2067
  if(err > 0){
2068
        if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
2069
    put_str_packet ("E01");
2070
        return;
2071
        }
2072
 
2073
  /* ---------- GPRS ---------- */
2074
  for (regnum = 0; regnum < MAX_GPRS; regnum++)
2075
  {
2076
    err = gdb_write_reg(0x400 + regnum, hex2reg (&p_buf->data[regnum * 8 + 1]));
2077
          if(err > 0){
2078
                if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> GPRS\n", err);
2079
            put_str_packet ("E01");
2080
                return;
2081
          }
2082
  }
2083
 
2084
  /* ---------- PPC ---------- */
2085
  err = gdb_write_reg(PPC_CPU_REG_ADD, hex2reg (&p_buf->data[PPC_REGNUM * 8 + 1]));
2086
  if(err > 0){
2087
        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> PPC\n", err);
2088
    put_str_packet ("E01");
2089
        return;
2090
  }
2091
  /* ---------- SR ---------- */
2092
  err = gdb_write_reg(SR_CPU_REG_ADD, hex2reg (&p_buf->data[SR_REGNUM * 8 + 1]));
2093
  if(err > 0){
2094
        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> SR\n", err);
2095
    put_str_packet ("E01");
2096
        return;
2097
  }
2098
  /* ---------- NPC ---------- */
2099
  set_npc(hex2reg (&p_buf->data[NPC_REGNUM * 8 + 1]));
2100
  /*
2101
  err = gdb_write_reg(NPC_CPU_REG_ADD, hex2reg (&p_buf->data[NPC_REGNUM * 8 + 1]));
2102
  if(err > 0){
2103
        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> NPC\n", err);
2104
    put_str_packet ("E01");
2105
        return;
2106
  }
2107
  */
2108
  /* Acknowledge. TODO: We always succeed at present, even if the data was
2109
     defective. */
2110
  put_str_packet ("OK");
2111
}       /* rsp_write_all_regs () */
2112
 
2113
 
2114
/*---------------------------------------------------------------------------*/
2115
/* Handle a RSP read memory (symbolic) request
2116
 
2117
   Syntax is:
2118
 
2119
     m<addr>,<length>:
2120
 
2121
   The response is the bytes, lowest address first, encoded as pairs of hex
2122
   digits.
2123
 
2124
   The length given is the number of bytes to be read.
2125
 
2126
   @note This function reuses p_buf, so trashes the original command.
2127
 
2128
   @param[in] p_buf  The command received                                      */
2129
/*---------------------------------------------------------------------------*/
2130
static void rsp_read_mem (struct rsp_buf *p_buf)
2131
{
2132
  unsigned int    addr;                 /* Where to read the memory */
2133
  int             len;                  /* Number of bytes to read */
2134
  int             off;                  /* Offset into the memory */
2135
        uint32_t                temp_uint32 = 0;
2136
  char                                          *rec_buf;
2137
 
2138
 
2139
  if (2 != sscanf (p_buf->data, "m%x,%x:", &addr, &len))
2140
  {
2141
    fprintf (stderr, "Warning: Failed to recognize RSP read memory "
2142
       "command: %s\n", p_buf->data);
2143
    put_str_packet ("E01");
2144
    return;
2145
  }
2146
 
2147
  /* Make sure we won't overflow the buffer (2 chars per byte) */
2148
  if ((len * 2) >= GDB_BUF_MAX)
2149
  {
2150
    fprintf (stderr, "Warning: Memory read %s too large for RSP packet: "
2151
       "truncated\n", p_buf->data);
2152
    len = (GDB_BUF_MAX - 1) / 2;
2153
        }
2154
 
2155
  if(!(rec_buf = (char*)malloc(len))) {
2156
    put_str_packet ("E01");
2157
    ProtocolClean(0, JTAG_PROXY_OUT_OF_MEMORY);
2158
    return;
2159
  }
2160
 
2161
  // Make sure the processor is stalled
2162
  gdb_ensure_or1k_stalled();
2163
 
2164
  // Set chain 5 --> Wishbone Memory chain
2165
  err = gdb_set_chain(SC_WISHBONE);
2166
  if(err){
2167
        if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
2168
        put_str_packet ("E01");
2169
    return;
2170
        }
2171
 
2172
  // Read the data from Wishbone Memory chain
2173
  err = gdb_read_block(addr, (uint32_t*)rec_buf, len);
2174
  if(err){
2175
        put_str_packet ("E01");
2176
                return;
2177
        }
2178
 
2179
  /* Refill the buffer with the reply */
2180
  for( off = 0 ; off < len ; off ++ ) {
2181
                ;
2182
                temp_uint32 = (temp_uint32 << 8) | (0x000000ff & *(rec_buf + off));
2183
 
2184
                if((off %4 ) == 3){
2185
                        temp_uint32 = htonl(temp_uint32);
2186
                        reg2hex (temp_uint32, &(p_buf->data[off * 2 - 6]));
2187
                }
2188
                if (DEBUG_GDB_BLOCK_DATA){
2189
                  switch(off % 16)
2190
                        {
2191
                                case 3:
2192
                                        printf("Add 0x%08x   Data 0x%08x  ", addr + off - 3, temp_uint32);
2193
                                        break;
2194
                                case 7:
2195
                                case 11:
2196
                                        printf("0x%08x  ", temp_uint32);
2197
                                        break;
2198
                                case 15:
2199
                                        printf("0x%08x\n", temp_uint32);
2200
                                        break;
2201
                                default:
2202
                                        break;
2203
                        }
2204
                        if ((len - off == 1) && (off % 16) < 15) printf("\n");
2205
                }
2206
  }
2207
 
2208
  if (DEBUG_GDB && (err > 0)) printf("\nError %x\n", err);fflush (stdout);
2209
        free(rec_buf);
2210
  p_buf->data[off * 2] = 0;                      /* End of string */
2211
  p_buf->len           = strlen (p_buf->data);
2212
  put_packet (p_buf);
2213
}       /* rsp_read_mem () */
2214
 
2215
 
2216
/*---------------------------------------------------------------------------*/
2217
/*!Handle a RSP write memory (symbolic) request  ("M")
2218
 
2219
   Syntax is:
2220
 
2221
     M<addr>,<length>:<data>
2222
 
2223
        Example: M4015cc,2:c320#
2224
          (Write the value 0xc320 to address 0x4015cc.)
2225
 
2226
                An example target response:
2227
                + $OK#
2228
 
2229
   The data is the bytes, lowest address first, encoded as pairs of hex
2230
   digits.
2231
 
2232
   The length given is the number of bytes to be written.
2233
 
2234
   @note This function reuses p_buf, so trashes the original command.
2235
 
2236
   @param[in] p_buf  The command received                                      */
2237
/*---------------------------------------------------------------------------*/
2238
static void
2239
rsp_write_mem (struct rsp_buf *p_buf)
2240
{
2241
  unsigned int    addr;                 /* Where to write the memory */
2242
  int             len;                  /* Number of bytes to write */
2243
  char           *symdat;               /* Pointer to the symboli data */
2244
  int             datlen;               /* Number of digits in symbolic data */
2245
  int             off;                  /* Offset into the memory */
2246
  int             nibc;                 /* Nibbel counter */
2247
        uint32_t   val;
2248
 
2249
  if (2 != sscanf (p_buf->data, "M%x,%x:", &addr, &len))
2250
  {
2251
    fprintf (stderr, "Warning: Failed to recognize RSP write memory "
2252
       "command: %s\n", p_buf->data);
2253
    put_str_packet ("E01");
2254
    return;
2255
  }
2256
 
2257
  /* Find the start of the data and check there is the amount we expect. */
2258
  symdat = (char*) memchr ((const void *)p_buf->data, ':', GDB_BUF_MAX) + 1;
2259
  datlen = p_buf->len - (symdat - p_buf->data);
2260
 
2261
  /* Sanity check */
2262
  if (len * 2 != datlen)
2263
  {
2264
    fprintf (stderr, "Warning: Write of %d digits requested, but %d digits "
2265
       "supplied: packet ignored\n", len * 2, datlen );
2266
    put_str_packet ("E01");
2267
    return;
2268
  }
2269
 
2270
  // Make sure the processor is stalled
2271
  gdb_ensure_or1k_stalled();
2272
 
2273
 
2274
  // Set chain 5 --> Wishbone Memory chain
2275
  err = gdb_set_chain(SC_WISHBONE);
2276
        if(err){
2277
    put_str_packet ("E01");
2278
    return;
2279
        }
2280
 
2281
        val = 0;
2282
        off = 0;
2283
  /* Write the bytes to memory */
2284
  for (nibc = 0; nibc < datlen; nibc++)
2285
  {
2286
                val |= 0x0000000f & hex (symdat[nibc]);
2287
                if(nibc % 8 == 7){
2288
                        err = gdb_write_block(addr + off, &val, 4);
2289
                        if (DEBUG_GDB) printf("Error %x\n", err);fflush (stdout);
2290
                        if(err){
2291
                                put_str_packet ("E01");
2292
                                return;
2293
                        }
2294
                  val = 0;
2295
                        off += 4;
2296
                }
2297
          val <<= 4;
2298
  }
2299
  put_str_packet ("OK");
2300
}       /* rsp_write_mem () */
2301
 
2302
 
2303
/*---------------------------------------------------------------------------*/
2304
/*!Read a single register
2305
 
2306
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PC
2307
   (i.e. SPR NPC) and SR (i.e. SPR SR). The register is returned as a
2308
   sequence of bytes in target endian order.
2309
 
2310
   Each byte is packed as a pair of hex digits.
2311
 
2312
   @param[in] p_buf  The original packet request. Reused for the reply.        */
2313
/*---------------------------------------------------------------------------*/
2314
static void
2315
rsp_read_reg (struct rsp_buf *p_buf)
2316
{
2317
  unsigned int          regnum;
2318
        uint32_t        temp_uint32;
2319
 
2320
  /* Break out the fields from the data */
2321
  if (1 != sscanf (p_buf->data, "p%x", &regnum))
2322
    {
2323
      fprintf (stderr, "Warning: Failed to recognize RSP read register "
2324
               "command: %s\n", p_buf->data);
2325
      put_str_packet ("E01");
2326
      return;
2327
    }
2328
 
2329
  // Make sure the processor is stalled
2330
  gdb_ensure_or1k_stalled();
2331
 
2332
  // First set the chain 
2333
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
2334
  if(err > 0){
2335
        if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
2336
    put_str_packet ("E01");
2337
        return;
2338
        }
2339
 
2340
  /* Get the relevant register */
2341
  if (regnum < MAX_GPRS)
2342
    {
2343
                  err = gdb_read_reg(0x400 + regnum, &temp_uint32);
2344
                  if(err > 0){
2345
                        if (DEBUG_GDB) printf("Error %d in rsp_read_reg at reg. %d \n", err, regnum);
2346
                    put_str_packet ("E01");
2347
                        return;
2348
                  }
2349
                  reg2hex (temp_uint32, p_buf->data);
2350
    }
2351
  else if (PPC_REGNUM == regnum)        /* ---------- PPC ---------- */
2352
    {
2353
                  err = gdb_read_reg(PPC_CPU_REG_ADD, &temp_uint32);
2354
                  if(err > 0){
2355
                        if (DEBUG_GDB) printf("Error %d in rsp_read_reg read --> PPC\n", err);
2356
                    put_str_packet ("E01");
2357
                        return;
2358
                  }
2359
                  reg2hex (temp_uint32, p_buf->data);
2360
    }
2361
  else if (NPC_REGNUM == regnum)        /* ---------- NPC ---------- */
2362
    {
2363
      temp_uint32 = get_npc();
2364
      /*
2365
      err = gdb_read_reg(NPC_CPU_REG_ADD, &temp_uint32);
2366
      if(err > 0){
2367
        if (DEBUG_GDB) printf("Error %d in rsp_read_reg read --> PPC\n", err);
2368
        put_str_packet ("E01");
2369
        return;
2370
      }
2371
      */
2372
      reg2hex (temp_uint32, p_buf->data);
2373
    }
2374
  else if (SR_REGNUM == regnum)         /* ---------- SR ---------- */
2375
    {
2376
      err = gdb_read_reg(SR_CPU_REG_ADD, &temp_uint32);
2377
      if(err > 0){
2378
        if (DEBUG_GDB) printf("Error %d in rsp_read_reg read --> PPC\n", err);
2379
        put_str_packet ("E01");
2380
        return;
2381
      }
2382
      reg2hex (temp_uint32, p_buf->data);
2383
    }
2384
  else
2385
    {
2386
      /* Error response if we don't know the register */
2387
      fprintf (stderr, "Warning: Attempt to read unknown register 0x%x: "
2388
               "ignored\n", regnum);
2389
      put_str_packet ("E01");
2390
      return;
2391
    }
2392
 
2393
  p_buf->len = strlen (p_buf->data);
2394
  put_packet (p_buf);
2395
 
2396
}       /* rsp_read_reg () */
2397
 
2398
 
2399
/*---------------------------------------------------------------------------*/
2400
/*!Write a single register
2401
 
2402
   The registers follow the GDB sequence for OR1K: GPR0 through GPR31, PC
2403
   (i.e. SPR NPC) and SR (i.e. SPR SR). The register is specified as a
2404
   sequence of bytes in target endian order.
2405
 
2406
   Each byte is packed as a pair of hex digits.
2407
 
2408
   @param[in] p_buf  The original packet request.                              */
2409
/*---------------------------------------------------------------------------*/
2410
static void
2411
rsp_write_reg (struct rsp_buf *p_buf)
2412
{
2413
  unsigned int  regnum;
2414
  char          valstr[9];              /* Allow for EOS on the string */
2415
        // int           err = 0;
2416
 
2417
  /* Break out the fields from the data */
2418
  if (2 != sscanf (p_buf->data, "P%x=%8s", &regnum, valstr))
2419
    {
2420
      fprintf (stderr, "Warning: Failed to recognize RSP write register "
2421
               "command: %s\n", p_buf->data);
2422
      put_str_packet ("E01");
2423
      return;
2424
    }
2425
 
2426
  // Make sure the processor is stalled
2427
  gdb_ensure_or1k_stalled();
2428
 
2429
  // First set the chain 
2430
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
2431
  if(err > 0){
2432
        if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
2433
    put_str_packet ("E01");
2434
        return;
2435
        }
2436
 
2437
  /* Set the relevant register */
2438
  if (regnum < MAX_GPRS)                                 /* ---------- GPRS ---------- */
2439
                {
2440
      err = gdb_write_reg(0x400 + regnum, hex2reg (valstr));
2441
                  if(err > 0){
2442
                        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> GPRS\n", err);
2443
                    put_str_packet ("E01");
2444
                        return;
2445
                  }
2446
    }
2447
  else if (PPC_REGNUM == regnum) /* ---------- PPC ---------- */
2448
    {
2449
      err = gdb_write_reg(PPC_CPU_REG_ADD, hex2reg (valstr));
2450
                  if(err > 0){
2451
                        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> PPC\n", err);
2452
                    put_str_packet ("E01");
2453
                        return;
2454
                  }
2455
    }
2456
  else if (NPC_REGNUM == regnum) /* ---------- NPC ---------- */
2457
    {
2458
      set_npc(hex2reg (valstr));
2459
      /*
2460
      err = gdb_write_reg(NPC_CPU_REG_ADD, hex2reg (valstr));
2461
      if(err > 0){
2462
        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> NPC\n", err);
2463
        put_str_packet ("E01");
2464
        return;
2465
      }
2466
      */
2467
    }
2468
  else if (SR_REGNUM == regnum)  /* ---------- SR ---------- */
2469
    {
2470
      err = gdb_write_reg(SR_CPU_REG_ADD, hex2reg (valstr));
2471
                  if(err > 0){
2472
                        if (DEBUG_GDB) printf("Error %d in rsp_write_reg write --> SR\n", err);
2473
                    put_str_packet ("E01");
2474
                        return;
2475
                  }
2476
    }
2477
  else
2478
    {
2479
      /* Error response if we don't know the register */
2480
      fprintf (stderr, "Warning: Attempt to write unknown register 0x%x: "
2481
               "ignored\n", regnum);
2482
      put_str_packet ("E01");
2483
      return;
2484
    }
2485
 
2486
  put_str_packet ("OK");
2487
 
2488
}       /* rsp_write_reg () */
2489
 
2490
 
2491
/*---------------------------------------------------------------------------*/
2492
/*!Handle a RSP query request
2493
 
2494
   @param[in] p_buf  The request                                               */
2495
/*---------------------------------------------------------------------------*/
2496
static void
2497
rsp_query (struct rsp_buf *p_buf)
2498
{
2499
  if (0 == strcmp ("qC", p_buf->data))
2500
    {
2501
      /* Return the current thread ID (unsigned hex). A null response
2502
         indicates to use the previously selected thread. Since we do not
2503
         support a thread concept, this is the appropriate response. */
2504
      put_str_packet ("");
2505
    }
2506
  else if (0 == strncmp ("qCRC", p_buf->data, strlen ("qCRC")))
2507
    {
2508
      /* Return CRC of memory area */
2509
      fprintf (stderr, "Warning: RSP CRC query not supported\n");
2510
      put_str_packet ("E01");
2511
    }
2512
  else if (0 == strcmp ("qfThreadInfo", p_buf->data))
2513
    {
2514
      /* Return info about active threads. We return just '-1' */
2515
      put_str_packet ("m-1");
2516
    }
2517
  else if (0 == strcmp ("qsThreadInfo", p_buf->data))
2518
    {
2519
      /* Return info about more active threads. We have no more, so return the
2520
         end of list marker, 'l' */
2521
      put_str_packet ("l");
2522
    }
2523
  else if (0 == strncmp ("qGetTLSAddr:", p_buf->data, strlen ("qGetTLSAddr:")))
2524
    {
2525
      /* We don't support this feature */
2526
      put_str_packet ("");
2527
    }
2528
  else if (0 == strncmp ("qL", p_buf->data, strlen ("qL")))
2529
    {
2530
      /* Deprecated and replaced by 'qfThreadInfo' */
2531
      fprintf (stderr, "Warning: RSP qL deprecated: no info returned\n");
2532
      put_str_packet ("qM001");
2533
    }
2534
  else if (0 == strcmp ("qOffsets", p_buf->data))
2535
    {
2536
      /* Report any relocation */
2537
      put_str_packet ("Text=0;Data=0;Bss=0");
2538
    }
2539
  else if (0 == strncmp ("qP", p_buf->data, strlen ("qP")))
2540
    {
2541
      /* Deprecated and replaced by 'qThreadExtraInfo' */
2542
      fprintf (stderr, "Warning: RSP qP deprecated: no info returned\n");
2543
      put_str_packet ("");
2544
    }
2545
  else if (0 == strncmp ("qRcmd,", p_buf->data, strlen ("qRcmd,")))
2546
    {
2547
      /* This is used to interface to commands to do "stuff" */
2548
      rsp_command (p_buf);
2549
    }
2550
  else if (0 == strncmp ("qSupported", p_buf->data, strlen ("qSupported")))
2551
    {
2552
      /* Report a list of the features we support. For now we just ignore any
2553
                                 supplied specific feature queries, but in the future these may be
2554
                                 supported as well. Note that the packet size allows for 'G' + all the
2555
                                 registers sent to us, or a reply to 'g' with all the registers and an
2556
                                 EOS so the buffer is a well formed string. */
2557
      setup_or32();     // setup cpu
2558
      char  reply[GDB_BUF_MAX];
2559
      sprintf (reply, "PacketSize=%x", GDB_BUF_MAX);
2560
      put_str_packet (reply);
2561
    }
2562
  else if (0 == strncmp ("qSymbol:", p_buf->data, strlen ("qSymbol:")))
2563
    {
2564
      /* Offer to look up symbols. Nothing we want (for now). TODO. This just
2565
         ignores any replies to symbols we looked up, but we didn't want to
2566
         do that anyway! */
2567
      put_str_packet ("OK");
2568
    }
2569
  else if (0 == strncmp ("qThreadExtraInfo,", p_buf->data,
2570
                         strlen ("qThreadExtraInfo,")))
2571
    {
2572
      /* Report that we are runnable, but the text must be hex ASCI
2573
         digits. For now do this by steam, reusing the original packet */
2574
      sprintf (p_buf->data, "%02x%02x%02x%02x%02x%02x%02x%02x%02x",
2575
               'R', 'u', 'n', 'n', 'a', 'b', 'l', 'e', 0);
2576
      p_buf->len = strlen (p_buf->data);
2577
      put_packet (p_buf);
2578
    }
2579
  else if (0 == strncmp ("qXfer:", p_buf->data, strlen ("qXfer:")))
2580
    {
2581
      /* For now we support no 'qXfer' requests, but these should not be
2582
         expected, since they were not reported by 'qSupported' */
2583
      fprintf (stderr, "Warning: RSP 'qXfer' not supported: ignored\n");
2584
      put_str_packet ("");
2585
    }
2586
  else
2587
    {
2588
      fprintf (stderr, "Unrecognized RSP query: ignored\n");
2589
    }
2590
}       /* rsp_query () */
2591
 
2592
 
2593
/*---------------------------------------------------------------------------*/
2594
/*!Handle a RSP qRcmd request
2595
 
2596
  The actual command follows the "qRcmd," in ASCII encoded to hex
2597
 
2598
   @param[in] p_buf  The request in full                                       */
2599
/*---------------------------------------------------------------------------*/
2600
static void
2601
rsp_command (struct rsp_buf *p_buf)
2602
{
2603
  char  cmd[GDB_BUF_MAX];
2604
  unsigned int      regno;
2605
  uint32_t              temp_uint32;
2606
 
2607
  hex2ascii (cmd, &(p_buf->data[strlen ("qRcmd,")]));
2608
 
2609
  /* Work out which command it is */
2610
  if (0 == strncmp ("readspr ", cmd, strlen ("readspr")))
2611
  {
2612
    /* Parse and return error if we fail */
2613
    if( 1 != sscanf (cmd, "readspr %4x", &regno))
2614
      {
2615
        fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n", cmd);
2616
        put_str_packet ("E01");
2617
        return;
2618
      }
2619
 
2620
    /* SPR out of range */
2621
    if (regno > MAX_SPRS)
2622
      {
2623
        fprintf (stderr, "Warning: qRcmd readspr %x too large: ignored\n",
2624
                 regno);
2625
        put_str_packet ("E01");
2626
        return;
2627
      }
2628
 
2629
    /* Construct the reply */
2630
 
2631
    // Make sure the processor is stalled
2632
    gdb_ensure_or1k_stalled();
2633
 
2634
    // First set the chain 
2635
    gdb_set_chain(SC_RISC_DEBUG);       /* 1 RISC Debug Interface chain */
2636
 
2637
    // special case for NPC
2638
    if(regno == NPC_CPU_REG_ADD)
2639
      temp_uint32 = get_npc();
2640
    else
2641
      {
2642
        err = gdb_read_reg(regno, &temp_uint32);
2643
        if(err > 0){
2644
          if (DEBUG_GDB) printf("Error %d in rsp_command at reg. %x \n", err, regno);
2645
        }
2646
        else{
2647
          reg2hex (temp_uint32, cmd);
2648
          if (DEBUG_GDB) printf("Error %d Command readspr Read reg. %x = 0x%08x\n", err, regno, temp_uint32);
2649
        }
2650
      }
2651
 
2652
    // pack the result into the buffer to send back
2653
    sprintf (cmd, "%8x", (unsigned int)temp_uint32);
2654
    ascii2hex (p_buf->data, cmd);
2655
    p_buf->len = strlen (p_buf->data);
2656
    put_packet (p_buf);
2657
  }
2658
  else if (0 == strncmp ("writespr ", cmd, strlen ("writespr")))
2659
    {
2660
      unsigned int       regno;
2661
      uint32_t  val;
2662
 
2663
      /* Parse and return error if we fail */
2664
      if( 2 != sscanf (cmd, "writespr %4x %8x", &regno, &val))
2665
        {
2666
          fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n",
2667
                   cmd);
2668
          put_str_packet ("E01");
2669
          return;
2670
        }
2671
 
2672
      /* SPR out of range */
2673
      if (regno > MAX_SPRS)
2674
        {
2675
          fprintf (stderr, "Warning: qRcmd writespr %x too large: ignored\n",
2676
                   regno);
2677
          put_str_packet ("E01");
2678
          return;
2679
        }
2680
 
2681
      // Make sure the processor is stalled
2682
      gdb_ensure_or1k_stalled();
2683
 
2684
      // First set the chain 
2685
      gdb_set_chain(SC_RISC_DEBUG);     /* 1 RISC Debug Interface chain */
2686
 
2687
      /* set the relevant register */
2688
      // special case for NPC
2689
      if(regno == NPC_CPU_REG_ADD)
2690
        set_npc(val);
2691
      else
2692
        {
2693
 
2694
          err = gdb_write_reg(regno, val);
2695
          if(err > 0){
2696
            if (DEBUG_GDB) printf("Error %d in rsp_command write Reg. %x = 0x%08x\n", err, regno, val);
2697
            put_str_packet ("E01");
2698
            return;
2699
          }
2700
          else{
2701
            if (DEBUG_GDB) printf("Error %d Command writespr Write reg. %x = 0x%08x\n", err, regno, val);
2702
          }
2703
        }
2704
      put_str_packet ("OK");
2705
    }
2706
}       /* rsp_command () */
2707
 
2708
 
2709
/*---------------------------------------------------------------------------*/
2710
/*!Handle a RSP set request
2711
 
2712
   @param[in] p_buf  The request                                               */
2713
/*---------------------------------------------------------------------------*/
2714
static void
2715
rsp_set (struct rsp_buf *p_buf)
2716
{
2717
  if (0 == strncmp ("QPassSignals:", p_buf->data, strlen ("QPassSignals:")))
2718
    {
2719
      /* Passing signals not supported */
2720
      put_str_packet ("");
2721
    }
2722
  else if ((0 == strncmp ("QTDP",    p_buf->data, strlen ("QTDP")))   ||
2723
           (0 == strncmp ("QFrame",  p_buf->data, strlen ("QFrame"))) ||
2724
           (0 == strcmp  ("QTStart", p_buf->data))                    ||
2725
           (0 == strcmp  ("QTStop",  p_buf->data))                    ||
2726
           (0 == strcmp  ("QTinit",  p_buf->data))                    ||
2727
           (0 == strncmp ("QTro",    p_buf->data, strlen ("QTro"))))
2728
    {
2729
      /* All tracepoint features are not supported. This reply is really only
2730
         needed to 'QTDP', since with that the others should not be
2731
         generated. */
2732
      put_str_packet ("");
2733
    }
2734
  else
2735
    {
2736
      fprintf (stderr, "Unrecognized RSP set request: ignored\n");
2737
    }
2738
}       /* rsp_set () */
2739
 
2740
 
2741
/*---------------------------------------------------------------------------*/
2742
/*!Handle a RSP restart request
2743
 
2744
   For now we just put the program counter back to the one used with the last
2745
   vRun request. There is no point in unstalling the processor, since we'll
2746
   never get control back.                                                   */
2747
/*---------------------------------------------------------------------------*/
2748
static void
2749
rsp_restart (void)
2750
{
2751
  // Make sure the processor is stalled
2752
  gdb_ensure_or1k_stalled();
2753
 
2754
  // First set the chain 
2755
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
2756
  if(err > 0){
2757
        if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
2758
    put_str_packet ("E01");
2759
        return;
2760
        }
2761
        // OR32 Arc sim equivalent --> set_npc (rsp.start_addr);
2762
  /* Set NPC to reset vector 0x100 */
2763
  set_npc(rsp.start_addr);
2764
  /*
2765
  err = gdb_write_reg(NPC_CPU_REG_ADD, rsp.start_addr);
2766
  if(err > 0){
2767
        if (DEBUG_GDB) printf("Error %d in rsp_restart write Reg. %x = 0x%08x\n", err, NPC_CPU_REG_ADD, rsp.start_addr);
2768
    put_str_packet ("E01");
2769
        return;
2770
  }
2771
 
2772
  else{
2773
  if (DEBUG_GDB) printf("Error %d Command Reset. Set NPC to Start vector %x = 0x%08x\n", err, NPC_CPU_REG_ADD, rsp.start_addr);
2774
  }
2775
  */
2776
}       /* rsp_restart () */
2777
 
2778
 
2779
/*---------------------------------------------------------------------------*/
2780
/*!Handle a RSP step request
2781
 
2782
   Parse the command to see if there is an address. Uses the underlying
2783
   generic step function, with EXCEPT_NONE.
2784
 
2785
   @param[in] p_buf  The full step packet                          */
2786
/*---------------------------------------------------------------------------*/
2787
static void
2788
rsp_step (struct rsp_buf *p_buf)
2789
{
2790
  uint32_t  addr;               /* The address to step from, if any */
2791
 
2792
  // Make sure the processor is stalled
2793
  gdb_ensure_or1k_stalled();
2794
 
2795
  // First set the chain 
2796
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
2797
  if(err > 0){
2798
        printf("Error %d to set RISC Debug Interface chain in the STEP command 's'\n", err);
2799
    rsp_client_close ();
2800
    return;
2801
        }
2802
 
2803
  if (0 == strcmp ("s", p_buf->data))
2804
  {
2805
    // Arc Sim Code -->   addr = cpu_state.pc;  /* Default uses current NPC */
2806
    /* ---------- Npc ---------- */
2807
    addr = get_npc();
2808
    /*
2809
    err = gdb_read_reg(NPC_CPU_REG_ADD, &addr);
2810
    if(err > 0){
2811
      printf("Error %d to read NPC in the STEP command 's'\n", err);
2812
      rsp_client_close ();
2813
      return;
2814
    }
2815
    */
2816
  }
2817
  else if (1 != sscanf (p_buf->data, "s%x", &addr))
2818
  {
2819
    fprintf (stderr,
2820
             "Warning: RSP step address %s not recognized: ignored\n",
2821
             p_buf->data);
2822
 
2823
    // Arc Sim Code -->   addr = cpu_state.pc;  /* Default uses current NPC */
2824
    /* ---------- NPC ---------- */
2825
    addr = get_npc();
2826
    /*
2827
    err = gdb_read_reg(NPC_CPU_REG_ADD, &addr);
2828
    if(err > 0){
2829
      printf("Error %d to read NPC in the STEP command 's'\n", err);
2830
      rsp_client_close ();
2831
      return;
2832
    }
2833
    */
2834
  }
2835
 
2836
  //if (DEBUG_GDB) printf("rsp_step() --> Read NPC = 0x%08x\n", addr);
2837
  rsp_step_generic (addr, EXCEPT_NONE);
2838
 
2839
}       /* rsp_step () */
2840
 
2841
 
2842
/*---------------------------------------------------------------------------*/
2843
/*!Handle a RSP step with signal request
2844
 
2845
   Currently null. Will use the underlying generic step function.
2846
 
2847
   @param[in] p_buf  The full step with signal packet              */
2848
/*---------------------------------------------------------------------------*/
2849
static void
2850
rsp_step_with_signal (struct rsp_buf *p_buf)
2851
{
2852
  printf ("RSP step with signal '%s' received\n", p_buf->data);
2853
 
2854
}       /* rsp_step_with_signal () */
2855
 
2856
 
2857
/*---------------------------------------------------------------------------*/
2858
/*!Generic processing of a step request
2859
 
2860
   The signal may be EXCEPT_NONE if there is no exception to be
2861
   handled. Currently the exception is ignored.
2862
 
2863
   The single step flag is set in the debug registers and then the processor
2864
   is unstalled.
2865
 
2866
   @param[in] addr    Address from which to step
2867
   @param[in] except  The exception to use (if any)                          */
2868
/*---------------------------------------------------------------------------*/
2869
static void
2870
rsp_step_generic (uint32_t  addr,
2871
                  uint32_t  except)
2872
{
2873
  uint32_t              temp_uint32;
2874
 
2875
  /* Set the address as the value of the next program counter */
2876
 
2877
  set_npc (addr);
2878
 
2879
  /* Clear Debug Reason Register (DRR) 0x3015 */
2880
  // Arc sim --> cpu_state.sprs[SPR_DRR]   = 0;
2881
  if(gdb_write_reg(DRR_CPU_REG_ADD, 0)) printf("Error write to DRR register\n");
2882
 
2883
  /* Clear watchpoint break generation in Debug Mode Register 2 (DMR2) 0x3011 */
2884
  // Arc sim --> cpu_state.sprs[SPR_DMR2] &= ~SPR_DMR2_WGB;
2885
  if(gdb_read_reg(DMR2_CPU_REG_ADD, &temp_uint32)) printf("Error read from DMR2 register\n");
2886
  temp_uint32 &= ~SPR_DMR2_WGB;
2887
  if(gdb_write_reg(DMR2_CPU_REG_ADD, temp_uint32)) printf("Error write to DMR2 register\n");
2888
 
2889
  /* Set the single step trigger in Debug Mode Register 1 (DMR1) Register 0x3010 */
2890
  // Arc sim --> cpu_state.sprs[SPR_DMR1] |= SPR_DMR1_ST;
2891
  if(gdb_read_reg(DMR1_CPU_REG_ADD, &temp_uint32)) printf("Error read from DMR1 register\n");
2892
  temp_uint32 |= SPR_DMR1_ST;
2893
  if(gdb_write_reg(DMR1_CPU_REG_ADD, temp_uint32)) printf("Error write to DMR1 register\n");
2894
 
2895
  /* Set traps to be handled by the debug unit in the Debug Stop Register (DSR) Register 0x3014 */
2896
  // Arc sim --> cpu_state.sprs[SPR_DSR]  |= SPR_DSR_TE;
2897
  if(gdb_read_reg(DSR_CPU_REG_ADD, &temp_uint32)) printf("Error read from DSR register\n");
2898
  temp_uint32 |= SPR_DSR_TE;
2899
  if(gdb_write_reg(DSR_CPU_REG_ADD, temp_uint32)) printf("Error write to DSR register\n");
2900
 
2901
  /* Unstall the processor */
2902
  set_stall_state (0);
2903
 
2904
  /* Note the GDB client is now waiting for a reply. */
2905
  rsp.client_waiting = 1;
2906
 
2907
}       /* rsp_step_generic () */
2908
 
2909
 
2910
/*---------------------------------------------------------------------------*/
2911
/*!Handle a RSP 'v' packet
2912
 
2913
   These are commands associated with executing the code on the target
2914
 
2915
   @param[in] p_buf  The request                                               */
2916
/*---------------------------------------------------------------------------*/
2917
static void
2918
rsp_vpkt (struct rsp_buf *p_buf)
2919
{
2920
  if (0 == strncmp ("vAttach;", p_buf->data, strlen ("vAttach;")))
2921
    {
2922
      /* Attaching is a null action, since we have no other process. We just
2923
         return a stop packet (using TRAP) to indicate we are stopped. */
2924
      put_str_packet ("S05");
2925
      return;
2926
    }
2927
  else if (0 == strcmp ("vCont?", p_buf->data))
2928
    {
2929
      /* For now we don't support this. */
2930
      put_str_packet ("");
2931
      return;
2932
    }
2933
  else if (0 == strncmp ("vCont", p_buf->data, strlen ("vCont")))
2934
    {
2935
      /* This shouldn't happen, because we've reported non-support via vCont?
2936
         above */
2937
      fprintf (stderr, "Warning: RSP vCont not supported: ignored\n" );
2938
      return;
2939
    }
2940
  else if (0 == strncmp ("vFile:", p_buf->data, strlen ("vFile:")))
2941
    {
2942
      /* For now we don't support this. */
2943
      fprintf (stderr, "Warning: RSP vFile not supported: ignored\n" );
2944
      put_str_packet ("");
2945
      return;
2946
    }
2947
  else if (0 == strncmp ("vFlashErase:", p_buf->data, strlen ("vFlashErase:")))
2948
    {
2949
      /* For now we don't support this. */
2950
      fprintf (stderr, "Warning: RSP vFlashErase not supported: ignored\n" );
2951
      put_str_packet ("E01");
2952
      return;
2953
    }
2954
  else if (0 == strncmp ("vFlashWrite:", p_buf->data, strlen ("vFlashWrite:")))
2955
    {
2956
      /* For now we don't support this. */
2957
      fprintf (stderr, "Warning: RSP vFlashWrite not supported: ignored\n" );
2958
      put_str_packet ("E01");
2959
      return;
2960
    }
2961
  else if (0 == strcmp ("vFlashDone", p_buf->data))
2962
    {
2963
      /* For now we don't support this. */
2964
      fprintf (stderr, "Warning: RSP vFlashDone not supported: ignored\n" );
2965
      put_str_packet ("E01");
2966
      return;
2967
    }
2968
  else if (0 == strncmp ("vRun;", p_buf->data, strlen ("vRun;")))
2969
    {
2970
      /* We shouldn't be given any args, but check for this */
2971
      if (p_buf->len > (int) strlen ("vRun;"))
2972
        {
2973
          fprintf (stderr, "Warning: Unexpected arguments to RSP vRun "
2974
                   "command: ignored\n");
2975
        }
2976
 
2977
      /* Restart the current program. However unlike a "R" packet, "vRun"
2978
         should behave as though it has just stopped. We use signal
2979
         5 (TRAP). */
2980
      rsp_restart ();
2981
      put_str_packet ("S05");
2982
    }
2983
  else
2984
    {
2985
      fprintf (stderr, "Warning: Unknown RSP 'v' packet type %s: ignored\n",
2986
               p_buf->data);
2987
      put_str_packet ("E01");
2988
      return;
2989
    }
2990
}       /* rsp_vpkt () */
2991
 
2992
 
2993
/*---------------------------------------------------------------------------*/
2994
/*!Handle a RSP write memory (binary) request
2995
 
2996
   Syntax is:
2997
 
2998
     X<addr>,<length>:
2999
 
3000
   Followed by the specified number of bytes as raw binary. Response should be
3001
   "OK" if all copied OK, E<nn> if error <nn> has occurred.
3002
 
3003
   The length given is the number of bytes to be written. However the number
3004
   of data bytes may be greater, since '#', '$' and '}' are escaped by
3005
   preceding them by '}' and oring with 0x20.
3006
 
3007
   @param[in] p_buf  The command received                                      */
3008
/*---------------------------------------------------------------------------*/
3009
static void
3010
rsp_write_mem_bin (struct rsp_buf *p_buf)
3011
{
3012
  unsigned int  addr;                   /* Where to write the memory */
3013
  int           len;                    /* Number of bytes to write */
3014
  char          *bindat;        /* Pointer to the binary data */
3015
  int           off = 0; /* Offset to start of binary data */
3016
  int           newlen;         /* Number of bytes in bin data */
3017
 
3018
  if (2 != sscanf (p_buf->data, "X%x,%x:", &addr, &len))
3019
    {
3020
      fprintf (stderr, "Warning: Failed to recognize RSP write memory "
3021
               "command: %s\n", p_buf->data);
3022
      put_str_packet ("E01");
3023
      return;
3024
    }
3025
 
3026
  /* Find the start of the data and "unescape" it */
3027
  bindat = p_buf->data;
3028
  while(off < GDB_BUF_MAX){
3029
        if(bindat[off] == ':'){
3030
                        bindat = bindat + off + 1;
3031
                        off++;
3032
                        break;
3033
                }
3034
                off++;
3035
  }
3036
        if(off >= GDB_BUF_MAX){
3037
          put_str_packet ("E01");
3038
                return;
3039
        }
3040
 
3041
  newlen = rsp_unescape (bindat, p_buf->len - off);
3042
 
3043
  /* Sanity check */
3044
  if (newlen != len)
3045
  {
3046
    int  minlen = len < newlen ? len : newlen;
3047
 
3048
    fprintf (stderr, "Warning: Write of %d bytes requested, but %d bytes "
3049
       "supplied. %d will be written\n", len, newlen, minlen);
3050
    len = minlen;
3051
  }
3052
 
3053
  // Make sure the processor is stalled
3054
  gdb_ensure_or1k_stalled();
3055
 
3056
  // Set chain 5 --> Wishbone Memory chain
3057
  err = gdb_set_chain(SC_WISHBONE);
3058
  if(err){
3059
    put_str_packet ("E01");
3060
    return;
3061
  }
3062
 
3063
  /* Write the bytes to memory */
3064
  if (len)
3065
    {
3066
      swap_buf(bindat, len);
3067
 
3068
      if (DEBUG_GDB_BLOCK_DATA){
3069
        uint32_t  temp_uint32;
3070
        for (off = 0; off < len; off++){
3071
          temp_uint32 = (temp_uint32 << 8) | (0x000000ff & bindat[off]);
3072
          if((off %4 ) == 3){
3073
            temp_uint32 = htonl(temp_uint32);
3074
          }
3075
          switch(off % 16)
3076
            {
3077
            case 3:
3078
              printf("Add 0x%08x   Data 0x%08x  ", addr + off - 3, temp_uint32);
3079
              break;
3080
            case 7:
3081
            case 11:
3082
              printf("0x%08x  ", temp_uint32);
3083
              break;
3084
            case 15:
3085
              printf("0x%08x\n", temp_uint32);
3086
              break;
3087
            default:
3088
              break;
3089
            }
3090
          if ((len - off == 1) && (off % 16) < 15) printf("\n");
3091
        }
3092
      }
3093
 
3094
      err = gdb_write_block(addr, (uint32_t*)bindat, len);
3095
      if(err){
3096
        put_str_packet ("E01");
3097
        return;
3098
      }
3099
      if (DEBUG_GDB) printf("Error %x\n", err);fflush (stdout);
3100
    }
3101
  put_str_packet ("OK");
3102
 
3103
}       /* rsp_write_mem_bin () */
3104
 
3105
 
3106
/*---------------------------------------------------------------------------*/
3107
/*!Handle a RSP remove breakpoint or matchpoint request
3108
 
3109
   For now only memory breakpoints are implemented, which are implemented by
3110
   substituting a breakpoint at the specified address. The implementation must
3111
   cope with the possibility of duplicate packets.
3112
 
3113
   @todo This doesn't work with icache/immu yet
3114
 
3115
   @param[in] p_buf  The command received                                      */
3116
/*---------------------------------------------------------------------------*/
3117
static void
3118
rsp_remove_matchpoint (struct rsp_buf *p_buf)
3119
{
3120
  enum mp_type       type;              /* What sort of matchpoint */
3121
  uint32_t  addr;               /* Address specified */
3122
  int                len;                       /* Matchpoint length (not used) */
3123
  struct mp_entry   *mpe;                       /* Info about the replaced instr */
3124
 
3125
  /* Break out the instruction */
3126
  if (3 != sscanf (p_buf->data, "z%1d,%x,%1d", (int *)&type, &addr, &len))
3127
    {
3128
      fprintf (stderr, "Warning: RSP matchpoint deletion request not "
3129
               "recognized: ignored\n");
3130
      put_str_packet ("E01");
3131
      return;
3132
    }
3133
 
3134
  /* Sanity check that the length is 4 */
3135
  if (4 != len)
3136
    {
3137
      fprintf (stderr, "Warning: RSP matchpoint deletion length %d not "
3138
               "valid: 4 assumed\n", len);
3139
      len = 4;
3140
    }
3141
 
3142
  /* Sort out the type of matchpoint */
3143
  switch (type)
3144
    {
3145
    case BP_MEMORY:
3146
      /* Memory breakpoint - replace the original instruction. */
3147
      mpe = mp_hash_delete (type, addr);
3148
 
3149
      /* If the BP hasn't yet been deleted, put the original instruction
3150
                         back. Don't forget to free the hash table entry afterwards. */
3151
                        if (NULL != mpe)
3152
                        {
3153
                          // Arc Sim Code -->   set_program32 (addr, mpe->instr);
3154
                          // Make sure the processor is stalled
3155
                          gdb_ensure_or1k_stalled();
3156
 
3157
                          // Set chain 5 --> Wishbone Memory chain
3158
                          err = gdb_set_chain(SC_WISHBONE);
3159
                                if(err){
3160
                                        put_str_packet ("E01");
3161
                                  return;
3162
                                }
3163
                                err = gdb_write_block(addr, &mpe->instr, 4);
3164
                                if(err){
3165
                                        put_str_packet ("E01");
3166
                                  return;
3167
                                }
3168
                          free (mpe);
3169
                        }
3170
 
3171
      put_str_packet ("OK");
3172
      return;
3173
 
3174
    case BP_HARDWARE:
3175
      put_str_packet ("");              /* Not supported */
3176
      return;
3177
 
3178
    case WP_WRITE:
3179
      put_str_packet ("");              /* Not supported */
3180
      return;
3181
 
3182
    case WP_READ:
3183
      put_str_packet ("");              /* Not supported */
3184
      return;
3185
 
3186
    case WP_ACCESS:
3187
      put_str_packet ("");              /* Not supported */
3188
      return;
3189
 
3190
    default:
3191
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
3192
               "recognized: ignored\n", type);
3193
      put_str_packet ("E01");
3194
      return;
3195
 
3196
    }
3197
}       /* rsp_remove_matchpoint () */
3198
 
3199
 
3200
/*---------------------------------------------------------------------------*/
3201
/*!Handle a RSP insert breakpoint or matchpoint request
3202
 
3203
   For now only memory breakpoints are implemented, which are implemented by
3204
   substituting a breakpoint at the specified address. The implementation must
3205
   cope with the possibility of duplicate packets.
3206
 
3207
   @todo This doesn't work with icache/immu yet
3208
 
3209
   @param[in] p_buf  The command received                                      */
3210
/*---------------------------------------------------------------------------*/
3211
static void
3212
rsp_insert_matchpoint (struct rsp_buf *p_buf)
3213
{
3214
  enum mp_type       type;              /* What sort of matchpoint */
3215
  uint32_t  addr;               /* Address specified */
3216
  int                len;               /* Matchpoint length (not used) */
3217
        uint32_t      instr;
3218
 
3219
  /* Break out the instruction */
3220
  if (3 != sscanf (p_buf->data, "Z%1d,%x,%1d", (int *)&type, &addr, &len))
3221
    {
3222
      fprintf (stderr, "Warning: RSP matchpoint insertion request not "
3223
               "recognized: ignored\n");
3224
      put_str_packet ("E01");
3225
      return;
3226
    }
3227
 
3228
  /* Sanity check that the length is 4 */
3229
  if (4 != len)
3230
    {
3231
      fprintf (stderr, "Warning: RSP matchpoint insertion length %d not "
3232
               "valid: 4 assumed\n", len);
3233
      len = 4;
3234
    }
3235
 
3236
  /* Sort out the type of matchpoint */
3237
  switch (type)
3238
    {
3239
    case BP_MEMORY:             // software-breakpoint Z0  break
3240
      /* Memory breakpoint - substitute a TRAP instruction */
3241
      // Make sure the processor is stalled
3242
      gdb_ensure_or1k_stalled();
3243
 
3244
      // Set chain 5 --> Wishbone Memory chain
3245
      gdb_set_chain(SC_WISHBONE);
3246
 
3247
      // Read the data from Wishbone Memory chain
3248
      // Arc Sim Code -->   mp_hash_add (type, addr, eval_direct32 (addr, 0, 0));
3249
      gdb_read_block(addr, &instr, 4);
3250
 
3251
      mp_hash_add (type, addr, instr);
3252
 
3253
      // Arc Sim Code -->   set_program32 (addr, OR1K_TRAP_INSTR);
3254
      instr = OR1K_TRAP_INSTR;
3255
      err = gdb_write_block(addr, &instr, 4);
3256
      if(err){
3257
        put_str_packet ("E01");
3258
        return;
3259
      }
3260
      put_str_packet ("OK");
3261
      return;
3262
 
3263
    case BP_HARDWARE:   // hardware-breakpoint Z1  hbreak
3264
      put_str_packet ("");              /* Not supported */
3265
      return;
3266
 
3267
    case WP_WRITE:              // write-watchpoint    Z2  watch                                                                                                                                                        
3268
      put_str_packet ("");              /* Not supported */
3269
      return;
3270
 
3271
    case WP_READ:                       // read-watchpoint     Z3  rwatch
3272
      put_str_packet ("");              /* Not supported */
3273
      return;
3274
 
3275
    case WP_ACCESS:             // access-watchpoint   Z4  awatch
3276
      put_str_packet ("");              /* Not supported */
3277
      return;
3278
 
3279
    default:
3280
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
3281
               "recognized: ignored\n", type);
3282
      put_str_packet ("E01");
3283
      return;
3284
    }
3285
}       /* rsp_insert_matchpoint () */
3286
 
3287
 
3288
/*---------------------------------------------------------------------------
3289
Setup the or32 to init state
3290
 
3291
---------------------------------------------------------------------------*/
3292
void setup_or32(void)
3293
{
3294
  uint32_t              temp_uint32;
3295
  // First set the chain 
3296
  err = gdb_set_chain(SC_REGISTER);     /* 4 Register Chain */
3297
  if(err > 0){
3298
    if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
3299
  }
3300
  if(gdb_read_reg(0x04, &temp_uint32)) printf("Error read from register\n");
3301
  if (DEBUG_GDB) printf("Read from chain 4 SC_REGISTER at add 0x00000004 = 0x%08x\n", temp_uint32 );
3302
 
3303
  if(gdb_write_reg(0x04, 0x00000001)) printf("Error write to register\n");
3304
  if (DEBUG_GDB) printf("Write to chain 4 SC_REGISTER at add 0x00000004 = 0x00000001\n");
3305
 
3306
  //    if(gdb_read_reg(0x04, &temp_uint32)) printf("Error read from register\n");
3307
  //    if (DEBUG_GDB) printf("Read from chain 4 SC_REGISTER at add 0x00000004 = 0x%08x\n", temp_uint32 );                      
3308
 
3309
  //    if(gdb_read_reg(0x04, &temp_uint32)) printf("Error read from register\n");
3310
  //    if (DEBUG_GDB) printf("Read from chain 4 SC_REGISTER at add 0x00000004 = 0x%08x\n", temp_uint32 );                      
3311
 
3312
  if(gdb_write_reg(0x00, 0x01000001)) printf("Error write to register\n");
3313
  if (DEBUG_GDB) printf("Write to chain 4 SC_REGISTER at add 0x00000000 = 0x01000001\n");
3314
}
3315
 
3316
// Function to check if the processor is stalled - if not then stall it.
3317
// this is useful in the event that GDB thinks the processor is stalled, but has, in fact
3318
// been hard reset on the board and is running.
3319
static void gdb_ensure_or1k_stalled()
3320
{
3321
  unsigned char stalled;
3322
  dbg_cpu0_read_ctrl(0, &stalled);
3323
  if ((stalled & 0x1) != 0x1)
3324
    {
3325
      if (DEBUG_GDB)
3326
        printf("Processor not stalled, like we thought\n");
3327
 
3328
      // Set the TAP controller to its OR1k chain
3329
      dbg_set_tap_ir(JI_DEBUG);
3330
      gdb_chain = -1;
3331
 
3332
      // Processor isn't stalled, contrary to what we though, so stall it
3333
      printf("Stalling or1k\n");
3334
      dbg_cpu0_write_ctrl(0, 0x01);      // stall or1k
3335
    }
3336
}
3337
 
3338
 
3339
int gdb_read_reg(uint32_t adr, uint32_t *data) {
3340
  switch (gdb_chain) {
3341
  case SC_RISC_DEBUG: return dbg_cpu0_read(adr, data) ? ERR_CRC : ERR_NONE;
3342
  case SC_REGISTER:   return dbg_cpu0_read_ctrl(adr, (unsigned char*)data) ?
3343
      ERR_CRC : ERR_NONE;
3344
  case SC_WISHBONE:   return dbg_wb_read32(adr, data) ? ERR_CRC : ERR_NONE;
3345
  case SC_TRACE:      *data = 0; return 0;
3346
  default:            return JTAG_PROXY_INVALID_CHAIN;
3347
  }
3348
}
3349
 
3350
int gdb_write_reg(uint32_t adr, uint32_t data) {
3351
  switch (gdb_chain) { /* remap registers, to be compatible with jp1 */
3352
  case SC_RISC_DEBUG: if (adr == JTAG_RISCOP) adr = 0x00;
3353
    return dbg_cpu0_write(adr, data) ? ERR_CRC : ERR_NONE;
3354
  case SC_REGISTER:   return dbg_cpu0_write_ctrl(adr, data) ? ERR_CRC : ERR_NONE;
3355
  case SC_WISHBONE:   return dbg_wb_write32(adr, data) ? ERR_CRC : ERR_NONE;
3356
  case SC_TRACE:      return 0;
3357
  default:            return JTAG_PROXY_INVALID_CHAIN;
3358
  }
3359
}
3360
 
3361
int gdb_read_block(uint32_t adr, uint32_t *data, int len) {
3362
  if (DEBUG_CMDS) printf("rb %d\n", gdb_chain);
3363
  switch (gdb_chain) {
3364
  case SC_WISHBONE:   return dbg_wb_read_block32(adr, data, len) ?
3365
      ERR_CRC : ERR_NONE;
3366
  default:            return JTAG_PROXY_INVALID_CHAIN;
3367
  }
3368
}
3369
 
3370
int gdb_write_block(uint32_t adr, uint32_t *data, int len) {
3371
  if (DEBUG_CMDS) printf("wb %d\n", gdb_chain);
3372
  switch (gdb_chain) {
3373
  case SC_WISHBONE:   return dbg_wb_write_block32(adr, data, len) ?
3374
      ERR_CRC : ERR_NONE;
3375
  default:            return JTAG_PROXY_INVALID_CHAIN;
3376
  }
3377
}
3378
 
3379
int gdb_set_chain(int chain) {
3380
  switch (chain) {
3381
  case SC_RISC_DEBUG:
3382
  case SC_REGISTER:
3383
  case SC_TRACE:
3384
  case SC_WISHBONE:   gdb_chain = chain;
3385
    return ERR_NONE;
3386
  default:            return JTAG_PROXY_INVALID_CHAIN;
3387
  }
3388
}
3389
 
3390
/* Added by CZ 24/05/01 */
3391
int GetServerSocket(const char* name, const char* proto, int port) {
3392
  struct servent *service;
3393
  struct protoent *protocol;
3394
  struct sockaddr_in sa;
3395
  struct hostent *hp;
3396
  int sockfd;
3397
  char myname[256];
3398
  //int flags; --changed to socklen_t for c++?! -- Julius
3399
  socklen_t flags;
3400
  char sTemp[256];
3401
 
3402
  /* First, get the protocol number of TCP */
3403
  if (!(protocol = getprotobyname(proto))) {
3404
    sprintf(sTemp, "Unable to load protocol \"%s\"", proto);
3405
    perror(sTemp);
3406
    return 0;
3407
  }
3408
  tcp_level = protocol->p_proto; /* Save for later */
3409
 
3410
  /* If we weren't passed a non standard port, get the port
3411
     from the services directory. */
3412
  if (!port && (service = getservbyname(name, protocol->p_name)))
3413
    port = ntohs(service->s_port);
3414
 
3415
  /* Create the socket using the TCP protocol */
3416
  if ((sockfd = socket(PF_INET, SOCK_STREAM, protocol->p_proto)) < 0) {
3417
    perror("Unable to create socket");
3418
    return 0;
3419
  }
3420
 
3421
  flags = 1;
3422
  if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
3423
                 (const char*)&flags, sizeof(int)) < 0) {
3424
    sprintf(sTemp, "Can not set SO_REUSEADDR option on socket %d", sockfd);
3425
    perror(sTemp);
3426
    close(sockfd);
3427
    return 0;
3428
  }
3429
 
3430
  /* The server should also be non blocking. Get the current flags. */
3431
  if(fcntl(sockfd, F_GETFL, &flags) < 0) {
3432
    sprintf(sTemp, "Unable to get flags for socket %d", sockfd);
3433
    perror(sTemp);
3434
    close(sockfd);
3435
    return 0;
3436
  }
3437
 
3438
  /* Set the nonblocking flag */
3439
  if(fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) {
3440
    sprintf(sTemp, "Unable to set flags for socket %d to value 0x%08x",
3441
                    sockfd, flags | O_NONBLOCK);
3442
    perror(sTemp);
3443
    close(sockfd);
3444
    return 0;
3445
  }
3446
 
3447
  /* Find out what our address is */
3448
  memset(&sa, 0, sizeof(struct sockaddr_in));
3449
  gethostname(myname, sizeof(myname));
3450
  if(!(hp = gethostbyname(myname))) {
3451
    perror("Unable to read hostname");
3452
    close(sockfd);
3453
    return 0;
3454
  }
3455
 
3456
  /* Bind our socket to the appropriate address */
3457
  sa.sin_family = hp->h_addrtype;
3458
  sa.sin_port = htons(port);
3459
  if(bind(sockfd, (struct sockaddr*)&sa, sizeof(struct sockaddr_in)) < 0) {
3460
    sprintf(sTemp, "Unable to bind socket %d to port %d", sockfd, port);
3461
    perror(sTemp);
3462
    close(sockfd);
3463
    return 0;
3464
  }
3465
  serverIP = sa.sin_addr.s_addr;
3466
  flags = sizeof(struct sockaddr_in);
3467
  if(getsockname(sockfd, (struct sockaddr*)&sa, &flags) < 0) {
3468
    sprintf(sTemp, "Unable to get socket information for socket %d", sockfd);
3469
    perror(sTemp);
3470
    close(sockfd);
3471
    return 0;
3472
  }
3473
  serverPort = ntohs(sa.sin_port);
3474
 
3475
  /* Set the backlog to 1 connections */
3476
  if(listen(sockfd, 1) < 0) {
3477
    sprintf(sTemp, "Unable to set backlog on socket %d to %d", sockfd, 1);
3478
    perror(sTemp);
3479
    close(sockfd);
3480
    return 0;
3481
  }
3482
 
3483
  return sockfd;
3484
}
3485
 
3486
//void HandleServerSocket(Boolean block) {
3487
void HandleServerSocket(void) {
3488
  struct pollfd fds[2];
3489
  int n;
3490
  uint32_t              temp_uint32;
3491
 
3492
 rebuild:
3493
  n = 0;
3494
  if(!server_fd && !gdb_fd) return;
3495
 
3496
  if(server_fd) {
3497
    fds[n].fd = server_fd;
3498
    fds[n].events = POLLIN;
3499
    fds[n++].revents = 0;
3500
  }
3501
  if(gdb_fd) {
3502
    fds[n].fd = gdb_fd;
3503
    fds[n].events = POLLIN;
3504
    fds[n++].revents = 0;
3505
  }
3506
 
3507
  while(1) {
3508
    switch(poll(fds, n, -1)) {
3509
    case 0:
3510
    case -1:
3511
      if(errno == EINTR) continue;
3512
      perror("poll");
3513
      server_fd = 0;
3514
      return;
3515
    default:
3516
      /* Make sure to handle the gdb port first! */
3517
      if (gdb_fd && (fds[0].revents && !server_fd || fds[1].revents && server_fd))
3518
        {
3519
          int revents = server_fd ? fds[1].revents : fds[0].revents;
3520
          if (revents & POLLIN){
3521
            /* If we have an unacknowledged exception tell the GDB client. If this
3522
               exception was a trap due to a memory breakpoint, then adjust the NPC. */
3523
            if (rsp.client_waiting)
3524
              {
3525
                err = gdb_read_reg(PPC_CPU_REG_ADD, &temp_uint32);
3526
                if(err) printf("Error read from PPC register\n");
3527
                if ((TARGET_SIGNAL_TRAP == rsp.sigval) &&
3528
                    (NULL != mp_hash_lookup (BP_MEMORY, temp_uint32)))
3529
                  {
3530
                    set_npc (temp_uint32);
3531
                  }
3532
 
3533
                rsp_report_exception();
3534
                rsp.client_waiting = 0;          /* No longer waiting */
3535
              }
3536
            GDBRequest();
3537
          }
3538
          else {/* Error Occurred */
3539
            printf("\n%sSocket closed.\n",printTime());
3540
            //fprintf(stderr, 
3541
            //"Received flags 0x%08x on gdb socket. Shutting down.\n", revents);
3542
            close(gdb_fd);
3543
            gdb_fd = 0;
3544
          }
3545
        }
3546
 
3547
      // Go to blocking accept() instead of looping around through poll(), 
3548
      // takes a loot of CPU resources and it doesn't work when 
3549
      // reconnecting... Jonas Rosén
3550
      if(!gdb_fd)
3551
      {
3552
                          JTAGRequest();
3553
                          rsp.client_waiting = 0;                /* No longer waiting */
3554
                          goto rebuild;
3555
      }
3556
 
3557
      if(fds[0].revents && server_fd) {
3558
        if(fds[0].revents & POLLIN) {
3559
          JTAGRequest();
3560
          rsp.client_waiting = 0;                /* No longer waiting */
3561
          goto rebuild;
3562
        } else { /* Error Occurred */
3563
                          fprintf(stderr,
3564
                                  "Received flags 0x%08x on server. Shutting down.\n",
3565
                                  fds[0].revents);
3566
                          close(server_fd);
3567
                          server_fd = 0;
3568
                          serverPort = 0;
3569
                          serverIP = 0;
3570
                          return;
3571
                                }
3572
                }
3573
      break;
3574
    } /* End of switch statement */
3575
  } /* End of while statement */
3576
}
3577
 
3578
void JTAGRequest(void) {
3579
  struct sockaddr_in sa;
3580
  struct sockaddr* addr = (struct sockaddr*)&sa;
3581
  //int n = sizeof(struct sockaddr_in); --changed to socklen_t from int type
3582
  socklen_t n = sizeof(struct sockaddr_in);
3583
  int fd = accept(server_fd, addr, &n);
3584
  int on_off = 0; /* Turn off Nagel's algorithm on the socket */
3585
  int flags;
3586
  char sTemp[256];
3587
  if (DEBUG_GDB) printf("JTAGRequest\n");
3588
 
3589
  if(fd < 0) {
3590
    /* This is valid, because a connection could have started,
3591
       and then terminated due to a protocol error or user
3592
       initiation before the accept could take place. */
3593
    if(errno != EWOULDBLOCK && errno != EAGAIN) {
3594
      perror("accept");
3595
      close(server_fd);
3596
      server_fd = 0;
3597
      serverPort = 0;
3598
      serverIP = 0;
3599
    }
3600
    return;
3601
  }
3602
 
3603
  if(gdb_fd) {
3604
    close(fd);
3605
    return;
3606
  }
3607
 
3608
  if(fcntl(fd, F_GETFL, &flags) < 0) {
3609
    sprintf(sTemp, "Unable to get flags for gdb socket %d", fd);
3610
    perror(sTemp);
3611
    close(fd);
3612
    return;
3613
  }
3614
 
3615
  /* Rene
3616
  if(fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
3617
    sprintf(sTemp, "Unable to set flags for gdb socket %d to value 0x%08x",
3618
      fd, flags | O_NONBLOCK);
3619
    perror(sTemp);
3620
    close(fd);
3621
    return;
3622
  }     Rene */
3623
 
3624
  if(setsockopt(fd, tcp_level, TCP_NODELAY, &on_off, sizeof(int)) < 0) {
3625
    sprintf(sTemp, "Unable to disable Nagel's algorithm for socket %d.\nsetsockopt", fd);
3626
    perror(sTemp);
3627
    close(fd);
3628
    return;
3629
  }
3630
 
3631
  printf("\n%sConnection established from %s on port %d\n", printTime(),inet_ntoa(sa.sin_addr),ntohs(sa.sin_port));
3632
  gdb_fd = fd;
3633
}
3634
 
3635
 
3636
/*---------------------------------------------------------------------------
3637
* Decode the GDB command.
3638
*
3639
*---------------------------------------------------------------------------*/
3640
static void GDBRequest(void) {
3641
  JTAGProxyWriteMessage msg_write;
3642
  JTAGProxyReadMessage msg_read;
3643
  JTAGProxyChainMessage msg_chain;
3644
  JTAGProxyWriteResponse resp_write;
3645
  JTAGProxyReadResponse resp_read;
3646
  JTAGProxyChainResponse resp_chain;
3647
  JTAGProxyBlockWriteMessage *msg_bwrite;
3648
  JTAGProxyBlockReadMessage msg_bread;
3649
  JTAGProxyBlockWriteResponse resp_bwrite;
3650
  JTAGProxyBlockReadResponse *resp_bread;
3651
  char *p_buf;
3652
  uint32_t command;
3653
  uint32_t length;
3654
  int len, i;
3655
 
3656
  /* First, we must read the incomming command */
3657
  if(gdb_read(&command, sizeof(uint32_t)) < 0) {
3658
    client_close ('1');
3659
    return;
3660
  }
3661
  command = ntohl(command);
3662
 
3663
  if(gdb_read(&length, sizeof(uint32_t)) < 0) {
3664
    client_close ('2');
3665
    return;
3666
  }
3667
  length = ntohl(length);
3668
  if (DEBUG_GDB) printf("\n%s-----------------------------------------------------\nCommand %d Length %d ", printTime(), command, length);
3669
 
3670
  if (DEBUG_GDB){
3671
  switch(command){
3672
    case JTAG_COMMAND_READ:
3673
            printf("JTAG_COMMAND_READ       \n");
3674
            break;
3675
    case JTAG_COMMAND_WRITE:
3676
            printf("JTAG_COMMAND_WRITE      \n");
3677
            break;
3678
    case JTAG_COMMAND_BLOCK_READ:
3679
            printf("JTAG_COMMAND_BLOCK_READ \n");
3680
            break;
3681
    case JTAG_COMMAND_BLOCK_WRITE:
3682
            printf("JTAG_COMMAND_BLOCK_WRITE\n");
3683
            break;
3684
    case JTAG_COMMAND_CHAIN:
3685
            printf("JTAG_COMMAND_CHAIN      \n");
3686
            break;
3687
                }
3688
        }
3689
 
3690
  /* Now, verify the protocol and implement the command */
3691
  switch(command) {
3692
    case JTAG_COMMAND_WRITE:
3693
      if(length != sizeof(msg_write) - 8) {
3694
        ProtocolClean(length, JTAG_PROXY_PROTOCOL_ERROR);
3695
        return;
3696
      }
3697
      p_buf = (char*)&msg_write;
3698
      if(gdb_read(&p_buf[8], length) < 0) {
3699
        client_close ('3');
3700
        return;
3701
      }
3702
      msg_write.address = ntohl(msg_write.address);
3703
      msg_write.data_H = ntohl(msg_write.data_H);
3704
      msg_write.data_L = ntohl(msg_write.data_L);
3705
      err = gdb_write_reg(msg_write.address, msg_write.data_L);
3706
      resp_write.status = htonl(err);
3707
      if (DEBUG_GDB) printf("Write Reg to Chain %d at add 0x%08x -> H-Data 0x%08x L-Data 0x%08x Error %d",
3708
        gdb_chain, msg_write.address, msg_write.data_H, msg_write.data_L, err);fflush (stdout);
3709
      if(gdb_write(&resp_write, sizeof(resp_write)) < 0) {
3710
        client_close ('4');
3711
        return;
3712
      }
3713
      break;
3714
    case JTAG_COMMAND_READ:
3715
      if(length != sizeof(msg_read) - 8) {
3716
        ProtocolClean(length, JTAG_PROXY_PROTOCOL_ERROR);
3717
        return;
3718
      }
3719
      p_buf = (char*)&msg_read;
3720
      if(gdb_read(&p_buf[8], length) < 0) {
3721
        client_close ('5');
3722
        return;
3723
      }
3724
      msg_read.address = ntohl(msg_read.address);
3725
      err = gdb_read_reg(msg_read.address, (uint32_t *)&resp_read.data_L);
3726
      if (DEBUG_GDB) printf("Read Reg from Chain %d at add 0x%08x", gdb_chain, msg_read.address);
3727
      resp_read.status = htonl(err);
3728
      resp_read.data_H = 0;
3729
      resp_read.data_L = htonl(resp_read.data_L);
3730
      if(gdb_write(&resp_read, sizeof(resp_read)) < 0) {
3731
        client_close ('6');
3732
        return;
3733
        }
3734
      if (DEBUG_GDB) printf(" --> Data 0x%08x Error %d\n", htonl(resp_read.data_L), err);fflush (stdout);
3735
      break;
3736
    case JTAG_COMMAND_BLOCK_WRITE:
3737
      if(length < sizeof(JTAGProxyBlockWriteMessage)-8) {
3738
        ProtocolClean(length, JTAG_PROXY_PROTOCOL_ERROR);
3739
        return;
3740
      }
3741
      if(!(p_buf = (char*)malloc(8+length))) {
3742
        ProtocolClean(length, JTAG_PROXY_OUT_OF_MEMORY);
3743
        return;
3744
      }
3745
      msg_bwrite = (JTAGProxyBlockWriteMessage*)p_buf;
3746
      if(gdb_read(&p_buf[8], length) < 0) {
3747
        client_close ('5');
3748
        free(p_buf);
3749
        return;
3750
      }
3751
      msg_bwrite->address = ntohl(msg_bwrite->address);
3752
      msg_bwrite->nRegisters = ntohl(msg_bwrite->nRegisters);
3753
      if (DEBUG_GDB) printf("Block Write to Chain %d start add 0x%08x Write %d (32 bit words):\n\n", gdb_chain, msg_bwrite->address, msg_bwrite->nRegisters);
3754
      for(i=0;i<msg_bwrite->nRegisters;i++) {
3755
        msg_bwrite->data[i] = ntohl(msg_bwrite->data[i]);
3756
                                if (DEBUG_GDB_BLOCK_DATA){
3757
                                  if ((i % 4) == 0)      printf("Add 0x%08x   Data 0x%08x  ", msg_bwrite->address + (i * 4), msg_bwrite->data[i]);
3758
                          else if ((i % 4) == 3) printf("0x%08x\n", msg_bwrite->data[i]);
3759
                                  else                   printf("0x%08x  ", msg_bwrite->data[i]);
3760
 
3761
                                        // add a new line on the last data, but not if it is the last one in the colum 
3762
                                        if ((msg_bwrite->nRegisters - i == 1) && (i % 4) < 3) printf("\n");
3763
                                }
3764
      }
3765
      err = gdb_write_block(msg_bwrite->address, (uint32_t*)msg_bwrite->data, msg_bwrite->nRegisters * 4);
3766
      if (DEBUG_GDB) printf("Error %x\n", err);fflush (stdout);
3767
      resp_bwrite.status = htonl(err);
3768
      free(p_buf);
3769
      msg_bwrite = (JTAGProxyBlockWriteMessage *)NULL;
3770
      p_buf = (char *)msg_bwrite;
3771
      if(gdb_write(&resp_bwrite, sizeof(resp_bwrite)) < 0) {
3772
        client_close ('4');
3773
        return;
3774
      }
3775
      break;
3776
    case JTAG_COMMAND_BLOCK_READ:
3777
      if(length != sizeof(msg_bread) - 8) {
3778
        ProtocolClean(length, JTAG_PROXY_PROTOCOL_ERROR);
3779
        return;
3780
      }
3781
      p_buf = (char*)&msg_bread;
3782
      if(gdb_read(&p_buf[8], length) < 0) {
3783
        client_close ('5');
3784
        return;
3785
      }
3786
      msg_bread.address = ntohl(msg_bread.address);
3787
      msg_bread.nRegisters = ntohl(msg_bread.nRegisters);
3788
      if (DEBUG_GDB) printf("Block Read from Chain %d start add 0x%08x Read %d (32 bit words):\n\n", gdb_chain, msg_bread.address, msg_bread.nRegisters);
3789
      len = sizeof(JTAGProxyBlockReadResponse) + 4*(msg_bread.nRegisters-1);
3790
      if(!(p_buf = (char*)malloc(len))) {
3791
        ProtocolClean(0, JTAG_PROXY_OUT_OF_MEMORY);
3792
        return;
3793
      }
3794
      resp_bread = (JTAGProxyBlockReadResponse*)p_buf;
3795
      err = gdb_read_block(msg_bread.address, (uint32_t*)resp_bread->data, msg_bread.nRegisters * 4);
3796
      for(i=0;i<msg_bread.nRegisters;i++) {
3797
        /* Read previous, address next one. */
3798
        resp_bread->data[i] = htonl(resp_bread->data[i]);
3799
                if (DEBUG_GDB_BLOCK_DATA){
3800
                  if ((i % 4) == 0)      printf("Add 0x%08x   Data 0x%08x  ", msg_bread.address + (i * 4), htonl(resp_bread->data[i]));
3801
          else if ((i % 4) == 3) printf("0x%08x\n", htonl(resp_bread->data[i]));
3802
                  else                   printf("0x%08x  ", htonl(resp_bread->data[i]));
3803
                }
3804
                // add a new line on the last data, but not if it is the last one in the colum 
3805
                if ((msg_bread.nRegisters - i == 1) && (i % 4) < 3) printf("\n");
3806
      }
3807
      resp_bread->status = htonl(err);
3808
      resp_bread->nRegisters = htonl(msg_bread.nRegisters);
3809
      if (DEBUG_GDB) printf("\nError %x\n", err);fflush (stdout);
3810
      if(gdb_write(resp_bread, len) < 0) {
3811
        client_close ('6');
3812
        free(p_buf);
3813
        return;
3814
      }
3815
      free(p_buf);
3816
      resp_bread = (JTAGProxyBlockReadResponse *)NULL;
3817
      p_buf = (char *)resp_bread;
3818
      break;
3819
    case JTAG_COMMAND_CHAIN:
3820
      if(length != sizeof(msg_chain) - 8) {
3821
        ProtocolClean(length, JTAG_PROXY_PROTOCOL_ERROR);
3822
        return;
3823
      }
3824
      p_buf = (char*)&msg_chain;
3825
      if(gdb_read(&p_buf[8], sizeof(msg_chain)-8) < 0) {
3826
        client_close ('7');
3827
        return;
3828
      }
3829
      msg_chain.chain = htonl(msg_chain.chain);
3830
      err = gdb_set_chain(msg_chain.chain);
3831
      resp_chain.status = htonl(err);
3832
      if (DEBUG_GDB){
3833
              switch(msg_chain.chain){
3834
                                        case SC_GLOBAL:      /* 0 Global BS Chain */
3835
                                                printf("Set Chain %d Global BS Chain  Error %x\n", msg_chain.chain, err);
3836
                                                break;
3837
                                        case SC_RISC_DEBUG:  /* 1 RISC Debug Interface chain */
3838
                                                printf("Set Chain %d RISC Debug Interface chain  Error %x\n", msg_chain.chain, err);
3839
                                                break;
3840
                                        case SC_RISC_TEST:   /* 2 RISC Test Chain */
3841
                                                printf("Set Chain %d RISC Test Chain  Error %x\n", msg_chain.chain, err);
3842
                                                break;
3843
                                        case SC_TRACE:       /* 3 Trace Chain */
3844
                                                printf("Set Chain %d Trace Chain  Error %x\n", msg_chain.chain, err);
3845
                                                break;
3846
                                        case SC_REGISTER:    /* 4 Register Chain */
3847
                                                printf("Set Chain %d Register Chain  Error %x\n", msg_chain.chain, err);
3848
                                                break;
3849
                                        case SC_WISHBONE:    /* 5 Memory chain */
3850
                                                printf("Set Chain %d Wishbone Memory chain  Error %x\n", msg_chain.chain, err);
3851
                                                break;
3852
                                        case SC_BLOCK:       /* 6 Block Chains */
3853
                                                printf("Set Chain %d Block Chains  Error %x\n", msg_chain.chain, err);
3854
                                                break;
3855
                                        default:                                                 /* Invalid chain */
3856
                                                printf("Set Chain %d Invalid chain  Error %x\n", msg_chain.chain, err);
3857
                                                break;
3858
              }
3859
        fflush (stdout);
3860
      }
3861
      if(gdb_write(&resp_chain, sizeof(resp_chain)) < 0) {
3862
        client_close ('8');
3863
        return;
3864
      }
3865
      break;
3866
    default:
3867
      perror("Unknown JTAG command.");fflush (stdout);
3868
      ProtocolClean(length, JTAG_PROXY_COMMAND_NOT_IMPLEMENTED);
3869
      break;
3870
  }
3871
}
3872
 
3873
static void ProtocolClean(int length, int32_t err) {
3874
  char buffer[4096];
3875
 
3876
  err = htonl(err);
3877
  if((gdb_read(buffer, length) < 0) || (gdb_write(&err, sizeof(err)) < 0) && gdb_fd) {
3878
    perror("gdb socket - 9");
3879
    close(gdb_fd);
3880
    gdb_fd = 0;
3881
  }
3882
}
3883
 
3884
static int gdb_write(void* p_buf, int len) {
3885
  int n;
3886
  char* w_buf = (char*)p_buf;
3887
  struct pollfd block;
3888
 
3889
  while(len) {
3890
    if((n = write(gdb_fd, w_buf, len)) < 0) {
3891
      switch(errno) {
3892
        case EWOULDBLOCK: /* or EAGAIN */
3893
          /* We've been called on a descriptor marked
3894
             for nonblocking I/O. We better simulate
3895
             blocking behavior. */
3896
          block.fd = gdb_fd;
3897
          block.events = POLLOUT;
3898
          block.revents = 0;
3899
          poll(&block, 1, -1);
3900
          continue;
3901
        case EINTR:
3902
          continue;
3903
        case EPIPE:
3904
          close(gdb_fd);
3905
          gdb_fd = 0;
3906
          return -1;
3907
        default:
3908
          return -1;
3909
        }
3910
      } else {
3911
        len -= n;
3912
        w_buf += n;
3913
      }
3914
  }
3915
  return 0;
3916
}
3917
 
3918
static int gdb_read(void* p_buf, int len) {
3919
  int n;
3920
  char* r_buf = (char*)p_buf;
3921
  struct pollfd block;
3922
 
3923
  while(len) {
3924
    if((n = read(gdb_fd, r_buf, len)) < 0) {
3925
      switch(errno) {
3926
        case EWOULDBLOCK: /* or EAGAIN */
3927
          /* We've been called on a descriptor marked
3928
       for nonblocking I/O. We better simulate
3929
       blocking behavior. */
3930
          block.fd = gdb_fd;
3931
          block.events = POLLIN;
3932
          block.revents = 0;
3933
          poll(&block, 1, -1);
3934
          continue;
3935
        case EINTR:
3936
          continue;
3937
        default:
3938
          return -1;
3939
        }
3940
    } else if(n == 0) {
3941
      close(gdb_fd);
3942
      gdb_fd = 0;
3943
      return -1;
3944
    } else {
3945
      len -= n;
3946
      r_buf += n;
3947
    }
3948
  }
3949
  return 0;
3950
}
3951
 
3952
 
3953
/*****************************************************************************
3954
* Close the connection to the client if it is open
3955
******************************************************************************/
3956
static void client_close (char err)
3957
{
3958
  if(gdb_fd) {
3959
    perror("gdb socket - " + err);
3960
    close(gdb_fd);
3961
    gdb_fd = 0;
3962
  }
3963
}       /* client_close () */
3964
 
3965
 
3966
/*---------------------------------------------------------------------------*/
3967
/* Swap a buffer of 4-byte from 1234 to 4321
3968
 
3969
   parameter[in]  p_buf and len
3970
   parameter[out] none                                                                                                                                                                                                                   */
3971
/*---------------------------------------------------------------------------*/
3972
static void swap_buf(char* p_buf, int len)
3973
{
3974
        int temp;
3975
        int n = 0;
3976
 
3977
  if (len > 2)
3978
  {
3979
    while(n < len){
3980
        // swap 0 and 3
3981
        temp = p_buf[n];
3982
                        p_buf[n] = p_buf[n + 3];
3983
                        p_buf[n + 3] = temp;
3984
        // swap 1 and 2
3985
        temp = p_buf[n + 1];
3986
                        p_buf[n + 1] = p_buf[n + 2];
3987
                        p_buf[n + 2] = temp;
3988
 
3989
                        n += 4;
3990
    }
3991
        }
3992
}
3993
 
3994
 
3995
/*---------------------------------------------------------------------------*/
3996
/*!Set the stall state of the processor
3997
 
3998
   @param[in] state  If non-zero stall the processor.                        */
3999
/*---------------------------------------------------------------------------*/
4000
static void
4001
set_stall_state (int state)
4002
{
4003
 
4004
  if(state == 0)
4005
    {
4006
      err = dbg_cpu0_write_ctrl(0, 0);     /* unstall or1k */
4007
      stallState = UNSTALLED;
4008
      npcIsCached = 0;
4009
      rsp.sigval = TARGET_SIGNAL_NONE;
4010
    }
4011
  else
4012
    {
4013
      err = dbg_cpu0_write_ctrl(0, 0x01);                                 /* stall or1k */
4014
      stallState = STALLED;
4015
    }
4016
 
4017
  if(err > 0 && DEBUG_GDB)printf("Error %d in set_stall_state Stall state = %d\n", err, state);
4018
 
4019
}       /* set_stall_state () */
4020
 
4021
 
4022
/*---------------------------------------------------------------------------*/
4023
/*!Close down the connection with GDB in the event of a kill signal
4024
 
4025
 */
4026
/*---------------------------------------------------------------------------*/
4027
void gdb_close()
4028
{
4029
  if (gdb_fd) close(gdb_fd);
4030
  // Maybe do other things here!
4031
}

powered by: WebSVN 2.1.0

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