OpenCores
URL https://opencores.org/ocsvn/openrisc_2011-10-31/openrisc_2011-10-31/trunk

Subversion Repositories openrisc_2011-10-31

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

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

powered by: WebSVN 2.1.0

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