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 831

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 425 julius
  if (0 == strcmp ("qAttached", p_buf->data))
2808 40 julius
    {
2809 425 julius
      /* We are always attaching to an existing process with the bare metal
2810
         embedded system. */
2811
      put_str_packet ("1");
2812
    }
2813
  else if (0 == strcmp ("qC", p_buf->data))
2814
    {
2815 40 julius
      /* Return the current thread ID (unsigned hex). A null response
2816
         indicates to use the previously selected thread. Since we do not
2817
         support a thread concept, this is the appropriate response. */
2818
      put_str_packet ("");
2819
    }
2820
  else if (0 == strncmp ("qCRC", p_buf->data, strlen ("qCRC")))
2821
    {
2822
      /* Return CRC of memory area */
2823
      fprintf (stderr, "Warning: RSP CRC query not supported\n");
2824
      put_str_packet ("E01");
2825
    }
2826
  else if (0 == strcmp ("qfThreadInfo", p_buf->data))
2827
    {
2828
      /* Return info about active threads. We return just '-1' */
2829
      put_str_packet ("m-1");
2830
    }
2831
  else if (0 == strcmp ("qsThreadInfo", p_buf->data))
2832
    {
2833
      /* Return info about more active threads. We have no more, so return the
2834
         end of list marker, 'l' */
2835
      put_str_packet ("l");
2836
    }
2837
  else if (0 == strncmp ("qGetTLSAddr:", p_buf->data, strlen ("qGetTLSAddr:")))
2838
    {
2839
      /* We don't support this feature */
2840
      put_str_packet ("");
2841
    }
2842
  else if (0 == strncmp ("qL", p_buf->data, strlen ("qL")))
2843
    {
2844
      /* Deprecated and replaced by 'qfThreadInfo' */
2845
      fprintf (stderr, "Warning: RSP qL deprecated: no info returned\n");
2846
      put_str_packet ("qM001");
2847
    }
2848
  else if (0 == strcmp ("qOffsets", p_buf->data))
2849
    {
2850
      /* Report any relocation */
2851
      put_str_packet ("Text=0;Data=0;Bss=0");
2852
    }
2853
  else if (0 == strncmp ("qP", p_buf->data, strlen ("qP")))
2854
    {
2855
      /* Deprecated and replaced by 'qThreadExtraInfo' */
2856
      fprintf (stderr, "Warning: RSP qP deprecated: no info returned\n");
2857
      put_str_packet ("");
2858
    }
2859
  else if (0 == strncmp ("qRcmd,", p_buf->data, strlen ("qRcmd,")))
2860
    {
2861
      /* This is used to interface to commands to do "stuff" */
2862
      rsp_command (p_buf);
2863
    }
2864
  else if (0 == strncmp ("qSupported", p_buf->data, strlen ("qSupported")))
2865
    {
2866
      /* Report a list of the features we support. For now we just ignore any
2867
                                 supplied specific feature queries, but in the future these may be
2868
                                 supported as well. Note that the packet size allows for 'G' + all the
2869
                                 registers sent to us, or a reply to 'g' with all the registers and an
2870
                                 EOS so the buffer is a well formed string. */
2871
      setup_or32();     // setup cpu
2872
      char  reply[GDB_BUF_MAX];
2873
      sprintf (reply, "PacketSize=%x", GDB_BUF_MAX);
2874
      put_str_packet (reply);
2875
    }
2876
  else if (0 == strncmp ("qSymbol:", p_buf->data, strlen ("qSymbol:")))
2877
    {
2878
      /* Offer to look up symbols. Nothing we want (for now). TODO. This just
2879
         ignores any replies to symbols we looked up, but we didn't want to
2880
         do that anyway! */
2881
      put_str_packet ("OK");
2882
    }
2883
  else if (0 == strncmp ("qThreadExtraInfo,", p_buf->data,
2884
                         strlen ("qThreadExtraInfo,")))
2885
    {
2886
      /* Report that we are runnable, but the text must be hex ASCI
2887
         digits. For now do this by steam, reusing the original packet */
2888
      sprintf (p_buf->data, "%02x%02x%02x%02x%02x%02x%02x%02x%02x",
2889
               'R', 'u', 'n', 'n', 'a', 'b', 'l', 'e', 0);
2890
      p_buf->len = strlen (p_buf->data);
2891
      put_packet (p_buf);
2892
    }
2893 425 julius
  else if (0 == strncmp ("qTStatus", p_buf->data, strlen ("qTStatus")))
2894
    {
2895
      /* We don't support tracing, so return empty packet. */
2896
      put_str_packet ("");
2897
    }
2898 40 julius
  else if (0 == strncmp ("qXfer:", p_buf->data, strlen ("qXfer:")))
2899
    {
2900
      /* For now we support no 'qXfer' requests, but these should not be
2901
         expected, since they were not reported by 'qSupported' */
2902
      fprintf (stderr, "Warning: RSP 'qXfer' not supported: ignored\n");
2903
      put_str_packet ("");
2904
    }
2905
  else
2906
    {
2907
      fprintf (stderr, "Unrecognized RSP query: ignored\n");
2908
    }
2909
}       /* rsp_query () */
2910
 
2911
 
2912
/*---------------------------------------------------------------------------*/
2913
/*!Handle a RSP qRcmd request
2914
 
2915
  The actual command follows the "qRcmd," in ASCII encoded to hex
2916
 
2917
   @param[in] p_buf  The request in full                                       */
2918
/*---------------------------------------------------------------------------*/
2919
static void
2920
rsp_command (struct rsp_buf *p_buf)
2921
{
2922
  char  cmd[GDB_BUF_MAX];
2923
  unsigned int      regno;
2924
  uint32_t              temp_uint32;
2925
 
2926
  hex2ascii (cmd, &(p_buf->data[strlen ("qRcmd,")]));
2927
 
2928
  /* Work out which command it is */
2929
  if (0 == strncmp ("readspr ", cmd, strlen ("readspr")))
2930
  {
2931
    /* Parse and return error if we fail */
2932
    if( 1 != sscanf (cmd, "readspr %4x", &regno))
2933
      {
2934
        fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n", cmd);
2935
        put_str_packet ("E01");
2936
        return;
2937
      }
2938
 
2939
    /* SPR out of range */
2940
    if (regno > MAX_SPRS)
2941
      {
2942
        fprintf (stderr, "Warning: qRcmd readspr %x too large: ignored\n",
2943
                 regno);
2944
        put_str_packet ("E01");
2945
        return;
2946
      }
2947
 
2948
    /* Construct the reply */
2949
 
2950
    // Make sure the processor is stalled
2951
    gdb_ensure_or1k_stalled();
2952
 
2953
    // First set the chain 
2954
    gdb_set_chain(SC_RISC_DEBUG);       /* 1 RISC Debug Interface chain */
2955
 
2956 49 julius
    /* special case for NPC */
2957 40 julius
    if(regno == NPC_CPU_REG_ADD)
2958
      temp_uint32 = get_npc();
2959 49 julius
    /* Also special case for debug group (group 6) registers */
2960
    else if (((regno >> OR1K_SPG_SIZE_BITS) & 0xff) == OR1K_SPG_DEBUG)
2961
      {
2962
        if (dbg_regs_cache_dirty == -1) // Regs invalid, get them
2963
          get_debug_registers();
2964
 
2965
        uint32_t * dbg_reg_array = (uint32_t *) &or1k_dbg_group_regs_cache;
2966
        temp_uint32 = dbg_reg_array[(regno & 0xff)];
2967
        dbg_regs_cache_dirty = 0;
2968
      }
2969 40 julius
    else
2970
      {
2971
        err = gdb_read_reg(regno, &temp_uint32);
2972
        if(err > 0){
2973
          if (DEBUG_GDB) printf("Error %d in rsp_command at reg. %x \n", err, regno);
2974
        }
2975
        else{
2976
          reg2hex (temp_uint32, cmd);
2977
          if (DEBUG_GDB) printf("Error %d Command readspr Read reg. %x = 0x%08x\n", err, regno, temp_uint32);
2978
        }
2979
      }
2980
 
2981
    // pack the result into the buffer to send back
2982
    sprintf (cmd, "%8x", (unsigned int)temp_uint32);
2983
    ascii2hex (p_buf->data, cmd);
2984
    p_buf->len = strlen (p_buf->data);
2985
    put_packet (p_buf);
2986
  }
2987
  else if (0 == strncmp ("writespr ", cmd, strlen ("writespr")))
2988
    {
2989
      unsigned int       regno;
2990
      uint32_t  val;
2991
 
2992
      /* Parse and return error if we fail */
2993
      if( 2 != sscanf (cmd, "writespr %4x %8x", &regno, &val))
2994
        {
2995
          fprintf (stderr, "Warning: qRcmd %s not recognized: ignored\n",
2996
                   cmd);
2997
          put_str_packet ("E01");
2998
          return;
2999
        }
3000
 
3001
      /* SPR out of range */
3002
      if (regno > MAX_SPRS)
3003
        {
3004
          fprintf (stderr, "Warning: qRcmd writespr %x too large: ignored\n",
3005
                   regno);
3006
          put_str_packet ("E01");
3007
          return;
3008
        }
3009
 
3010
      // Make sure the processor is stalled
3011
      gdb_ensure_or1k_stalled();
3012
 
3013
      // First set the chain 
3014
      gdb_set_chain(SC_RISC_DEBUG);     /* 1 RISC Debug Interface chain */
3015
 
3016
      /* set the relevant register */
3017
      // special case for NPC
3018
      if(regno == NPC_CPU_REG_ADD)
3019
        set_npc(val);
3020 49 julius
      /* Also special case for debug group (group 6) registers */
3021
      else if (((regno >> OR1K_SPG_SIZE_BITS) & 0xff) == OR1K_SPG_DEBUG)
3022
        {
3023
          if (dbg_regs_cache_dirty == -1) // Regs invalid, get them
3024
            get_debug_registers();
3025
 
3026
          uint32_t * dbg_reg_array = (uint32_t *) &or1k_dbg_group_regs_cache;
3027
          dbg_reg_array[(regno & 0xff)] = val;
3028
          dbg_regs_cache_dirty = 1;
3029
        }
3030 40 julius
      else
3031
        {
3032
 
3033
          err = gdb_write_reg(regno, val);
3034
          if(err > 0){
3035
            if (DEBUG_GDB) printf("Error %d in rsp_command write Reg. %x = 0x%08x\n", err, regno, val);
3036
            put_str_packet ("E01");
3037
            return;
3038
          }
3039
          else{
3040
            if (DEBUG_GDB) printf("Error %d Command writespr Write reg. %x = 0x%08x\n", err, regno, val);
3041
          }
3042
        }
3043
      put_str_packet ("OK");
3044
    }
3045
}       /* rsp_command () */
3046
 
3047
 
3048
/*---------------------------------------------------------------------------*/
3049
/*!Handle a RSP set request
3050
 
3051
   @param[in] p_buf  The request                                               */
3052
/*---------------------------------------------------------------------------*/
3053
static void
3054
rsp_set (struct rsp_buf *p_buf)
3055
{
3056
  if (0 == strncmp ("QPassSignals:", p_buf->data, strlen ("QPassSignals:")))
3057
    {
3058
      /* Passing signals not supported */
3059
      put_str_packet ("");
3060
    }
3061
  else if ((0 == strncmp ("QTDP",    p_buf->data, strlen ("QTDP")))   ||
3062
           (0 == strncmp ("QFrame",  p_buf->data, strlen ("QFrame"))) ||
3063
           (0 == strcmp  ("QTStart", p_buf->data))                    ||
3064
           (0 == strcmp  ("QTStop",  p_buf->data))                    ||
3065
           (0 == strcmp  ("QTinit",  p_buf->data))                    ||
3066
           (0 == strncmp ("QTro",    p_buf->data, strlen ("QTro"))))
3067
    {
3068
      /* All tracepoint features are not supported. This reply is really only
3069
         needed to 'QTDP', since with that the others should not be
3070
         generated. */
3071
      put_str_packet ("");
3072
    }
3073
  else
3074
    {
3075
      fprintf (stderr, "Unrecognized RSP set request: ignored\n");
3076
    }
3077
}       /* rsp_set () */
3078
 
3079
 
3080
/*---------------------------------------------------------------------------*/
3081
/*!Handle a RSP restart request
3082
 
3083
   For now we just put the program counter back to the one used with the last
3084
   vRun request. There is no point in unstalling the processor, since we'll
3085
   never get control back.                                                   */
3086
/*---------------------------------------------------------------------------*/
3087
static void
3088
rsp_restart (void)
3089
{
3090
  // Make sure the processor is stalled
3091
  gdb_ensure_or1k_stalled();
3092
 
3093
  // First set the chain 
3094
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
3095
  if(err > 0){
3096 49 julius
    if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
3097 40 julius
    put_str_packet ("E01");
3098 49 julius
    return;
3099
  }
3100
 
3101 40 julius
  /* Set NPC to reset vector 0x100 */
3102
  set_npc(rsp.start_addr);
3103 49 julius
 
3104 40 julius
}       /* rsp_restart () */
3105
 
3106
 
3107
/*---------------------------------------------------------------------------*/
3108
/*!Handle a RSP step request
3109
 
3110
   Parse the command to see if there is an address. Uses the underlying
3111
   generic step function, with EXCEPT_NONE.
3112
 
3113
   @param[in] p_buf  The full step packet                          */
3114
/*---------------------------------------------------------------------------*/
3115
static void
3116
rsp_step (struct rsp_buf *p_buf)
3117
{
3118
  uint32_t  addr;               /* The address to step from, if any */
3119
 
3120
  // Make sure the processor is stalled
3121
  gdb_ensure_or1k_stalled();
3122
 
3123
  // First set the chain 
3124
  err = gdb_set_chain(SC_RISC_DEBUG);   /* 1 RISC Debug Interface chain */
3125
  if(err > 0){
3126
        printf("Error %d to set RISC Debug Interface chain in the STEP command 's'\n", err);
3127
    rsp_client_close ();
3128
    return;
3129
        }
3130
 
3131
  if (0 == strcmp ("s", p_buf->data))
3132
  {
3133
    /* ---------- Npc ---------- */
3134
    addr = get_npc();
3135
  }
3136
  else if (1 != sscanf (p_buf->data, "s%x", &addr))
3137
  {
3138
    fprintf (stderr,
3139
             "Warning: RSP step address %s not recognized: ignored\n",
3140
             p_buf->data);
3141 49 julius
 
3142 40 julius
    /* ---------- NPC ---------- */
3143
    addr = get_npc();
3144
  }
3145
 
3146
  rsp_step_generic (addr, EXCEPT_NONE);
3147
 
3148
}       /* rsp_step () */
3149
 
3150
 
3151
/*---------------------------------------------------------------------------*/
3152
/*!Handle a RSP step with signal request
3153
 
3154
   Currently null. Will use the underlying generic step function.
3155
 
3156
   @param[in] p_buf  The full step with signal packet              */
3157
/*---------------------------------------------------------------------------*/
3158
static void
3159
rsp_step_with_signal (struct rsp_buf *p_buf)
3160
{
3161
  printf ("RSP step with signal '%s' received\n", p_buf->data);
3162
 
3163
}       /* rsp_step_with_signal () */
3164
 
3165
 
3166
/*---------------------------------------------------------------------------*/
3167
/*!Generic processing of a step request
3168
 
3169
   The signal may be EXCEPT_NONE if there is no exception to be
3170
   handled. Currently the exception is ignored.
3171
 
3172
   The single step flag is set in the debug registers and then the processor
3173
   is unstalled.
3174
 
3175
   @param[in] addr    Address from which to step
3176
   @param[in] except  The exception to use (if any)                          */
3177
/*---------------------------------------------------------------------------*/
3178
static void
3179
rsp_step_generic (uint32_t  addr,
3180
                  uint32_t  except)
3181
{
3182
  uint32_t              temp_uint32;
3183
 
3184
  /* Set the address as the value of the next program counter */
3185
 
3186
  set_npc (addr);
3187
 
3188 49 julius
  or1k_dbg_group_regs_cache.drr = 0; // Clear DRR
3189
  or1k_dbg_group_regs_cache.dmr1 |= SPR_DMR1_ST; // Stepping, so enable step in DMR1
3190
  or1k_dbg_group_regs_cache.dsr |= SPR_DSR_TE; // Enable trap handled by DU
3191
  or1k_dbg_group_regs_cache.dmr2 &= ~SPR_DMR2_WGB; // Stepping, so disable breakpoints from watchpoints
3192
  dbg_regs_cache_dirty = 1; // Always write the cache back
3193 40 julius
 
3194 49 julius
  /* Commit all debug registers */
3195
  if (dbg_regs_cache_dirty == 1)
3196
    put_debug_registers();
3197
 
3198 40 julius
  /* Unstall the processor */
3199
  set_stall_state (0);
3200 49 julius
 
3201
  /* Debug regs cache now in invalid state */
3202
  dbg_regs_cache_dirty = -1;
3203 40 julius
 
3204
  /* Note the GDB client is now waiting for a reply. */
3205
  rsp.client_waiting = 1;
3206
 
3207
}       /* rsp_step_generic () */
3208
 
3209
 
3210
/*---------------------------------------------------------------------------*/
3211
/*!Handle a RSP 'v' packet
3212
 
3213
   These are commands associated with executing the code on the target
3214
 
3215
   @param[in] p_buf  The request                                               */
3216
/*---------------------------------------------------------------------------*/
3217
static void
3218
rsp_vpkt (struct rsp_buf *p_buf)
3219
{
3220
  if (0 == strncmp ("vAttach;", p_buf->data, strlen ("vAttach;")))
3221
    {
3222
      /* Attaching is a null action, since we have no other process. We just
3223
         return a stop packet (using TRAP) to indicate we are stopped. */
3224
      put_str_packet ("S05");
3225
      return;
3226
    }
3227
  else if (0 == strcmp ("vCont?", p_buf->data))
3228
    {
3229
      /* For now we don't support this. */
3230
      put_str_packet ("");
3231
      return;
3232
    }
3233
  else if (0 == strncmp ("vCont", p_buf->data, strlen ("vCont")))
3234
    {
3235
      /* This shouldn't happen, because we've reported non-support via vCont?
3236
         above */
3237
      fprintf (stderr, "Warning: RSP vCont not supported: ignored\n" );
3238
      return;
3239
    }
3240
  else if (0 == strncmp ("vFile:", p_buf->data, strlen ("vFile:")))
3241
    {
3242
      /* For now we don't support this. */
3243
      fprintf (stderr, "Warning: RSP vFile not supported: ignored\n" );
3244
      put_str_packet ("");
3245
      return;
3246
    }
3247
  else if (0 == strncmp ("vFlashErase:", p_buf->data, strlen ("vFlashErase:")))
3248
    {
3249
      /* For now we don't support this. */
3250
      fprintf (stderr, "Warning: RSP vFlashErase not supported: ignored\n" );
3251
      put_str_packet ("E01");
3252
      return;
3253
    }
3254
  else if (0 == strncmp ("vFlashWrite:", p_buf->data, strlen ("vFlashWrite:")))
3255
    {
3256
      /* For now we don't support this. */
3257
      fprintf (stderr, "Warning: RSP vFlashWrite not supported: ignored\n" );
3258
      put_str_packet ("E01");
3259
      return;
3260
    }
3261
  else if (0 == strcmp ("vFlashDone", p_buf->data))
3262
    {
3263
      /* For now we don't support this. */
3264
      fprintf (stderr, "Warning: RSP vFlashDone not supported: ignored\n" );
3265
      put_str_packet ("E01");
3266
      return;
3267
    }
3268
  else if (0 == strncmp ("vRun;", p_buf->data, strlen ("vRun;")))
3269
    {
3270
      /* We shouldn't be given any args, but check for this */
3271
      if (p_buf->len > (int) strlen ("vRun;"))
3272
        {
3273
          fprintf (stderr, "Warning: Unexpected arguments to RSP vRun "
3274
                   "command: ignored\n");
3275
        }
3276
 
3277
      /* Restart the current program. However unlike a "R" packet, "vRun"
3278
         should behave as though it has just stopped. We use signal
3279
         5 (TRAP). */
3280
      rsp_restart ();
3281
      put_str_packet ("S05");
3282
    }
3283
  else
3284
    {
3285
      fprintf (stderr, "Warning: Unknown RSP 'v' packet type %s: ignored\n",
3286
               p_buf->data);
3287
      put_str_packet ("E01");
3288
      return;
3289
    }
3290
}       /* rsp_vpkt () */
3291
 
3292
 
3293
/*---------------------------------------------------------------------------*/
3294
/*!Handle a RSP write memory (binary) request
3295
 
3296
   Syntax is:
3297
 
3298
     X<addr>,<length>:
3299
 
3300
   Followed by the specified number of bytes as raw binary. Response should be
3301
   "OK" if all copied OK, E<nn> if error <nn> has occurred.
3302
 
3303
   The length given is the number of bytes to be written. However the number
3304
   of data bytes may be greater, since '#', '$' and '}' are escaped by
3305
   preceding them by '}' and oring with 0x20.
3306
 
3307
   @param[in] p_buf  The command received                                      */
3308
/*---------------------------------------------------------------------------*/
3309
static void
3310
rsp_write_mem_bin (struct rsp_buf *p_buf)
3311
{
3312
  unsigned int  addr;                   /* Where to write the memory */
3313
  int           len;                    /* Number of bytes to write */
3314 46 julius
  char          *bindat, *bindat_ptr;   /* Pointer to the binary data */
3315 40 julius
  int           off = 0; /* Offset to start of binary data */
3316
  int           newlen;         /* Number of bytes in bin data */
3317 46 julius
  int i;
3318
  int bytes_per_word = 4; /* Current OR implementation is 4-byte words */
3319 40 julius
 
3320
  if (2 != sscanf (p_buf->data, "X%x,%x:", &addr, &len))
3321
    {
3322
      fprintf (stderr, "Warning: Failed to recognize RSP write memory "
3323
               "command: %s\n", p_buf->data);
3324
      put_str_packet ("E01");
3325
      return;
3326
    }
3327
 
3328
  /* Find the start of the data and "unescape" it */
3329
  bindat = p_buf->data;
3330
  while(off < GDB_BUF_MAX){
3331
        if(bindat[off] == ':'){
3332
                        bindat = bindat + off + 1;
3333
                        off++;
3334
                        break;
3335
                }
3336
                off++;
3337
  }
3338
        if(off >= GDB_BUF_MAX){
3339
          put_str_packet ("E01");
3340
                return;
3341
        }
3342
 
3343
  newlen = rsp_unescape (bindat, p_buf->len - off);
3344
 
3345
  /* Sanity check */
3346
  if (newlen != len)
3347
  {
3348
    int  minlen = len < newlen ? len : newlen;
3349
 
3350
    fprintf (stderr, "Warning: Write of %d bytes requested, but %d bytes "
3351
       "supplied. %d will be written\n", len, newlen, minlen);
3352
    len = minlen;
3353
  }
3354
 
3355
  // Make sure the processor is stalled
3356
  gdb_ensure_or1k_stalled();
3357
 
3358
  // Set chain 5 --> Wishbone Memory chain
3359
  err = gdb_set_chain(SC_WISHBONE);
3360
  if(err){
3361
    put_str_packet ("E01");
3362
    return;
3363
  }
3364
 
3365
  /* Write the bytes to memory */
3366
  if (len)
3367
    {
3368
      swap_buf(bindat, len);
3369
 
3370
      if (DEBUG_GDB_BLOCK_DATA){
3371
        uint32_t  temp_uint32;
3372
        for (off = 0; off < len; off++){
3373
          temp_uint32 = (temp_uint32 << 8) | (0x000000ff & bindat[off]);
3374
          if((off %4 ) == 3){
3375
            temp_uint32 = htonl(temp_uint32);
3376
          }
3377
          switch(off % 16)
3378
            {
3379
            case 3:
3380
              printf("Add 0x%08x   Data 0x%08x  ", addr + off - 3, temp_uint32);
3381
              break;
3382
            case 7:
3383
            case 11:
3384
              printf("0x%08x  ", temp_uint32);
3385
              break;
3386
            case 15:
3387
              printf("0x%08x\n", temp_uint32);
3388
              break;
3389
            default:
3390
              break;
3391
            }
3392
          if ((len - off == 1) && (off % 16) < 15) printf("\n");
3393
        }
3394
      }
3395 46 julius
 
3396
      bindat_ptr = bindat; // Copy of this pointer so we don't trash it
3397
      if (addr & 0x3) // not perfectly aligned at beginning - fix
3398
        {
3399
          if (DEBUG_GDB) printf("rsp_write_mem_bin: address not word aligned: 0x%.8x\n", addr);fflush (stdout);
3400
          // Write enough to align us
3401
          int bytes_to_write = bytes_per_word - (addr&0x3);
3402
          if (bytes_to_write > len) bytes_to_write = len; // case of writing 1 byte to adr 0x1
3403
          if (DEBUG_GDB) printf("rsp_write_mem_bin: writing %d bytes of len (%d)\n",
3404
                                bytes_to_write, len);fflush (stdout);
3405
 
3406
          for (i=0;i<bytes_to_write;i++) err = gdb_write_byte(addr+i, (uint8_t) bindat_ptr[i]);
3407
          addr += bytes_to_write; bindat_ptr += bytes_to_write; len -= bytes_to_write;
3408
          if (DEBUG_GDB) printf("rsp_write_mem_bin: address should now be word aligned: 0x%.8x\n", addr);fflush (stdout);
3409
 
3410
        }
3411
      if ((len > 3) && !err) // now write full words, if we can
3412
        {
3413
          int words_to_write = len/bytes_per_word;
3414
          if (DEBUG_GDB) printf("rsp_write_mem_bin: writing %d words from 0x%x, len %d bytes\n",
3415
                                words_to_write, addr, len);fflush (stdout);
3416
 
3417
          err = gdb_write_block(addr, (uint32_t*)bindat_ptr, (words_to_write*bytes_per_word));
3418
          addr+=(words_to_write*bytes_per_word); bindat_ptr+=(words_to_write*bytes_per_word);
3419
          len-=(words_to_write*bytes_per_word);
3420
        }
3421
      if (len && !err)  // leftover words. Write them out
3422
        {
3423
          if (DEBUG_GDB) printf("rsp_write_mem_bin: writing remainder %d bytes to 0x%.8x\n",
3424
                                len, addr);fflush (stdout);
3425
 
3426
          for (i=0;i<len;i++) err = gdb_write_byte(addr+i, (uint8_t) bindat_ptr[i]);
3427
        }
3428 40 julius
      if(err){
3429
        put_str_packet ("E01");
3430
        return;
3431
      }
3432
      if (DEBUG_GDB) printf("Error %x\n", err);fflush (stdout);
3433
    }
3434
  put_str_packet ("OK");
3435
 
3436
}       /* rsp_write_mem_bin () */
3437
 
3438 49 julius
/*---------------------------------------------------------------------------*/
3439
/*!Copy the debug group registers from the processor into our cache struct
3440
                                                                             */
3441
/*---------------------------------------------------------------------------*/
3442
static void
3443
get_debug_registers(void)
3444
{
3445
 
3446
  if (dbg_regs_cache_dirty != -1) return; // Don't need to update them
3447
 
3448
    if (DEBUG_GDB)
3449
      printf("gdb - get_debug_registers() - reading %d bytes for debug regs\n",sizeof(or1k_dbg_group_regs_cache));
3450
 
3451
 
3452
  err = gdb_set_chain(SC_RISC_DEBUG);   /* Register Chain */
3453
  /* Fill our debug group registers struct */
3454
  gdb_read_block((OR1K_SPG_DEBUG << OR1K_SPG_SIZE_BITS),
3455
                 (uint32_t *) &or1k_dbg_group_regs_cache,
3456
                 (uint32_t) sizeof(or1k_dbg_group_regs_cache));
3457
  dbg_regs_cache_dirty = 0; // Just updated it so not dirty
3458
 
3459
  if (DEBUG_GDB)
3460
    {
3461
      printf("gdb - get_debug_registers() - registers:\n\t");
3462
      uint32_t * regs_ptr = (uint32_t*) &or1k_dbg_group_regs_cache;
3463
      int i;
3464
      for(i=0;i<(sizeof(or1k_dbg_group_regs_cache)/4);i++)
3465
        { if (i%4==0)printf("\n\t");
3466
          if (i<8)
3467
            printf("DVR%.2d %.8x ",i,regs_ptr[i]);
3468
          else if (i<16)
3469
            printf("DCR%.2d %.8x ",i-8,regs_ptr[i]);
3470
          else if (i<17)
3471
            printf("DMR1  %.8x ",regs_ptr[i]);
3472
          else if (i<18)
3473
            printf("DMR2  %.8x ",regs_ptr[i]);
3474
          else if (i<19)
3475
            printf("DCWR0 %.8x ",regs_ptr[i]);
3476
          else if (i<20)
3477
            printf("DCWR1 %.8x ",regs_ptr[i]);
3478
          else if (i<21)
3479
            printf("DSR   %.8x ",regs_ptr[i]);
3480
          else if (i<22)
3481
            printf("DRR   %.8x ",regs_ptr[i]);
3482
 
3483
        }
3484
      printf("\n");
3485
    }
3486
  return;
3487
} /* get_debug_registers() */
3488
 
3489
/*---------------------------------------------------------------------------*/
3490
/*!Copy the debug group registers from our cache to the processor
3491
                                                                             */
3492
/*---------------------------------------------------------------------------*/
3493
static void
3494
put_debug_registers(void)
3495
{
3496
  /* TODO: Block CPU registers write functionality */
3497
  if (DEBUG_GDB) printf("gdb - put_debug_registers()\n");
3498
  int i;
3499
  uint32_t *dbg_regs_ptr = (uint32_t *) &or1k_dbg_group_regs_cache;
3500
 
3501
  if (DEBUG_GDB)
3502
    {
3503
      printf("gdb - put_debug_registers() - registers:\n\t");
3504
      uint32_t * regs_ptr = (uint32_t*) &or1k_dbg_group_regs_cache;
3505
      int i;
3506
      for(i=0;i<(sizeof(or1k_dbg_group_regs_cache)/4);i++)
3507
        { if (i%4==0)printf("\n\t");
3508
          if (i<8)
3509
            printf("DVR%.2d %.8x ",i,regs_ptr[i]);
3510
          else if (i<16)
3511
            printf("DCR%.2d %.8x ",i-8,regs_ptr[i]);
3512
          else if (i<17)
3513
            printf("DMR1  %.8x ",regs_ptr[i]);
3514
          else if (i<18)
3515
            printf("DMR2  %.8x ",regs_ptr[i]);
3516
          else if (i<19)
3517
            printf("DCWR0 %.8x ",regs_ptr[i]);
3518
          else if (i<20)
3519
            printf("DCWR1 %.8x ",regs_ptr[i]);
3520
          else if (i<21)
3521
            printf("DSR   %.8x ",regs_ptr[i]);
3522
          else if (i<22)
3523
            printf("DRR   %.8x ",regs_ptr[i]);
3524
 
3525
        }
3526
      printf("\n");
3527
    }
3528
 
3529
  err = gdb_set_chain(SC_RISC_DEBUG);   /* Register Chain */
3530
 
3531
  gdb_write_block((OR1K_SPG_DEBUG << OR1K_SPG_SIZE_BITS),
3532
                  (uint32_t *) &or1k_dbg_group_regs_cache,
3533
                  sizeof(or1k_dbg_group_regs_cache));
3534
 
3535
  return;
3536
 
3537
} /* put_debug_registers() */
3538
 
3539
/*---------------------------------------------------------------------------*/
3540
/*!Find the DVR/DCR pair corresponding to the address
3541
 
3542
  @return the number, 0-7 of the DCR/DVR pair, if possible, -1 else.         */
3543
/*---------------------------------------------------------------------------*/
3544
static int
3545
find_matching_dcrdvr_pair(uint32_t addr, uint32_t cc)
3546
{
3547
  int i;
3548
  for (i=0;i<OR1K_MAX_MATCHPOINTS; i++)
3549
    {
3550
      // Find the one matching according to address, and in use
3551
      if ((or1k_dbg_group_regs_cache.dvr[i] == addr)  &&
3552
          (or1k_dbg_group_regs_cache.dcr[i].cc == cc))
3553
        {
3554
          /*
3555
          if (DEBUG_GDB) printf("gdb - find_matching_dcrdvr_pair(%.8x, %d)\n",addr, cc);
3556
          if (DEBUG_GDB) printf("gdb - find_matching_dcrdvr_pair match in %d: dvr[%d] = %.8x dcr[%d].cc=%d\n",
3557
                                i,i,or1k_dbg_group_regs_cache.dvr[i],i,or1k_dbg_group_regs_cache.dcr[i].cc);
3558
          */
3559
          return i;
3560
        }
3561
    }
3562
 
3563
  // If the loop finished, no appropriate matchpoints
3564
  return -1;
3565
} /* find_matching_dcrdvr_pair() */
3566
 /*---------------------------------------------------------------------------*/
3567
/*!Count number of free DCR/DVR pairs
3568
 
3569
  @return the number, 0-7         */
3570
/*---------------------------------------------------------------------------*/
3571
static int
3572
count_free_dcrdvr_pairs(void)
3573
{
3574
  int i, free=0;
3575
  for (i=0;i<OR1K_MAX_MATCHPOINTS; i++)
3576
    {
3577
      if ((or1k_dbg_group_regs_cache.dcr[i].cc == OR1K_CC_MASKED) // If compare condition is masked, it's not used
3578
          && or1k_dbg_group_regs_cache.dcr[i].dp ) // and the debug point is present
3579
        free++;
3580
    }
3581
 
3582
 
3583
  return free;
3584
} /* count_free_dcrdvr_pairs() */
3585
 
3586
/*---------------------------------------------------------------------------*/
3587
/*!Find a free hardware breakpoint register, DCR/DVR pair
3588
 
3589
  @return the number, 0-7 of the DCR/DVR pair, if possible, -1 else.         */
3590
/*---------------------------------------------------------------------------*/
3591
static int
3592
find_free_dcrdvr_pair(void)
3593
{
3594
  int i;
3595
  for (i=0;i<OR1K_MAX_MATCHPOINTS; i++)
3596
    {
3597
      if ((or1k_dbg_group_regs_cache.dcr[i].cc == OR1K_CC_MASKED) // If compare condition is masked, it's not used
3598
          && or1k_dbg_group_regs_cache.dcr[i].dp ) // and the debug point is present
3599
        return i;
3600
    }
3601
 
3602
  // If the loop finished, no free matchpoints
3603
  return -1;
3604
} /* find_free_dcrdvr_pair() */
3605
 
3606
/*---------------------------------------------------------------------------*/
3607
/*!Setup a DCR/DVR pair for our watchpoint.
3608
 @param[in] wp_num  The watchpoint number
3609
 @param[in] address  The address for watchpoint
3610
                                                                             */
3611
/*---------------------------------------------------------------------------*/
3612
static void
3613
insert_hw_watchpoint(int wp_num, uint32_t address, uint32_t cc)
3614
{
3615
  if (DEBUG_GDB) printf("gdb - insert_hw_watchpoint(%d, 0x%.8x)\n",wp_num, address);
3616
  or1k_dbg_group_regs_cache.dvr[wp_num] = address;
3617
 
3618
  or1k_dbg_group_regs_cache.dcr[wp_num].cc = cc;
3619
  or1k_dbg_group_regs_cache.dcr[wp_num].sc = 0;
3620
  or1k_dbg_group_regs_cache.dcr[wp_num].ct = OR1K_CT_FETCH; // Instruction fetch address
3621
 
3622
  // Mark the debug reg cache as dirty
3623
  dbg_regs_cache_dirty = 1;
3624
  return;
3625
 
3626
}  /* insert_hw_watchpoint() */
3627
 
3628
/*---------------------------------------------------------------------------*/
3629
/*!Remove/free a DCR/DVR watchpoint pair
3630
 @param[in] wp_num  The watchpoint number
3631
                                                                             */
3632
/*---------------------------------------------------------------------------*/
3633
static void
3634
remove_hw_watchpoint(int wp_num)
3635
{
3636
  or1k_dbg_group_regs_cache.dvr[wp_num] = 0;
3637
 
3638
  or1k_dbg_group_regs_cache.dcr[wp_num].cc = OR1K_CC_MASKED; // We only do equals for now
3639
  or1k_dbg_group_regs_cache.dcr[wp_num].sc = 0;
3640
 
3641
  /* Auto-disable it as generating a breakpoint, too, although maybe gets done after
3642
     this call anyway. Best to ensure. */
3643
  disable_hw_breakpoint(wp_num);
3644
 
3645
  // Mark the debug reg cache as dirty
3646
  dbg_regs_cache_dirty = 1;
3647
  return;
3648
 
3649
} /* remove_hw_watchpoint() */
3650
 
3651
/*---------------------------------------------------------------------------*/
3652
/*!Enable a DCR/DVR watchpoint to generate a breakpoint
3653
 @param[in] wp_num  The watchpoint number
3654
                                                                             */
3655
/*---------------------------------------------------------------------------*/
3656
static void
3657
enable_hw_breakpoint(int wp_num)
3658
{
3659
  // Set the corresponding bit in DMR2 to enable matchpoint 'num' to trigger a breakpoint
3660
  or1k_dbg_group_regs_cache.dmr2 |= (uint32_t) (1 << (SPR_DMR2_WGB_OFF + wp_num));
3661
  // Mark the debug reg cache as dirty
3662
  dbg_regs_cache_dirty = 1;
3663
  return;
3664
} /* enable_hw_breakpoint() */
3665
 
3666
/*---------------------------------------------------------------------------*/
3667
/*!Disable a DCR/DVR watchpoint from generating a breakpoint
3668
 @param[in] wp_num  The watchpoint number
3669
                                                                             */
3670
/*---------------------------------------------------------------------------*/
3671
static void
3672
disable_hw_breakpoint(int wp_num)
3673
{
3674
  // Set the corresponding bit in DMR2 to enable matchpoint 'num' to trigger a breakpoint
3675
  or1k_dbg_group_regs_cache.dmr2 &= (uint32_t) ~(1 << (SPR_DMR2_WGB_OFF + wp_num));
3676
  // Mark the debug reg cache as dirty
3677
  dbg_regs_cache_dirty = 1;
3678
  return;
3679
} /* disable_hw_breakpoint() */
3680 40 julius
 
3681
/*---------------------------------------------------------------------------*/
3682
/*!Handle a RSP remove breakpoint or matchpoint request
3683
 
3684
   For now only memory breakpoints are implemented, which are implemented by
3685
   substituting a breakpoint at the specified address. The implementation must
3686
   cope with the possibility of duplicate packets.
3687
 
3688
   @todo This doesn't work with icache/immu yet
3689
 
3690
   @param[in] p_buf  The command received                                      */
3691
/*---------------------------------------------------------------------------*/
3692
static void
3693
rsp_remove_matchpoint (struct rsp_buf *p_buf)
3694
{
3695
  enum mp_type       type;              /* What sort of matchpoint */
3696
  uint32_t  addr;               /* Address specified */
3697
  int                len;                       /* Matchpoint length (not used) */
3698
  struct mp_entry   *mpe;                       /* Info about the replaced instr */
3699 49 julius
  int wp_num;
3700 40 julius
 
3701
  /* Break out the instruction */
3702
  if (3 != sscanf (p_buf->data, "z%1d,%x,%1d", (int *)&type, &addr, &len))
3703
    {
3704
      fprintf (stderr, "Warning: RSP matchpoint deletion request not "
3705
               "recognized: ignored\n");
3706
      put_str_packet ("E01");
3707
      return;
3708
    }
3709
 
3710
  /* Sanity check that the length is 4 */
3711
  if (4 != len)
3712
    {
3713
      fprintf (stderr, "Warning: RSP matchpoint deletion length %d not "
3714
               "valid: 4 assumed\n", len);
3715
      len = 4;
3716
    }
3717
 
3718
  /* Sort out the type of matchpoint */
3719
  switch (type)
3720
    {
3721
    case BP_MEMORY:
3722
      /* Memory breakpoint - replace the original instruction. */
3723
      mpe = mp_hash_delete (type, addr);
3724
 
3725
      /* If the BP hasn't yet been deleted, put the original instruction
3726
                         back. Don't forget to free the hash table entry afterwards. */
3727
                        if (NULL != mpe)
3728
                        {
3729
                          // Arc Sim Code -->   set_program32 (addr, mpe->instr);
3730
                          // Make sure the processor is stalled
3731
                          gdb_ensure_or1k_stalled();
3732
 
3733
                          // Set chain 5 --> Wishbone Memory chain
3734
                          err = gdb_set_chain(SC_WISHBONE);
3735
                                if(err){
3736
                                        put_str_packet ("E01");
3737
                                  return;
3738
                                }
3739
                                err = gdb_write_block(addr, &mpe->instr, 4);
3740
                                if(err){
3741
                                        put_str_packet ("E01");
3742
                                  return;
3743
                                }
3744
                          free (mpe);
3745
                        }
3746
 
3747
      put_str_packet ("OK");
3748
      return;
3749
 
3750
    case BP_HARDWARE:
3751 49 julius
      /* Adding support -- jb 090901 */
3752
      if (dbg_regs_cache_dirty == -1) // Regs invalid, get them
3753
        get_debug_registers();
3754
 
3755
      if (DEBUG_GDB) printf("gdb - rsp_remove_matchpoint() - hardware mp remove at addr %.8x\n",addr);
3756
#ifdef HWBP_BTWN
3757
      // Find the first of the pair of dcr/dvr registers
3758
      wp_num = find_matching_dcrdvr_pair(addr-4,OR1K_CC_GE);
3759
#else
3760
      wp_num = find_matching_dcrdvr_pair(addr,OR1K_CC_EQ);
3761
      remove_hw_watchpoint(wp_num);
3762
#endif
3763
      if ( wp_num < 0 )
3764
        {
3765
          printf("gdb - rsp_remove_matchpoint() failed to remove hardware breakpoint at addr %.8x\n",
3766
                 addr);
3767
          put_str_packet ("E01"); /* Cannot remove */
3768
          return;
3769
        }
3770
 
3771
      if (DEBUG_GDB) printf("gdb - rsp_remove_matchpoint() - mp to remove in DCR/DVR pair %d \n",wp_num);
3772
      remove_hw_watchpoint(wp_num);
3773
 
3774
#ifdef HWBP_BTWN
3775
      wp_num++;
3776
      /* Should probably check here that this is correct. Oh well. */
3777
      remove_hw_watchpoint(wp_num);
3778
      // Unchain these
3779
      or1k_dbg_group_regs_cache.dmr1 &= ~(SPR_DMR1_CW << (wp_num * SPR_DMR1_CW_SZ));
3780
#endif
3781
 
3782
      // Disable breakpoint generation
3783
      disable_hw_breakpoint(wp_num);
3784
 
3785
 
3786
      put_str_packet ("OK");
3787 40 julius
      return;
3788
 
3789
    case WP_WRITE:
3790
      put_str_packet ("");              /* Not supported */
3791
      return;
3792
 
3793
    case WP_READ:
3794
      put_str_packet ("");              /* Not supported */
3795
      return;
3796
 
3797
    case WP_ACCESS:
3798
      put_str_packet ("");              /* Not supported */
3799
      return;
3800
 
3801
    default:
3802
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
3803
               "recognized: ignored\n", type);
3804
      put_str_packet ("E01");
3805
      return;
3806
 
3807
    }
3808
}       /* rsp_remove_matchpoint () */
3809
 
3810
/*---------------------------------------------------------------------------*/
3811
/*!Handle a RSP insert breakpoint or matchpoint request
3812
 
3813
   For now only memory breakpoints are implemented, which are implemented by
3814
   substituting a breakpoint at the specified address. The implementation must
3815
   cope with the possibility of duplicate packets.
3816
 
3817
   @todo This doesn't work with icache/immu yet
3818
 
3819
   @param[in] p_buf  The command received                                      */
3820
/*---------------------------------------------------------------------------*/
3821
static void
3822
rsp_insert_matchpoint (struct rsp_buf *p_buf)
3823
{
3824
  enum mp_type       type;              /* What sort of matchpoint */
3825
  uint32_t  addr;               /* Address specified */
3826
  int                len;               /* Matchpoint length (not used) */
3827 49 julius
  uint32_t      instr;
3828
  int wp_num;
3829 40 julius
 
3830
  /* Break out the instruction */
3831
  if (3 != sscanf (p_buf->data, "Z%1d,%x,%1d", (int *)&type, &addr, &len))
3832
    {
3833
      fprintf (stderr, "Warning: RSP matchpoint insertion request not "
3834
               "recognized: ignored\n");
3835
      put_str_packet ("E01");
3836
      return;
3837
    }
3838
 
3839
  /* Sanity check that the length is 4 */
3840
  if (4 != len)
3841
    {
3842
      fprintf (stderr, "Warning: RSP matchpoint insertion length %d not "
3843
               "valid: 4 assumed\n", len);
3844
      len = 4;
3845
    }
3846
 
3847
  /* Sort out the type of matchpoint */
3848
  switch (type)
3849
    {
3850
    case BP_MEMORY:             // software-breakpoint Z0  break
3851
      /* Memory breakpoint - substitute a TRAP instruction */
3852
      // Make sure the processor is stalled
3853
      gdb_ensure_or1k_stalled();
3854
 
3855
      // Set chain 5 --> Wishbone Memory chain
3856
      gdb_set_chain(SC_WISHBONE);
3857
 
3858
      // Read the data from Wishbone Memory chain
3859
      // Arc Sim Code -->   mp_hash_add (type, addr, eval_direct32 (addr, 0, 0));
3860
      gdb_read_block(addr, &instr, 4);
3861
 
3862
      mp_hash_add (type, addr, instr);
3863
 
3864
      // Arc Sim Code -->   set_program32 (addr, OR1K_TRAP_INSTR);
3865
      instr = OR1K_TRAP_INSTR;
3866
      err = gdb_write_block(addr, &instr, 4);
3867
      if(err){
3868
        put_str_packet ("E01");
3869
        return;
3870
      }
3871
      put_str_packet ("OK");
3872
      return;
3873
 
3874
    case BP_HARDWARE:   // hardware-breakpoint Z1  hbreak
3875 49 julius
      /* Adding support -- jb 090901 */
3876
      get_debug_registers(); // First update our copy of the debug registers
3877
 
3878
#ifdef HWBP_BTWN
3879
      if (count_free_dcrdvr_pairs() < 2) /* Need at least two spare watchpoints free */
3880
        put_str_packet (""); /* Cannot add */
3881
#endif
3882
 
3883
      wp_num = find_free_dcrdvr_pair();
3884
 
3885
      if (wp_num == -1)
3886
        {
3887
          put_str_packet (""); /* Could not find a place to put the breakpoint */
3888
 
3889
        }
3890
 
3891
#ifdef HWBP_BTWN      
3892
      if ((wp_num >= OR1K_MAX_MATCHPOINTS-1)
3893
          || (wp_num %2 != 0)) /* Should have gotten either, 0,2,4,6 */
3894
        {
3895
          /* Something is wrong - can't do it */
3896
          put_str_packet ("");
3897
          return;
3898
        }
3899
 
3900
      // First watchpoint to watch for address greater than the address
3901
      insert_hw_watchpoint(wp_num, addr-4, OR1K_CC_GE);
3902
 
3903
      wp_num++; // The watchpoints should be next to each other.
3904
 
3905
      // Second watchpoint to watch for address less than the address
3906
      insert_hw_watchpoint(wp_num, addr+4, OR1K_CC_LE);
3907
 
3908
      // Chain these two together
3909
      // First clear the chain settings for this wp (2 bits per)
3910
      or1k_dbg_group_regs_cache.dmr1 &= ~(SPR_DMR1_CW << (wp_num * SPR_DMR1_CW_SZ));
3911
      // We will trigger a match when wp-1 {_-*{>AND<}*-_} wp go off.
3912
      or1k_dbg_group_regs_cache.dmr1 |= (SPR_DMR1_CW_AND << (wp_num * SPR_DMR1_CW_SZ));
3913
      // Now enable this send wp (the higher of the two) to trigger a matchpoint
3914
#else
3915
      /* Simply insert a watchpoint at the address */
3916
      insert_hw_watchpoint(wp_num, addr, OR1K_CC_EQ);
3917
 
3918
#endif
3919
 
3920
      enable_hw_breakpoint(wp_num);
3921
      put_str_packet ("OK");
3922 40 julius
      return;
3923
 
3924
    case WP_WRITE:              // write-watchpoint    Z2  watch                                                                                                                                                        
3925
      put_str_packet ("");              /* Not supported */
3926
      return;
3927
 
3928
    case WP_READ:                       // read-watchpoint     Z3  rwatch
3929
      put_str_packet ("");              /* Not supported */
3930
      return;
3931
 
3932
    case WP_ACCESS:             // access-watchpoint   Z4  awatch
3933
      put_str_packet ("");              /* Not supported */
3934
      return;
3935
 
3936
    default:
3937
      fprintf (stderr, "Warning: RSP matchpoint type %d not "
3938
               "recognized: ignored\n", type);
3939
      put_str_packet ("E01");
3940
      return;
3941
    }
3942
}       /* rsp_insert_matchpoint () */
3943
 
3944
 
3945
/*---------------------------------------------------------------------------
3946
Setup the or32 to init state
3947
 
3948
---------------------------------------------------------------------------*/
3949
void setup_or32(void)
3950
{
3951
  uint32_t              temp_uint32;
3952
  // First set the chain 
3953
  err = gdb_set_chain(SC_REGISTER);     /* 4 Register Chain */
3954
  if(err > 0){
3955
    if (DEBUG_GDB) printf("Error %d in gdb_set_chain\n", err);
3956
  }
3957
  if(gdb_read_reg(0x04, &temp_uint32)) printf("Error read from register\n");
3958
  if (DEBUG_GDB) printf("Read from chain 4 SC_REGISTER at add 0x00000004 = 0x%08x\n", temp_uint32 );
3959
 
3960
  if(gdb_write_reg(0x04, 0x00000001)) printf("Error write to register\n");
3961
  if (DEBUG_GDB) printf("Write to chain 4 SC_REGISTER at add 0x00000004 = 0x00000001\n");
3962
 
3963
  //    if(gdb_read_reg(0x04, &temp_uint32)) printf("Error read from register\n");
3964
  //    if (DEBUG_GDB) printf("Read from chain 4 SC_REGISTER at add 0x00000004 = 0x%08x\n", temp_uint32 );                      
3965
 
3966
  //    if(gdb_read_reg(0x04, &temp_uint32)) printf("Error read from register\n");
3967
  //    if (DEBUG_GDB) printf("Read from chain 4 SC_REGISTER at add 0x00000004 = 0x%08x\n", temp_uint32 );                      
3968
 
3969
  if(gdb_write_reg(0x00, 0x01000001)) printf("Error write to register\n");
3970
  if (DEBUG_GDB) printf("Write to chain 4 SC_REGISTER at add 0x00000000 = 0x01000001\n");
3971
}
3972
 
3973
// Function to check if the processor is stalled - if not then stall it.
3974
// this is useful in the event that GDB thinks the processor is stalled, but has, in fact
3975
// been hard reset on the board and is running.
3976
static void gdb_ensure_or1k_stalled()
3977
{
3978
  // Disable continual checking that the or1k is stalled
3979
#ifdef ENABLE_OR1K_STALL_CHECK
3980
  unsigned char stalled;
3981
  dbg_cpu0_read_ctrl(0, &stalled);
3982
  if ((stalled & 0x1) != 0x1)
3983
    {
3984
      if (DEBUG_GDB)
3985
        printf("Processor not stalled, like we thought\n");
3986
 
3987
      // Set the TAP controller to its OR1k chain
3988
      dbg_set_tap_ir(JI_DEBUG);
3989
      gdb_chain = -1;
3990
 
3991
      // Processor isn't stalled, contrary to what we though, so stall it
3992
      printf("Stalling or1k\n");
3993
      dbg_cpu0_write_ctrl(0, 0x01);      // stall or1k
3994
    }
3995
#endif
3996
  return;
3997
}
3998
 
3999
 
4000 397 julius
int gdb_read_byte(uint32_t adr, uint8_t *data) {
4001
  if (DEBUG_CMDS) printf("rreg %d\n", gdb_chain);
4002
  switch (gdb_chain) {
4003
  case SC_RISC_DEBUG: *data = 0; return 0; // Should probably throw an error for chains without byte read...
4004
  case SC_REGISTER:   *data = 0; return 0;
4005
  case SC_WISHBONE:   return dbg_wb_read8(adr, data) ? ERR_CRC : ERR_NONE;
4006
  case SC_TRACE:      *data = 0; return 0;
4007
  default:            return JTAG_PROXY_INVALID_CHAIN;
4008
  }
4009
}
4010
 
4011 40 julius
int gdb_read_reg(uint32_t adr, uint32_t *data) {
4012 46 julius
  if (DEBUG_CMDS) printf("rreg %d\n", gdb_chain);
4013 40 julius
  switch (gdb_chain) {
4014 49 julius
  case SC_RISC_DEBUG: return dbg_cpu0_read(adr, data, 4) ? ERR_CRC : ERR_NONE;
4015 40 julius
  case SC_REGISTER:   return dbg_cpu0_read_ctrl(adr, (unsigned char*)data) ?
4016
      ERR_CRC : ERR_NONE;
4017
  case SC_WISHBONE:   return dbg_wb_read32(adr, data) ? ERR_CRC : ERR_NONE;
4018
  case SC_TRACE:      *data = 0; return 0;
4019
  default:            return JTAG_PROXY_INVALID_CHAIN;
4020
  }
4021
}
4022
 
4023 46 julius
int gdb_write_byte(uint32_t adr, uint8_t data) {
4024
  if (DEBUG_CMDS) printf("wbyte %d\n", gdb_chain);
4025
  switch (gdb_chain) {
4026
  case SC_WISHBONE:   return dbg_wb_write8(adr, data) ?
4027
      ERR_CRC : ERR_NONE;
4028
  default:            return JTAG_PROXY_INVALID_CHAIN;
4029
  }
4030
}
4031
 
4032
 int gdb_write_short(uint32_t adr, uint16_t data) {
4033
   if (DEBUG_CMDS) printf("wshort %d\n", gdb_chain); fflush (stdout);
4034
   switch (gdb_chain) {
4035
  case SC_WISHBONE:   return dbg_wb_write16(adr, data) ?
4036
      ERR_CRC : ERR_NONE;
4037
  default:            return JTAG_PROXY_INVALID_CHAIN;
4038
  }
4039
}
4040
 
4041 40 julius
int gdb_write_reg(uint32_t adr, uint32_t data) {
4042 46 julius
  if (DEBUG_CMDS) printf("wreg %d\n", gdb_chain); fflush (stdout);
4043 40 julius
  switch (gdb_chain) { /* remap registers, to be compatible with jp1 */
4044
  case SC_RISC_DEBUG: if (adr == JTAG_RISCOP) adr = 0x00;
4045 49 julius
    return dbg_cpu0_write(adr, &data, 4) ? ERR_CRC : ERR_NONE;
4046 40 julius
  case SC_REGISTER:   return dbg_cpu0_write_ctrl(adr, data) ? ERR_CRC : ERR_NONE;
4047
  case SC_WISHBONE:   return dbg_wb_write32(adr, data) ? ERR_CRC : ERR_NONE;
4048
  case SC_TRACE:      return 0;
4049
  default:            return JTAG_PROXY_INVALID_CHAIN;
4050
  }
4051
}
4052
 
4053
int gdb_read_block(uint32_t adr, uint32_t *data, int len) {
4054 49 julius
  if (DEBUG_CMDS) printf("rb %d len %d\n", gdb_chain, len); fflush (stdout);
4055 40 julius
  switch (gdb_chain) {
4056 49 julius
  case SC_RISC_DEBUG: return dbg_cpu0_read(adr, data, len) ? ERR_CRC : ERR_NONE;
4057
  case SC_WISHBONE:   return dbg_wb_read_block32(adr, data, len) ? ERR_CRC : ERR_NONE;
4058 40 julius
  default:            return JTAG_PROXY_INVALID_CHAIN;
4059
  }
4060
}
4061
 
4062
int gdb_write_block(uint32_t adr, uint32_t *data, int len) {
4063 46 julius
  if (DEBUG_CMDS) printf("wb %d\n", gdb_chain); fflush (stdout);
4064 40 julius
  switch (gdb_chain) {
4065 49 julius
  case SC_RISC_DEBUG: return dbg_cpu0_write(adr, data, len) ? ERR_CRC : ERR_NONE;
4066 40 julius
  case SC_WISHBONE:   return dbg_wb_write_block32(adr, data, len) ?
4067
      ERR_CRC : ERR_NONE;
4068
  default:            return JTAG_PROXY_INVALID_CHAIN;
4069
  }
4070
}
4071
 
4072
int gdb_set_chain(int chain) {
4073
  int rv;
4074
  switch (chain) {
4075
  case SC_RISC_DEBUG:
4076
  case SC_REGISTER:
4077
  case SC_TRACE:
4078
  case SC_WISHBONE:   gdb_chain = chain;
4079
    rv = ERR_NONE;
4080
    break;
4081
  default:            rv = JTAG_PROXY_INVALID_CHAIN;
4082
    break;
4083
  }
4084
  return rv;
4085
}
4086
 
4087
 
4088
/*****************************************************************************
4089
* Close the connection to the client if it is open
4090
******************************************************************************/
4091
static void client_close (char err)
4092
{
4093
  if(gdb_fd) {
4094
    perror("gdb socket - " + err);
4095
    close(gdb_fd);
4096
    gdb_fd = 0;
4097
  }
4098
}       /* client_close () */
4099
 
4100
 
4101
/*---------------------------------------------------------------------------*/
4102
/* Swap a buffer of 4-byte from 1234 to 4321
4103
 
4104
   parameter[in]  p_buf and len
4105
   parameter[out] none                                                                                                                                                                                                                   */
4106
/*---------------------------------------------------------------------------*/
4107
static void swap_buf(char* p_buf, int len)
4108
{
4109
        int temp;
4110
        int n = 0;
4111
 
4112
  if (len > 2)
4113
  {
4114
    while(n < len){
4115
        // swap 0 and 3
4116
        temp = p_buf[n];
4117
                        p_buf[n] = p_buf[n + 3];
4118
                        p_buf[n + 3] = temp;
4119
        // swap 1 and 2
4120
        temp = p_buf[n + 1];
4121
                        p_buf[n + 1] = p_buf[n + 2];
4122
                        p_buf[n + 2] = temp;
4123
 
4124
                        n += 4;
4125
    }
4126
        }
4127
}
4128
 
4129
 
4130
/*---------------------------------------------------------------------------*/
4131
/*!Set the stall state of the processor
4132
 
4133
   @param[in] state  If non-zero stall the processor.                        */
4134
/*---------------------------------------------------------------------------*/
4135
static void
4136
set_stall_state (int state)
4137
{
4138
 
4139
  if(state == 0)
4140
    {
4141
      err = dbg_cpu0_write_ctrl(0, 0);     /* unstall or1k */
4142
      stallState = UNSTALLED;
4143
      npcIsCached = 0;
4144
      rsp.sigval = TARGET_SIGNAL_NONE;
4145
    }
4146
  else
4147
    {
4148
      err = dbg_cpu0_write_ctrl(0, 0x01);                                 /* stall or1k */
4149
      stallState = STALLED;
4150
    }
4151
 
4152
  if(err > 0 && DEBUG_GDB)printf("Error %d in set_stall_state Stall state = %d\n", err, state);
4153
 
4154
}       /* set_stall_state () */
4155
 
4156
 
4157
/*---------------------------------------------------------------------------*/
4158
/*!Set the reset bit of the processor's control reg in debug interface
4159
 */
4160
/*---------------------------------------------------------------------------*/
4161
static void
4162
reset_or1k (void)
4163
{
4164
 
4165
  err = dbg_cpu0_write_ctrl(0, 0x02);  /* reset or1k */
4166
 
4167
  if(err > 0 && DEBUG_GDB)printf("Error %d in reset_or1k()\n", err);
4168
 
4169
}       /* reset_or1k () */
4170
 
4171
/*---------------------------------------------------------------------------*/
4172
/*!Close down the connection with GDB in the event of a kill signal
4173
 
4174
 */
4175
/*---------------------------------------------------------------------------*/
4176
void gdb_close()
4177
{
4178
  rsp_client_close();
4179
  client_close('0');
4180
  // Maybe do other things here!
4181
}

powered by: WebSVN 2.1.0

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