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

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [orpsocv2/] [bench/] [verilog/] [vpi/] [c/] [gdb.c] - Blame information for rev 40

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

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

powered by: WebSVN 2.1.0

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