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

Subversion Repositories openrisc_2011-10-31

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

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

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

powered by: WebSVN 2.1.0

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