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

Subversion Repositories openrisc_me

[/] [openrisc/] [trunk/] [or_debug_proxy/] [src/] [gdb.c] - Blame information for rev 40

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

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

powered by: WebSVN 2.1.0

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