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

Subversion Repositories openrisc

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

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

powered by: WebSVN 2.1.0

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