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

Subversion Repositories or1k

[/] [or1k/] [trunk/] [gdb-5.3/] [gdb/] [remote.c] - Blame information for rev 1765

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1181 sfurman
/* Remote target communications for serial-line targets in custom GDB protocol
2
 
3
   Copyright 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996,
4
   1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
5
 
6
   This file is part of GDB.
7
 
8
   This program is free software; you can redistribute it and/or modify
9
   it under the terms of the GNU General Public License as published by
10
   the Free Software Foundation; either version 2 of the License, or
11
   (at your option) any later version.
12
 
13
   This program is distributed in the hope that it will be useful,
14
   but WITHOUT ANY WARRANTY; without even the implied warranty of
15
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
   GNU General Public License for more details.
17
 
18
   You should have received a copy of the GNU General Public License
19
   along with this program; if not, write to the Free Software
20
   Foundation, Inc., 59 Temple Place - Suite 330,
21
   Boston, MA 02111-1307, USA.  */
22
 
23
/* See the GDB User Guide for details of the GDB remote protocol. */
24
 
25
#include "defs.h"
26
#include "gdb_string.h"
27
#include <ctype.h>
28
#include <fcntl.h>
29
#include "inferior.h"
30
#include "bfd.h"
31
#include "symfile.h"
32
#include "target.h"
33
/*#include "terminal.h" */
34
#include "gdbcmd.h"
35
#include "objfiles.h"
36
#include "gdb-stabs.h"
37
#include "gdbthread.h"
38
#include "remote.h"
39
#include "regcache.h"
40
#include "value.h"
41
#include "gdb_assert.h"
42
 
43
#include <ctype.h>
44
#include <sys/time.h>
45
#ifdef USG
46
#include <sys/types.h>
47
#endif
48
 
49
#include "event-loop.h"
50
#include "event-top.h"
51
#include "inf-loop.h"
52
 
53
#include <signal.h>
54
#include "serial.h"
55
 
56
#include "gdbcore.h" /* for exec_bfd */
57
 
58
/* Prototypes for local functions */
59
static void cleanup_sigint_signal_handler (void *dummy);
60
static void initialize_sigint_signal_handler (void);
61
static int getpkt_sane (char *buf, long sizeof_buf, int forever);
62
 
63
static void handle_remote_sigint (int);
64
static void handle_remote_sigint_twice (int);
65
static void async_remote_interrupt (gdb_client_data);
66
void async_remote_interrupt_twice (gdb_client_data);
67
 
68
static void build_remote_gdbarch_data (void);
69
 
70
static int remote_write_bytes (CORE_ADDR memaddr, char *myaddr, int len);
71
 
72
static int remote_read_bytes (CORE_ADDR memaddr, char *myaddr, int len);
73
 
74
static void remote_files_info (struct target_ops *ignore);
75
 
76
static int remote_xfer_memory (CORE_ADDR memaddr, char *myaddr,
77
                               int len, int should_write,
78
                               struct mem_attrib *attrib,
79
                               struct target_ops *target);
80
 
81
static void remote_prepare_to_store (void);
82
 
83
static void remote_fetch_registers (int regno);
84
 
85
static void remote_resume (ptid_t ptid, int step,
86
                           enum target_signal siggnal);
87
static void remote_async_resume (ptid_t ptid, int step,
88
                                 enum target_signal siggnal);
89
static int remote_start_remote (struct ui_out *uiout, void *dummy);
90
 
91
static void remote_open (char *name, int from_tty);
92
static void remote_async_open (char *name, int from_tty);
93
 
94
static void extended_remote_open (char *name, int from_tty);
95
static void extended_remote_async_open (char *name, int from_tty);
96
 
97
static void remote_open_1 (char *, int, struct target_ops *, int extended_p,
98
                           int async_p);
99
 
100
static void remote_close (int quitting);
101
 
102
static void remote_store_registers (int regno);
103
 
104
static void remote_mourn (void);
105
static void remote_async_mourn (void);
106
 
107
static void extended_remote_restart (void);
108
 
109
static void extended_remote_mourn (void);
110
 
111
static void extended_remote_create_inferior (char *, char *, char **);
112
static void extended_remote_async_create_inferior (char *, char *, char **);
113
 
114
static void remote_mourn_1 (struct target_ops *);
115
 
116
static void remote_send (char *buf, long sizeof_buf);
117
 
118
static int readchar (int timeout);
119
 
120
static ptid_t remote_wait (ptid_t ptid,
121
                                 struct target_waitstatus *status);
122
static ptid_t remote_async_wait (ptid_t ptid,
123
                                       struct target_waitstatus *status);
124
 
125
static void remote_kill (void);
126
static void remote_async_kill (void);
127
 
128
static int tohex (int nib);
129
 
130
static void remote_detach (char *args, int from_tty);
131
static void remote_async_detach (char *args, int from_tty);
132
 
133
static void remote_interrupt (int signo);
134
 
135
static void remote_interrupt_twice (int signo);
136
 
137
static void interrupt_query (void);
138
 
139
static void set_thread (int, int);
140
 
141
static int remote_thread_alive (ptid_t);
142
 
143
static void get_offsets (void);
144
 
145
static long read_frame (char *buf, long sizeof_buf);
146
 
147
static int remote_insert_breakpoint (CORE_ADDR, char *);
148
 
149
static int remote_remove_breakpoint (CORE_ADDR, char *);
150
 
151 1258 hpanther
static int remote_insert_hw_breakpoint (CORE_ADDR, char *);
152
 
153
static int remote_remove_hw_breakpoint (CORE_ADDR, char *);
154
 
155 1181 sfurman
static int hexnumlen (ULONGEST num);
156
 
157
static void init_remote_ops (void);
158
 
159
static void init_extended_remote_ops (void);
160
 
161
static void init_remote_cisco_ops (void);
162
 
163
static struct target_ops remote_cisco_ops;
164
 
165
static void remote_stop (void);
166
 
167
static int ishex (int ch, int *val);
168
 
169
static int stubhex (int ch);
170
 
171
static int remote_query (int /*char */ , char *, char *, int *);
172
 
173
static int hexnumstr (char *, ULONGEST);
174
 
175
static int hexnumnstr (char *, ULONGEST, int);
176
 
177
static CORE_ADDR remote_address_masked (CORE_ADDR);
178
 
179
static void print_packet (char *);
180
 
181
static unsigned long crc32 (unsigned char *, int, unsigned int);
182
 
183
static void compare_sections_command (char *, int);
184
 
185
static void packet_command (char *, int);
186
 
187
static int stub_unpack_int (char *buff, int fieldlength);
188
 
189
static ptid_t remote_current_thread (ptid_t oldptid);
190
 
191
static void remote_find_new_threads (void);
192
 
193
static void record_currthread (int currthread);
194
 
195
static int fromhex (int a);
196
 
197
static int hex2bin (const char *hex, char *bin, int count);
198
 
199
static int bin2hex (const char *bin, char *hex, int count);
200
 
201
static int putpkt_binary (char *buf, int cnt);
202
 
203
static void check_binary_download (CORE_ADDR addr);
204
 
205
struct packet_config;
206
 
207
static void show_packet_config_cmd (struct packet_config *config);
208
 
209
static void update_packet_config (struct packet_config *config);
210
 
211
void _initialize_remote (void);
212
 
213
/* Description of the remote protocol.  Strictly speaking, when the
214
   target is open()ed, remote.c should create a per-target description
215
   of the remote protocol using that target's architecture.
216
   Unfortunatly, the target stack doesn't include local state.  For
217
   the moment keep the information in the target's architecture
218
   object.  Sigh..  */
219
 
220
struct packet_reg
221
{
222
  long offset; /* Offset into G packet.  */
223
  long regnum; /* GDB's internal register number.  */
224
  LONGEST pnum; /* Remote protocol register number.  */
225
  int in_g_packet; /* Always part of G packet.  */
226
  /* long size in bytes;  == REGISTER_RAW_SIZE (regnum); at present.  */
227
  /* char *name; == REGISTER_NAME (regnum); at present.  */
228
};
229
 
230
struct remote_state
231
{
232
  /* Description of the remote protocol registers.  */
233
  long sizeof_g_packet;
234
 
235
  /* Description of the remote protocol registers indexed by REGNUM
236
     (making an array of NUM_REGS + NUM_PSEUDO_REGS in size).  */
237
  struct packet_reg *regs;
238
 
239
  /* This is the size (in chars) of the first response to the ``g''
240
     packet.  It is used as a heuristic when determining the maximum
241
     size of memory-read and memory-write packets.  A target will
242
     typically only reserve a buffer large enough to hold the ``g''
243
     packet.  The size does not include packet overhead (headers and
244
     trailers). */
245
  long actual_register_packet_size;
246
 
247
  /* This is the maximum size (in chars) of a non read/write packet.
248
     It is also used as a cap on the size of read/write packets. */
249
  long remote_packet_size;
250
};
251
 
252
 
253
/* Handle for retreving the remote protocol data from gdbarch.  */
254
static struct gdbarch_data *remote_gdbarch_data_handle;
255
 
256
static struct remote_state *
257
get_remote_state (void)
258
{
259
  return gdbarch_data (current_gdbarch, remote_gdbarch_data_handle);
260
}
261
 
262
static void *
263
init_remote_state (struct gdbarch *gdbarch)
264
{
265
  int regnum;
266
  struct remote_state *rs = xmalloc (sizeof (struct remote_state));
267
 
268
  /* Start out by having the remote protocol mimic the existing
269
     behavour - just copy in the description of the register cache.  */
270
  rs->sizeof_g_packet = REGISTER_BYTES; /* OK use.   */
271
 
272
  /* Assume a 1:1 regnum<->pnum table.  */
273
  rs->regs = xcalloc (NUM_REGS + NUM_PSEUDO_REGS, sizeof (struct packet_reg));
274
  for (regnum = 0; regnum < NUM_REGS + NUM_PSEUDO_REGS; regnum++)
275
    {
276
      struct packet_reg *r = &rs->regs[regnum];
277
      r->pnum = regnum;
278
      r->regnum = regnum;
279
      r->offset = REGISTER_BYTE (regnum);
280
      r->in_g_packet = (regnum < NUM_REGS);
281
      /* ...size = REGISTER_RAW_SIZE (regnum); */
282
      /* ...name = REGISTER_NAME (regnum); */
283
    }
284
 
285
  /* Default maximum number of characters in a packet body. Many
286
     remote stubs have a hardwired buffer size of 400 bytes
287
     (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
288
     as the maximum packet-size to ensure that the packet and an extra
289
     NUL character can always fit in the buffer.  This stops GDB
290
     trashing stubs that try to squeeze an extra NUL into what is
291
     already a full buffer (As of 1999-12-04 that was most stubs. */
292
  rs->remote_packet_size = 400 - 1;
293
 
294
  /* Should rs->sizeof_g_packet needs more space than the
295
     default, adjust the size accordingly. Remember that each byte is
296
     encoded as two characters. 32 is the overhead for the packet
297
     header / footer. NOTE: cagney/1999-10-26: I suspect that 8
298
     (``$NN:G...#NN'') is a better guess, the below has been padded a
299
     little. */
300
  if (rs->sizeof_g_packet > ((rs->remote_packet_size - 32) / 2))
301
    rs->remote_packet_size = (rs->sizeof_g_packet * 2 + 32);
302
 
303
  /* This one is filled in when a ``g'' packet is received. */
304
  rs->actual_register_packet_size = 0;
305
 
306
  return rs;
307
}
308
 
309
static void
310
free_remote_state (struct gdbarch *gdbarch, void *pointer)
311
{
312
  struct remote_state *data = pointer;
313
  xfree (data->regs);
314
  xfree (data);
315
}
316
 
317
static struct packet_reg *
318
packet_reg_from_regnum (struct remote_state *rs, long regnum)
319
{
320
  if (regnum < 0 && regnum >= NUM_REGS + NUM_PSEUDO_REGS)
321
    return NULL;
322
  else
323
    {
324
      struct packet_reg *r = &rs->regs[regnum];
325
      gdb_assert (r->regnum == regnum);
326
      return r;
327
    }
328
}
329
 
330
static struct packet_reg *
331
packet_reg_from_pnum (struct remote_state *rs, LONGEST pnum)
332
{
333
  int i;
334
  for (i = 0; i < NUM_REGS + NUM_PSEUDO_REGS; i++)
335
    {
336
      struct packet_reg *r = &rs->regs[i];
337
      if (r->pnum == pnum)
338
        return r;
339
    }
340
  return NULL;
341
}
342
 
343
/* FIXME: graces/2002-08-08: These variables should eventually be
344
   bound to an instance of the target object (as in gdbarch-tdep()),
345
   when such a thing exists.  */
346
 
347
/* This is set to the data address of the access causing the target
348
   to stop for a watchpoint.  */
349
static CORE_ADDR remote_watch_data_address;
350
 
351
/* This is non-zero if taregt stopped for a watchpoint. */
352
static int remote_stopped_by_watchpoint_p;
353
 
354
 
355
static struct target_ops remote_ops;
356
 
357
static struct target_ops extended_remote_ops;
358
 
359
/* Temporary target ops. Just like the remote_ops and
360
   extended_remote_ops, but with asynchronous support. */
361
static struct target_ops remote_async_ops;
362
 
363
static struct target_ops extended_async_remote_ops;
364
 
365
/* FIXME: cagney/1999-09-23: Even though getpkt was called with
366
   ``forever'' still use the normal timeout mechanism.  This is
367
   currently used by the ASYNC code to guarentee that target reads
368
   during the initial connect always time-out.  Once getpkt has been
369
   modified to return a timeout indication and, in turn
370
   remote_wait()/wait_for_inferior() have gained a timeout parameter
371
   this can go away. */
372
static int wait_forever_enabled_p = 1;
373
 
374
 
375
/* This variable chooses whether to send a ^C or a break when the user
376
   requests program interruption.  Although ^C is usually what remote
377
   systems expect, and that is the default here, sometimes a break is
378
   preferable instead.  */
379
 
380
static int remote_break;
381
 
382
/* Descriptor for I/O to remote machine.  Initialize it to NULL so that
383
   remote_open knows that we don't have a file open when the program
384
   starts.  */
385
static struct serial *remote_desc = NULL;
386
 
387
/* This is set by the target (thru the 'S' message)
388
   to denote that the target is in kernel mode.  */
389
static int cisco_kernel_mode = 0;
390
 
391
/* This variable sets the number of bits in an address that are to be
392
   sent in a memory ("M" or "m") packet.  Normally, after stripping
393
   leading zeros, the entire address would be sent. This variable
394
   restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
395
   initial implementation of remote.c restricted the address sent in
396
   memory packets to ``host::sizeof long'' bytes - (typically 32
397
   bits).  Consequently, for 64 bit targets, the upper 32 bits of an
398
   address was never sent.  Since fixing this bug may cause a break in
399
   some remote targets this variable is principly provided to
400
   facilitate backward compatibility. */
401
 
402
static int remote_address_size;
403
 
404
/* Tempoary to track who currently owns the terminal.  See
405
   target_async_terminal_* for more details.  */
406
 
407
static int remote_async_terminal_ours_p;
408
 
409
 
410
/* User configurable variables for the number of characters in a
411
   memory read/write packet.  MIN ((rs->remote_packet_size),
412
   rs->sizeof_g_packet) is the default.  Some targets need smaller
413
   values (fifo overruns, et.al.)  and some users need larger values
414
   (speed up transfers).  The variables ``preferred_*'' (the user
415
   request), ``current_*'' (what was actually set) and ``forced_*''
416
   (Positive - a soft limit, negative - a hard limit). */
417
 
418
struct memory_packet_config
419
{
420
  char *name;
421
  long size;
422
  int fixed_p;
423
};
424
 
425
/* Compute the current size of a read/write packet.  Since this makes
426
   use of ``actual_register_packet_size'' the computation is dynamic.  */
427
 
428
static long
429
get_memory_packet_size (struct memory_packet_config *config)
430
{
431
  struct remote_state *rs = get_remote_state ();
432
  /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
433
     law?) that some hosts don't cope very well with large alloca()
434
     calls.  Eventually the alloca() code will be replaced by calls to
435
     xmalloc() and make_cleanups() allowing this restriction to either
436
     be lifted or removed. */
437
#ifndef MAX_REMOTE_PACKET_SIZE
438
#define MAX_REMOTE_PACKET_SIZE 16384
439
#endif
440
  /* NOTE: 16 is just chosen at random. */
441
#ifndef MIN_REMOTE_PACKET_SIZE
442
#define MIN_REMOTE_PACKET_SIZE 16
443
#endif
444
  long what_they_get;
445
  if (config->fixed_p)
446
    {
447
      if (config->size <= 0)
448
        what_they_get = MAX_REMOTE_PACKET_SIZE;
449
      else
450
        what_they_get = config->size;
451
    }
452
  else
453
    {
454
      what_they_get = (rs->remote_packet_size);
455
      /* Limit the packet to the size specified by the user. */
456
      if (config->size > 0
457
          && what_they_get > config->size)
458
        what_they_get = config->size;
459
      /* Limit it to the size of the targets ``g'' response. */
460
      if ((rs->actual_register_packet_size) > 0
461
          && what_they_get > (rs->actual_register_packet_size))
462
        what_they_get = (rs->actual_register_packet_size);
463
    }
464
  if (what_they_get > MAX_REMOTE_PACKET_SIZE)
465
    what_they_get = MAX_REMOTE_PACKET_SIZE;
466
  if (what_they_get < MIN_REMOTE_PACKET_SIZE)
467
    what_they_get = MIN_REMOTE_PACKET_SIZE;
468
  return what_they_get;
469
}
470
 
471
/* Update the size of a read/write packet. If they user wants
472
   something really big then do a sanity check. */
473
 
474
static void
475
set_memory_packet_size (char *args, struct memory_packet_config *config)
476
{
477
  int fixed_p = config->fixed_p;
478
  long size = config->size;
479
  if (args == NULL)
480
    error ("Argument required (integer, `fixed' or `limited').");
481
  else if (strcmp (args, "hard") == 0
482
      || strcmp (args, "fixed") == 0)
483
    fixed_p = 1;
484
  else if (strcmp (args, "soft") == 0
485
           || strcmp (args, "limit") == 0)
486
    fixed_p = 0;
487
  else
488
    {
489
      char *end;
490
      size = strtoul (args, &end, 0);
491
      if (args == end)
492
        error ("Invalid %s (bad syntax).", config->name);
493
#if 0
494
      /* Instead of explicitly capping the size of a packet to
495
         MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
496
         instead allowed to set the size to something arbitrarily
497
         large. */
498
      if (size > MAX_REMOTE_PACKET_SIZE)
499
        error ("Invalid %s (too large).", config->name);
500
#endif
501
    }
502
  /* Extra checks? */
503
  if (fixed_p && !config->fixed_p)
504
    {
505
      if (! query ("The target may not be able to correctly handle a %s\n"
506
                   "of %ld bytes. Change the packet size? ",
507
                   config->name, size))
508
        error ("Packet size not changed.");
509
    }
510
  /* Update the config. */
511
  config->fixed_p = fixed_p;
512
  config->size = size;
513
}
514
 
515
static void
516
show_memory_packet_size (struct memory_packet_config *config)
517
{
518
  printf_filtered ("The %s is %ld. ", config->name, config->size);
519
  if (config->fixed_p)
520
    printf_filtered ("Packets are fixed at %ld bytes.\n",
521
                     get_memory_packet_size (config));
522
  else
523
    printf_filtered ("Packets are limited to %ld bytes.\n",
524
                     get_memory_packet_size (config));
525
}
526
 
527
static struct memory_packet_config memory_write_packet_config =
528
{
529
  "memory-write-packet-size",
530
};
531
 
532
static void
533
set_memory_write_packet_size (char *args, int from_tty)
534
{
535
  set_memory_packet_size (args, &memory_write_packet_config);
536
}
537
 
538
static void
539
show_memory_write_packet_size (char *args, int from_tty)
540
{
541
  show_memory_packet_size (&memory_write_packet_config);
542
}
543
 
544
static long
545
get_memory_write_packet_size (void)
546
{
547
  return get_memory_packet_size (&memory_write_packet_config);
548
}
549
 
550
static struct memory_packet_config memory_read_packet_config =
551
{
552
  "memory-read-packet-size",
553
};
554
 
555
static void
556
set_memory_read_packet_size (char *args, int from_tty)
557
{
558
  set_memory_packet_size (args, &memory_read_packet_config);
559
}
560
 
561
static void
562
show_memory_read_packet_size (char *args, int from_tty)
563
{
564
  show_memory_packet_size (&memory_read_packet_config);
565
}
566
 
567
static long
568
get_memory_read_packet_size (void)
569
{
570
  struct remote_state *rs = get_remote_state ();
571
  long size = get_memory_packet_size (&memory_read_packet_config);
572
  /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
573
     extra buffer size argument before the memory read size can be
574
     increased beyond (rs->remote_packet_size). */
575
  if (size > (rs->remote_packet_size))
576
    size = (rs->remote_packet_size);
577
  return size;
578
}
579
 
580
 
581
/* Generic configuration support for packets the stub optionally
582
   supports. Allows the user to specify the use of the packet as well
583
   as allowing GDB to auto-detect support in the remote stub. */
584
 
585
enum packet_support
586
  {
587
    PACKET_SUPPORT_UNKNOWN = 0,
588
    PACKET_ENABLE,
589
    PACKET_DISABLE
590
  };
591
 
592
struct packet_config
593
  {
594
    char *name;
595
    char *title;
596
    enum auto_boolean detect;
597
    enum packet_support support;
598
  };
599
 
600
/* Analyze a packet's return value and update the packet config
601
   accordingly. */
602
 
603
enum packet_result
604
{
605
  PACKET_ERROR,
606
  PACKET_OK,
607
  PACKET_UNKNOWN
608
};
609
 
610
static void
611
update_packet_config (struct packet_config *config)
612
{
613
  switch (config->detect)
614
    {
615
    case AUTO_BOOLEAN_TRUE:
616
      config->support = PACKET_ENABLE;
617
      break;
618
    case AUTO_BOOLEAN_FALSE:
619
      config->support = PACKET_DISABLE;
620
      break;
621
    case AUTO_BOOLEAN_AUTO:
622
      config->support = PACKET_SUPPORT_UNKNOWN;
623
      break;
624
    }
625
}
626
 
627
static void
628
show_packet_config_cmd (struct packet_config *config)
629
{
630
  char *support = "internal-error";
631
  switch (config->support)
632
    {
633
    case PACKET_ENABLE:
634
      support = "enabled";
635
      break;
636
    case PACKET_DISABLE:
637
      support = "disabled";
638
      break;
639
    case PACKET_SUPPORT_UNKNOWN:
640
      support = "unknown";
641
      break;
642
    }
643
  switch (config->detect)
644
    {
645
    case AUTO_BOOLEAN_AUTO:
646
      printf_filtered ("Support for remote protocol `%s' (%s) packet is auto-detected, currently %s.\n",
647
                       config->name, config->title, support);
648
      break;
649
    case AUTO_BOOLEAN_TRUE:
650
    case AUTO_BOOLEAN_FALSE:
651
      printf_filtered ("Support for remote protocol `%s' (%s) packet is currently %s.\n",
652
                       config->name, config->title, support);
653
      break;
654
    }
655
}
656
 
657
static void
658
add_packet_config_cmd (struct packet_config *config,
659
                       char *name,
660
                       char *title,
661
                       cmd_sfunc_ftype *set_func,
662
                       cmd_sfunc_ftype *show_func,
663
                       struct cmd_list_element **set_remote_list,
664
                       struct cmd_list_element **show_remote_list,
665
                       int legacy)
666
{
667
  struct cmd_list_element *set_cmd;
668
  struct cmd_list_element *show_cmd;
669
  char *set_doc;
670
  char *show_doc;
671
  char *cmd_name;
672
  config->name = name;
673
  config->title = title;
674
  config->detect = AUTO_BOOLEAN_AUTO;
675
  config->support = PACKET_SUPPORT_UNKNOWN;
676
  xasprintf (&set_doc, "Set use of remote protocol `%s' (%s) packet",
677
             name, title);
678
  xasprintf (&show_doc, "Show current use of remote protocol `%s' (%s) packet",
679
             name, title);
680
  /* set/show TITLE-packet {auto,on,off} */
681
  xasprintf (&cmd_name, "%s-packet", title);
682
  add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
683
                                &config->detect, set_doc, show_doc,
684
                                set_func, show_func,
685
                                set_remote_list, show_remote_list);
686
  /* set/show remote NAME-packet {auto,on,off} -- legacy */
687
  if (legacy)
688
    {
689
      char *legacy_name;
690
      xasprintf (&legacy_name, "%s-packet", name);
691
      add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
692
                     set_remote_list);
693
      add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
694
                     show_remote_list);
695
    }
696
}
697
 
698
static enum packet_result
699
packet_ok (const char *buf, struct packet_config *config)
700
{
701
  if (buf[0] != '\0')
702
    {
703
      /* The stub recognized the packet request.  Check that the
704
         operation succeeded. */
705
      switch (config->support)
706
        {
707
        case PACKET_SUPPORT_UNKNOWN:
708
          if (remote_debug)
709
            fprintf_unfiltered (gdb_stdlog,
710
                                    "Packet %s (%s) is supported\n",
711
                                    config->name, config->title);
712
          config->support = PACKET_ENABLE;
713
          break;
714
        case PACKET_DISABLE:
715
          internal_error (__FILE__, __LINE__,
716
                          "packet_ok: attempt to use a disabled packet");
717
          break;
718
        case PACKET_ENABLE:
719
          break;
720
        }
721
      if (buf[0] == 'O' && buf[1] == 'K' && buf[2] == '\0')
722
        /* "OK" - definitly OK. */
723
        return PACKET_OK;
724
      if (buf[0] == 'E'
725
          && isxdigit (buf[1]) && isxdigit (buf[2])
726
          && buf[3] == '\0')
727
        /* "Enn"  - definitly an error. */
728
        return PACKET_ERROR;
729
      /* The packet may or may not be OK.  Just assume it is */
730
      return PACKET_OK;
731
    }
732
  else
733
    {
734
      /* The stub does not support the packet. */
735
      switch (config->support)
736
        {
737
        case PACKET_ENABLE:
738
          if (config->detect == AUTO_BOOLEAN_AUTO)
739
            /* If the stub previously indicated that the packet was
740
               supported then there is a protocol error.. */
741
            error ("Protocol error: %s (%s) conflicting enabled responses.",
742
                   config->name, config->title);
743
          else
744
            /* The user set it wrong. */
745
            error ("Enabled packet %s (%s) not recognized by stub",
746
                   config->name, config->title);
747
          break;
748
        case PACKET_SUPPORT_UNKNOWN:
749
          if (remote_debug)
750
            fprintf_unfiltered (gdb_stdlog,
751
                                "Packet %s (%s) is NOT supported\n",
752
                                config->name, config->title);
753
          config->support = PACKET_DISABLE;
754
          break;
755
        case PACKET_DISABLE:
756
          break;
757
        }
758
      return PACKET_UNKNOWN;
759
    }
760
}
761
 
762
/* Should we try the 'qSymbol' (target symbol lookup service) request? */
763
static struct packet_config remote_protocol_qSymbol;
764
 
765
static void
766
set_remote_protocol_qSymbol_packet_cmd (char *args, int from_tty,
767
                                  struct cmd_list_element *c)
768
{
769
  update_packet_config (&remote_protocol_qSymbol);
770
}
771
 
772
static void
773
show_remote_protocol_qSymbol_packet_cmd (char *args, int from_tty,
774
                                         struct cmd_list_element *c)
775
{
776
  show_packet_config_cmd (&remote_protocol_qSymbol);
777
}
778
 
779
/* Should we try the 'e' (step over range) request? */
780
static struct packet_config remote_protocol_e;
781
 
782
static void
783
set_remote_protocol_e_packet_cmd (char *args, int from_tty,
784
                                  struct cmd_list_element *c)
785
{
786
  update_packet_config (&remote_protocol_e);
787
}
788
 
789
static void
790
show_remote_protocol_e_packet_cmd (char *args, int from_tty,
791
                                   struct cmd_list_element *c)
792
{
793
  show_packet_config_cmd (&remote_protocol_e);
794
}
795
 
796
 
797
/* Should we try the 'E' (step over range / w signal #) request? */
798
static struct packet_config remote_protocol_E;
799
 
800
static void
801
set_remote_protocol_E_packet_cmd (char *args, int from_tty,
802
                                  struct cmd_list_element *c)
803
{
804
  update_packet_config (&remote_protocol_E);
805
}
806
 
807
static void
808
show_remote_protocol_E_packet_cmd (char *args, int from_tty,
809
                                   struct cmd_list_element *c)
810
{
811
  show_packet_config_cmd (&remote_protocol_E);
812
}
813
 
814
 
815
/* Should we try the 'P' (set register) request?  */
816
 
817
static struct packet_config remote_protocol_P;
818
 
819
static void
820
set_remote_protocol_P_packet_cmd (char *args, int from_tty,
821
                                  struct cmd_list_element *c)
822
{
823
  update_packet_config (&remote_protocol_P);
824
}
825
 
826
static void
827
show_remote_protocol_P_packet_cmd (char *args, int from_tty,
828
                                   struct cmd_list_element *c)
829
{
830
  show_packet_config_cmd (&remote_protocol_P);
831
}
832
 
833
/* Should we try one of the 'Z' requests?  */
834
 
835
enum Z_packet_type
836
{
837
  Z_PACKET_SOFTWARE_BP,
838
  Z_PACKET_HARDWARE_BP,
839
  Z_PACKET_WRITE_WP,
840
  Z_PACKET_READ_WP,
841
  Z_PACKET_ACCESS_WP,
842
  NR_Z_PACKET_TYPES
843
};
844
 
845
static struct packet_config remote_protocol_Z[NR_Z_PACKET_TYPES];
846
 
847
/* FIXME: Instead of having all these boiler plate functions, the
848
   command callback should include a context argument. */
849
 
850
static void
851
set_remote_protocol_Z_software_bp_packet_cmd (char *args, int from_tty,
852
                                              struct cmd_list_element *c)
853
{
854
  update_packet_config (&remote_protocol_Z[Z_PACKET_SOFTWARE_BP]);
855
}
856
 
857
static void
858
show_remote_protocol_Z_software_bp_packet_cmd (char *args, int from_tty,
859
                                               struct cmd_list_element *c)
860
{
861
  show_packet_config_cmd (&remote_protocol_Z[Z_PACKET_SOFTWARE_BP]);
862
}
863
 
864
static void
865
set_remote_protocol_Z_hardware_bp_packet_cmd (char *args, int from_tty,
866
                                              struct cmd_list_element *c)
867
{
868
  update_packet_config (&remote_protocol_Z[Z_PACKET_HARDWARE_BP]);
869
}
870
 
871
static void
872
show_remote_protocol_Z_hardware_bp_packet_cmd (char *args, int from_tty,
873
                                               struct cmd_list_element *c)
874
{
875
  show_packet_config_cmd (&remote_protocol_Z[Z_PACKET_HARDWARE_BP]);
876
}
877
 
878
static void
879
set_remote_protocol_Z_write_wp_packet_cmd (char *args, int from_tty,
880
                                              struct cmd_list_element *c)
881
{
882
  update_packet_config (&remote_protocol_Z[Z_PACKET_WRITE_WP]);
883
}
884
 
885
static void
886
show_remote_protocol_Z_write_wp_packet_cmd (char *args, int from_tty,
887
                                            struct cmd_list_element *c)
888
{
889
  show_packet_config_cmd (&remote_protocol_Z[Z_PACKET_WRITE_WP]);
890
}
891
 
892
static void
893
set_remote_protocol_Z_read_wp_packet_cmd (char *args, int from_tty,
894
                                              struct cmd_list_element *c)
895
{
896
  update_packet_config (&remote_protocol_Z[Z_PACKET_READ_WP]);
897
}
898
 
899
static void
900
show_remote_protocol_Z_read_wp_packet_cmd (char *args, int from_tty,
901
                                           struct cmd_list_element *c)
902
{
903
  show_packet_config_cmd (&remote_protocol_Z[Z_PACKET_READ_WP]);
904
}
905
 
906
static void
907
set_remote_protocol_Z_access_wp_packet_cmd (char *args, int from_tty,
908
                                              struct cmd_list_element *c)
909
{
910
  update_packet_config (&remote_protocol_Z[Z_PACKET_ACCESS_WP]);
911
}
912
 
913
static void
914
show_remote_protocol_Z_access_wp_packet_cmd (char *args, int from_tty,
915
                                             struct cmd_list_element *c)
916
{
917
  show_packet_config_cmd (&remote_protocol_Z[Z_PACKET_ACCESS_WP]);
918
}
919
 
920
/* For compatibility with older distributions.  Provide a ``set remote
921
   Z-packet ...'' command that updates all the Z packet types. */
922
 
923
static enum auto_boolean remote_Z_packet_detect;
924
 
925
static void
926
set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
927
                                  struct cmd_list_element *c)
928
{
929
  int i;
930
  for (i = 0; i < NR_Z_PACKET_TYPES; i++)
931
    {
932
      remote_protocol_Z[i].detect = remote_Z_packet_detect;
933
      update_packet_config (&remote_protocol_Z[i]);
934
    }
935
}
936
 
937
static void
938
show_remote_protocol_Z_packet_cmd (char *args, int from_tty,
939
                                   struct cmd_list_element *c)
940
{
941
  int i;
942
  for (i = 0; i < NR_Z_PACKET_TYPES; i++)
943
    {
944
      show_packet_config_cmd (&remote_protocol_Z[i]);
945
    }
946
}
947
 
948
/* Should we try the 'X' (remote binary download) packet?
949
 
950
   This variable (available to the user via "set remote X-packet")
951
   dictates whether downloads are sent in binary (via the 'X' packet).
952
   We assume that the stub can, and attempt to do it. This will be
953
   cleared if the stub does not understand it. This switch is still
954
   needed, though in cases when the packet is supported in the stub,
955
   but the connection does not allow it (i.e., 7-bit serial connection
956
   only). */
957
 
958
static struct packet_config remote_protocol_binary_download;
959
 
960
/* Should we try the 'ThreadInfo' query packet?
961
 
962
   This variable (NOT available to the user: auto-detect only!)
963
   determines whether GDB will use the new, simpler "ThreadInfo"
964
   query or the older, more complex syntax for thread queries.
965
   This is an auto-detect variable (set to true at each connect,
966
   and set to false when the target fails to recognize it).  */
967
 
968
static int use_threadinfo_query;
969
static int use_threadextra_query;
970
 
971
static void
972
set_remote_protocol_binary_download_cmd (char *args,
973
                                         int from_tty,
974
                                         struct cmd_list_element *c)
975
{
976
  update_packet_config (&remote_protocol_binary_download);
977
}
978
 
979
static void
980
show_remote_protocol_binary_download_cmd (char *args, int from_tty,
981
                                          struct cmd_list_element *c)
982
{
983
  show_packet_config_cmd (&remote_protocol_binary_download);
984
}
985
 
986
 
987
/* Tokens for use by the asynchronous signal handlers for SIGINT */
988
static void *sigint_remote_twice_token;
989
static void *sigint_remote_token;
990
 
991
/* These are pointers to hook functions that may be set in order to
992
   modify resume/wait behavior for a particular architecture.  */
993
 
994
void (*target_resume_hook) (void);
995
void (*target_wait_loop_hook) (void);
996
 
997
 
998
 
999
/* These are the threads which we last sent to the remote system.
1000
   -1 for all or -2 for not sent yet.  */
1001
static int general_thread;
1002
static int continue_thread;
1003
 
1004
/* Call this function as a result of
1005
   1) A halt indication (T packet) containing a thread id
1006
   2) A direct query of currthread
1007
   3) Successful execution of set thread
1008
 */
1009
 
1010
static void
1011
record_currthread (int currthread)
1012
{
1013
  general_thread = currthread;
1014
 
1015
  /* If this is a new thread, add it to GDB's thread list.
1016
     If we leave it up to WFI to do this, bad things will happen.  */
1017
  if (!in_thread_list (pid_to_ptid (currthread)))
1018
    {
1019
      add_thread (pid_to_ptid (currthread));
1020
      ui_out_text (uiout, "[New ");
1021
      ui_out_text (uiout, target_pid_to_str (pid_to_ptid (currthread)));
1022
      ui_out_text (uiout, "]\n");
1023
    }
1024
}
1025
 
1026
#define MAGIC_NULL_PID 42000
1027
 
1028
static void
1029
set_thread (int th, int gen)
1030
{
1031
  struct remote_state *rs = get_remote_state ();
1032
  char *buf = alloca (rs->remote_packet_size);
1033
  int state = gen ? general_thread : continue_thread;
1034
 
1035
  if (state == th)
1036
    return;
1037
 
1038
  buf[0] = 'H';
1039
  buf[1] = gen ? 'g' : 'c';
1040
  if (th == MAGIC_NULL_PID)
1041
    {
1042
      buf[2] = '0';
1043
      buf[3] = '\0';
1044
    }
1045
  else if (th < 0)
1046
    sprintf (&buf[2], "-%x", -th);
1047
  else
1048
    sprintf (&buf[2], "%x", th);
1049
  putpkt (buf);
1050
  getpkt (buf, (rs->remote_packet_size), 0);
1051
  if (gen)
1052
    general_thread = th;
1053
  else
1054
    continue_thread = th;
1055
}
1056
 
1057
/*  Return nonzero if the thread TH is still alive on the remote system.  */
1058
 
1059
static int
1060
remote_thread_alive (ptid_t ptid)
1061
{
1062
  int tid = PIDGET (ptid);
1063
  char buf[16];
1064
 
1065
  if (tid < 0)
1066
    sprintf (buf, "T-%08x", -tid);
1067
  else
1068
    sprintf (buf, "T%08x", tid);
1069
  putpkt (buf);
1070
  getpkt (buf, sizeof (buf), 0);
1071
  return (buf[0] == 'O' && buf[1] == 'K');
1072
}
1073
 
1074
/* About these extended threadlist and threadinfo packets.  They are
1075
   variable length packets but, the fields within them are often fixed
1076
   length.  They are redundent enough to send over UDP as is the
1077
   remote protocol in general.  There is a matching unit test module
1078
   in libstub.  */
1079
 
1080
#define OPAQUETHREADBYTES 8
1081
 
1082
/* a 64 bit opaque identifier */
1083
typedef unsigned char threadref[OPAQUETHREADBYTES];
1084
 
1085
/* WARNING: This threadref data structure comes from the remote O.S., libstub
1086
   protocol encoding, and remote.c. it is not particularly changable */
1087
 
1088
/* Right now, the internal structure is int. We want it to be bigger.
1089
   Plan to fix this.
1090
 */
1091
 
1092
typedef int gdb_threadref;      /* internal GDB thread reference */
1093
 
1094
/* gdb_ext_thread_info is an internal GDB data structure which is
1095
   equivalint to the reply of the remote threadinfo packet */
1096
 
1097
struct gdb_ext_thread_info
1098
  {
1099
    threadref threadid;         /* External form of thread reference */
1100
    int active;                 /* Has state interesting to GDB? , regs, stack */
1101
    char display[256];          /* Brief state display, name, blocked/syspended */
1102
    char shortname[32];         /* To be used to name threads */
1103
    char more_display[256];     /* Long info, statistics, queue depth, whatever */
1104
  };
1105
 
1106
/* The volume of remote transfers can be limited by submitting
1107
   a mask containing bits specifying the desired information.
1108
   Use a union of these values as the 'selection' parameter to
1109
   get_thread_info. FIXME: Make these TAG names more thread specific.
1110
 */
1111
 
1112
#define TAG_THREADID 1
1113
#define TAG_EXISTS 2
1114
#define TAG_DISPLAY 4
1115
#define TAG_THREADNAME 8
1116
#define TAG_MOREDISPLAY 16
1117
 
1118
#define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES*2)
1119
 
1120
char *unpack_varlen_hex (char *buff, ULONGEST *result);
1121
 
1122
static char *unpack_nibble (char *buf, int *val);
1123
 
1124
static char *pack_nibble (char *buf, int nibble);
1125
 
1126
static char *pack_hex_byte (char *pkt, int /*unsigned char */ byte);
1127
 
1128
static char *unpack_byte (char *buf, int *value);
1129
 
1130
static char *pack_int (char *buf, int value);
1131
 
1132
static char *unpack_int (char *buf, int *value);
1133
 
1134
static char *unpack_string (char *src, char *dest, int length);
1135
 
1136
static char *pack_threadid (char *pkt, threadref * id);
1137
 
1138
static char *unpack_threadid (char *inbuf, threadref * id);
1139
 
1140
void int_to_threadref (threadref * id, int value);
1141
 
1142
static int threadref_to_int (threadref * ref);
1143
 
1144
static void copy_threadref (threadref * dest, threadref * src);
1145
 
1146
static int threadmatch (threadref * dest, threadref * src);
1147
 
1148
static char *pack_threadinfo_request (char *pkt, int mode, threadref * id);
1149
 
1150
static int remote_unpack_thread_info_response (char *pkt,
1151
                                               threadref * expectedref,
1152
                                               struct gdb_ext_thread_info
1153
                                               *info);
1154
 
1155
 
1156
static int remote_get_threadinfo (threadref * threadid, int fieldset,   /*TAG mask */
1157
                                  struct gdb_ext_thread_info *info);
1158
 
1159
static int adapt_remote_get_threadinfo (gdb_threadref * ref,
1160
                                        int selection,
1161
                                        struct gdb_ext_thread_info *info);
1162
 
1163
static char *pack_threadlist_request (char *pkt, int startflag,
1164
                                      int threadcount,
1165
                                      threadref * nextthread);
1166
 
1167
static int parse_threadlist_response (char *pkt,
1168
                                      int result_limit,
1169
                                      threadref * original_echo,
1170
                                      threadref * resultlist, int *doneflag);
1171
 
1172
static int remote_get_threadlist (int startflag,
1173
                                  threadref * nextthread,
1174
                                  int result_limit,
1175
                                  int *done,
1176
                                  int *result_count, threadref * threadlist);
1177
 
1178
typedef int (*rmt_thread_action) (threadref * ref, void *context);
1179
 
1180
static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1181
                                       void *context, int looplimit);
1182
 
1183
static int remote_newthread_step (threadref * ref, void *context);
1184
 
1185
/* encode 64 bits in 16 chars of hex */
1186
 
1187
static const char hexchars[] = "0123456789abcdef";
1188
 
1189
static int
1190
ishex (int ch, int *val)
1191
{
1192
  if ((ch >= 'a') && (ch <= 'f'))
1193
    {
1194
      *val = ch - 'a' + 10;
1195
      return 1;
1196
    }
1197
  if ((ch >= 'A') && (ch <= 'F'))
1198
    {
1199
      *val = ch - 'A' + 10;
1200
      return 1;
1201
    }
1202
  if ((ch >= '0') && (ch <= '9'))
1203
    {
1204
      *val = ch - '0';
1205
      return 1;
1206
    }
1207
  return 0;
1208
}
1209
 
1210
static int
1211
stubhex (int ch)
1212
{
1213
  if (ch >= 'a' && ch <= 'f')
1214
    return ch - 'a' + 10;
1215
  if (ch >= '0' && ch <= '9')
1216
    return ch - '0';
1217
  if (ch >= 'A' && ch <= 'F')
1218
    return ch - 'A' + 10;
1219
  return -1;
1220
}
1221
 
1222
static int
1223
stub_unpack_int (char *buff, int fieldlength)
1224
{
1225
  int nibble;
1226
  int retval = 0;
1227
 
1228
  while (fieldlength)
1229
    {
1230
      nibble = stubhex (*buff++);
1231
      retval |= nibble;
1232
      fieldlength--;
1233
      if (fieldlength)
1234
        retval = retval << 4;
1235
    }
1236
  return retval;
1237
}
1238
 
1239
char *
1240
unpack_varlen_hex (char *buff,  /* packet to parse */
1241
                   ULONGEST *result)
1242
{
1243
  int nibble;
1244
  int retval = 0;
1245
 
1246
  while (ishex (*buff, &nibble))
1247
    {
1248
      buff++;
1249
      retval = retval << 4;
1250
      retval |= nibble & 0x0f;
1251
    }
1252
  *result = retval;
1253
  return buff;
1254
}
1255
 
1256
static char *
1257
unpack_nibble (char *buf, int *val)
1258
{
1259
  ishex (*buf++, val);
1260
  return buf;
1261
}
1262
 
1263
static char *
1264
pack_nibble (char *buf, int nibble)
1265
{
1266
  *buf++ = hexchars[(nibble & 0x0f)];
1267
  return buf;
1268
}
1269
 
1270
static char *
1271
pack_hex_byte (char *pkt, int byte)
1272
{
1273
  *pkt++ = hexchars[(byte >> 4) & 0xf];
1274
  *pkt++ = hexchars[(byte & 0xf)];
1275
  return pkt;
1276
}
1277
 
1278
static char *
1279
unpack_byte (char *buf, int *value)
1280
{
1281
  *value = stub_unpack_int (buf, 2);
1282
  return buf + 2;
1283
}
1284
 
1285
static char *
1286
pack_int (char *buf, int value)
1287
{
1288
  buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1289
  buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1290
  buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1291
  buf = pack_hex_byte (buf, (value & 0xff));
1292
  return buf;
1293
}
1294
 
1295
static char *
1296
unpack_int (char *buf, int *value)
1297
{
1298
  *value = stub_unpack_int (buf, 8);
1299
  return buf + 8;
1300
}
1301
 
1302
#if 0                           /* currently unused, uncomment when needed */
1303
static char *pack_string (char *pkt, char *string);
1304
 
1305
static char *
1306
pack_string (char *pkt, char *string)
1307
{
1308
  char ch;
1309
  int len;
1310
 
1311
  len = strlen (string);
1312
  if (len > 200)
1313
    len = 200;                  /* Bigger than most GDB packets, junk??? */
1314
  pkt = pack_hex_byte (pkt, len);
1315
  while (len-- > 0)
1316
    {
1317
      ch = *string++;
1318
      if ((ch == '\0') || (ch == '#'))
1319
        ch = '*';               /* Protect encapsulation */
1320
      *pkt++ = ch;
1321
    }
1322
  return pkt;
1323
}
1324
#endif /* 0 (unused) */
1325
 
1326
static char *
1327
unpack_string (char *src, char *dest, int length)
1328
{
1329
  while (length--)
1330
    *dest++ = *src++;
1331
  *dest = '\0';
1332
  return src;
1333
}
1334
 
1335
static char *
1336
pack_threadid (char *pkt, threadref *id)
1337
{
1338
  char *limit;
1339
  unsigned char *altid;
1340
 
1341
  altid = (unsigned char *) id;
1342
  limit = pkt + BUF_THREAD_ID_SIZE;
1343
  while (pkt < limit)
1344
    pkt = pack_hex_byte (pkt, *altid++);
1345
  return pkt;
1346
}
1347
 
1348
 
1349
static char *
1350
unpack_threadid (char *inbuf, threadref *id)
1351
{
1352
  char *altref;
1353
  char *limit = inbuf + BUF_THREAD_ID_SIZE;
1354
  int x, y;
1355
 
1356
  altref = (char *) id;
1357
 
1358
  while (inbuf < limit)
1359
    {
1360
      x = stubhex (*inbuf++);
1361
      y = stubhex (*inbuf++);
1362
      *altref++ = (x << 4) | y;
1363
    }
1364
  return inbuf;
1365
}
1366
 
1367
/* Externally, threadrefs are 64 bits but internally, they are still
1368
   ints. This is due to a mismatch of specifications.  We would like
1369
   to use 64bit thread references internally.  This is an adapter
1370
   function.  */
1371
 
1372
void
1373
int_to_threadref (threadref *id, int value)
1374
{
1375
  unsigned char *scan;
1376
 
1377
  scan = (unsigned char *) id;
1378
  {
1379
    int i = 4;
1380
    while (i--)
1381
      *scan++ = 0;
1382
  }
1383
  *scan++ = (value >> 24) & 0xff;
1384
  *scan++ = (value >> 16) & 0xff;
1385
  *scan++ = (value >> 8) & 0xff;
1386
  *scan++ = (value & 0xff);
1387
}
1388
 
1389
static int
1390
threadref_to_int (threadref *ref)
1391
{
1392
  int i, value = 0;
1393
  unsigned char *scan;
1394
 
1395
  scan = (char *) ref;
1396
  scan += 4;
1397
  i = 4;
1398
  while (i-- > 0)
1399
    value = (value << 8) | ((*scan++) & 0xff);
1400
  return value;
1401
}
1402
 
1403
static void
1404
copy_threadref (threadref *dest, threadref *src)
1405
{
1406
  int i;
1407
  unsigned char *csrc, *cdest;
1408
 
1409
  csrc = (unsigned char *) src;
1410
  cdest = (unsigned char *) dest;
1411
  i = 8;
1412
  while (i--)
1413
    *cdest++ = *csrc++;
1414
}
1415
 
1416
static int
1417
threadmatch (threadref *dest, threadref *src)
1418
{
1419
  /* things are broken right now, so just assume we got a match */
1420
#if 0
1421
  unsigned char *srcp, *destp;
1422
  int i, result;
1423
  srcp = (char *) src;
1424
  destp = (char *) dest;
1425
 
1426
  result = 1;
1427
  while (i-- > 0)
1428
    result &= (*srcp++ == *destp++) ? 1 : 0;
1429
  return result;
1430
#endif
1431
  return 1;
1432
}
1433
 
1434
/*
1435
   threadid:1,        # always request threadid
1436
   context_exists:2,
1437
   display:4,
1438
   unique_name:8,
1439
   more_display:16
1440
 */
1441
 
1442
/* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
1443
 
1444
static char *
1445
pack_threadinfo_request (char *pkt, int mode, threadref *id)
1446
{
1447
  *pkt++ = 'q';                 /* Info Query */
1448
  *pkt++ = 'P';                 /* process or thread info */
1449
  pkt = pack_int (pkt, mode);   /* mode */
1450
  pkt = pack_threadid (pkt, id);        /* threadid */
1451
  *pkt = '\0';                  /* terminate */
1452
  return pkt;
1453
}
1454
 
1455
/* These values tag the fields in a thread info response packet */
1456
/* Tagging the fields allows us to request specific fields and to
1457
   add more fields as time goes by */
1458
 
1459
#define TAG_THREADID 1          /* Echo the thread identifier */
1460
#define TAG_EXISTS 2            /* Is this process defined enough to
1461
                                   fetch registers and its stack */
1462
#define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
1463
#define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is */
1464
#define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about 
1465
                                   the process */
1466
 
1467
static int
1468
remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1469
                                    struct gdb_ext_thread_info *info)
1470
{
1471
  struct remote_state *rs = get_remote_state ();
1472
  int mask, length;
1473
  unsigned int tag;
1474
  threadref ref;
1475
  char *limit = pkt + (rs->remote_packet_size); /* plausable parsing limit */
1476
  int retval = 1;
1477
 
1478
  /* info->threadid = 0; FIXME: implement zero_threadref */
1479
  info->active = 0;
1480
  info->display[0] = '\0';
1481
  info->shortname[0] = '\0';
1482
  info->more_display[0] = '\0';
1483
 
1484
  /* Assume the characters indicating the packet type have been stripped */
1485
  pkt = unpack_int (pkt, &mask);        /* arg mask */
1486
  pkt = unpack_threadid (pkt, &ref);
1487
 
1488
  if (mask == 0)
1489
    warning ("Incomplete response to threadinfo request\n");
1490
  if (!threadmatch (&ref, expectedref))
1491
    {                           /* This is an answer to a different request */
1492
      warning ("ERROR RMT Thread info mismatch\n");
1493
      return 0;
1494
    }
1495
  copy_threadref (&info->threadid, &ref);
1496
 
1497
  /* Loop on tagged fields , try to bail if somthing goes wrong */
1498
 
1499
  while ((pkt < limit) && mask && *pkt)         /* packets are terminated with nulls */
1500
    {
1501
      pkt = unpack_int (pkt, &tag);     /* tag */
1502
      pkt = unpack_byte (pkt, &length);         /* length */
1503
      if (!(tag & mask))        /* tags out of synch with mask */
1504
        {
1505
          warning ("ERROR RMT: threadinfo tag mismatch\n");
1506
          retval = 0;
1507
          break;
1508
        }
1509
      if (tag == TAG_THREADID)
1510
        {
1511
          if (length != 16)
1512
            {
1513
              warning ("ERROR RMT: length of threadid is not 16\n");
1514
              retval = 0;
1515
              break;
1516
            }
1517
          pkt = unpack_threadid (pkt, &ref);
1518
          mask = mask & ~TAG_THREADID;
1519
          continue;
1520
        }
1521
      if (tag == TAG_EXISTS)
1522
        {
1523
          info->active = stub_unpack_int (pkt, length);
1524
          pkt += length;
1525
          mask = mask & ~(TAG_EXISTS);
1526
          if (length > 8)
1527
            {
1528
              warning ("ERROR RMT: 'exists' length too long\n");
1529
              retval = 0;
1530
              break;
1531
            }
1532
          continue;
1533
        }
1534
      if (tag == TAG_THREADNAME)
1535
        {
1536
          pkt = unpack_string (pkt, &info->shortname[0], length);
1537
          mask = mask & ~TAG_THREADNAME;
1538
          continue;
1539
        }
1540
      if (tag == TAG_DISPLAY)
1541
        {
1542
          pkt = unpack_string (pkt, &info->display[0], length);
1543
          mask = mask & ~TAG_DISPLAY;
1544
          continue;
1545
        }
1546
      if (tag == TAG_MOREDISPLAY)
1547
        {
1548
          pkt = unpack_string (pkt, &info->more_display[0], length);
1549
          mask = mask & ~TAG_MOREDISPLAY;
1550
          continue;
1551
        }
1552
      warning ("ERROR RMT: unknown thread info tag\n");
1553
      break;                    /* Not a tag we know about */
1554
    }
1555
  return retval;
1556
}
1557
 
1558
static int
1559
remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
1560
                       struct gdb_ext_thread_info *info)
1561
{
1562
  struct remote_state *rs = get_remote_state ();
1563
  int result;
1564
  char *threadinfo_pkt = alloca (rs->remote_packet_size);
1565
 
1566
  pack_threadinfo_request (threadinfo_pkt, fieldset, threadid);
1567
  putpkt (threadinfo_pkt);
1568
  getpkt (threadinfo_pkt, (rs->remote_packet_size), 0);
1569
  result = remote_unpack_thread_info_response (threadinfo_pkt + 2, threadid,
1570
                                               info);
1571
  return result;
1572
}
1573
 
1574
/* Unfortunately, 61 bit thread-ids are bigger than the internal
1575
   representation of a threadid.  */
1576
 
1577
static int
1578
adapt_remote_get_threadinfo (gdb_threadref *ref, int selection,
1579
                             struct gdb_ext_thread_info *info)
1580
{
1581
  threadref lclref;
1582
 
1583
  int_to_threadref (&lclref, *ref);
1584
  return remote_get_threadinfo (&lclref, selection, info);
1585
}
1586
 
1587
/*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
1588
 
1589
static char *
1590
pack_threadlist_request (char *pkt, int startflag, int threadcount,
1591
                         threadref *nextthread)
1592
{
1593
  *pkt++ = 'q';                 /* info query packet */
1594
  *pkt++ = 'L';                 /* Process LIST or threadLIST request */
1595
  pkt = pack_nibble (pkt, startflag);   /* initflag 1 bytes */
1596
  pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
1597
  pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
1598
  *pkt = '\0';
1599
  return pkt;
1600
}
1601
 
1602
/* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
1603
 
1604
static int
1605
parse_threadlist_response (char *pkt, int result_limit,
1606
                           threadref *original_echo, threadref *resultlist,
1607
                           int *doneflag)
1608
{
1609
  struct remote_state *rs = get_remote_state ();
1610
  char *limit;
1611
  int count, resultcount, done;
1612
 
1613
  resultcount = 0;
1614
  /* Assume the 'q' and 'M chars have been stripped.  */
1615
  limit = pkt + ((rs->remote_packet_size) - BUF_THREAD_ID_SIZE);                /* done parse past here */
1616
  pkt = unpack_byte (pkt, &count);      /* count field */
1617
  pkt = unpack_nibble (pkt, &done);
1618
  /* The first threadid is the argument threadid.  */
1619
  pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
1620
  while ((count-- > 0) && (pkt < limit))
1621
    {
1622
      pkt = unpack_threadid (pkt, resultlist++);
1623
      if (resultcount++ >= result_limit)
1624
        break;
1625
    }
1626
  if (doneflag)
1627
    *doneflag = done;
1628
  return resultcount;
1629
}
1630
 
1631
static int
1632
remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
1633
                       int *done, int *result_count, threadref *threadlist)
1634
{
1635
  struct remote_state *rs = get_remote_state ();
1636
  static threadref echo_nextthread;
1637
  char *threadlist_packet = alloca (rs->remote_packet_size);
1638
  char *t_response = alloca (rs->remote_packet_size);
1639
  int result = 1;
1640
 
1641
  /* Trancate result limit to be smaller than the packet size */
1642
  if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= (rs->remote_packet_size))
1643
    result_limit = ((rs->remote_packet_size) / BUF_THREAD_ID_SIZE) - 2;
1644
 
1645
  pack_threadlist_request (threadlist_packet,
1646
                           startflag, result_limit, nextthread);
1647
  putpkt (threadlist_packet);
1648
  getpkt (t_response, (rs->remote_packet_size), 0);
1649
 
1650
  *result_count =
1651
    parse_threadlist_response (t_response + 2, result_limit, &echo_nextthread,
1652
                               threadlist, done);
1653
 
1654
  if (!threadmatch (&echo_nextthread, nextthread))
1655
    {
1656
      /* FIXME: This is a good reason to drop the packet */
1657
      /* Possably, there is a duplicate response */
1658
      /* Possabilities :
1659
         retransmit immediatly - race conditions
1660
         retransmit after timeout - yes
1661
         exit
1662
         wait for packet, then exit
1663
       */
1664
      warning ("HMM: threadlist did not echo arg thread, dropping it\n");
1665
      return 0;                  /* I choose simply exiting */
1666
    }
1667
  if (*result_count <= 0)
1668
    {
1669
      if (*done != 1)
1670
        {
1671
          warning ("RMT ERROR : failed to get remote thread list\n");
1672
          result = 0;
1673
        }
1674
      return result;            /* break; */
1675
    }
1676
  if (*result_count > result_limit)
1677
    {
1678
      *result_count = 0;
1679
      warning ("RMT ERROR: threadlist response longer than requested\n");
1680
      return 0;
1681
    }
1682
  return result;
1683
}
1684
 
1685
/* This is the interface between remote and threads, remotes upper interface */
1686
 
1687
/* remote_find_new_threads retrieves the thread list and for each
1688
   thread in the list, looks up the thread in GDB's internal list,
1689
   ading the thread if it does not already exist.  This involves
1690
   getting partial thread lists from the remote target so, polling the
1691
   quit_flag is required.  */
1692
 
1693
 
1694
/* About this many threadisds fit in a packet. */
1695
 
1696
#define MAXTHREADLISTRESULTS 32
1697
 
1698
static int
1699
remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
1700
                            int looplimit)
1701
{
1702
  int done, i, result_count;
1703
  int startflag = 1;
1704
  int result = 1;
1705
  int loopcount = 0;
1706
  static threadref nextthread;
1707
  static threadref resultthreadlist[MAXTHREADLISTRESULTS];
1708
 
1709
  done = 0;
1710
  while (!done)
1711
    {
1712
      if (loopcount++ > looplimit)
1713
        {
1714
          result = 0;
1715
          warning ("Remote fetch threadlist -infinite loop-\n");
1716
          break;
1717
        }
1718
      if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
1719
                                  &done, &result_count, resultthreadlist))
1720
        {
1721
          result = 0;
1722
          break;
1723
        }
1724
      /* clear for later iterations */
1725
      startflag = 0;
1726
      /* Setup to resume next batch of thread references, set nextthread.  */
1727
      if (result_count >= 1)
1728
        copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
1729
      i = 0;
1730
      while (result_count--)
1731
        if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
1732
          break;
1733
    }
1734
  return result;
1735
}
1736
 
1737
static int
1738
remote_newthread_step (threadref *ref, void *context)
1739
{
1740
  ptid_t ptid;
1741
 
1742
  ptid = pid_to_ptid (threadref_to_int (ref));
1743
 
1744
  if (!in_thread_list (ptid))
1745
    add_thread (ptid);
1746
  return 1;                     /* continue iterator */
1747
}
1748
 
1749
#define CRAZY_MAX_THREADS 1000
1750
 
1751
static ptid_t
1752
remote_current_thread (ptid_t oldpid)
1753
{
1754
  struct remote_state *rs = get_remote_state ();
1755
  char *buf = alloca (rs->remote_packet_size);
1756
 
1757
  putpkt ("qC");
1758
  getpkt (buf, (rs->remote_packet_size), 0);
1759
  if (buf[0] == 'Q' && buf[1] == 'C')
1760
    return pid_to_ptid (strtol (&buf[2], NULL, 16));
1761
  else
1762
    return oldpid;
1763
}
1764
 
1765
/* Find new threads for info threads command.
1766
 * Original version, using John Metzler's thread protocol.
1767
 */
1768
 
1769
static void
1770
remote_find_new_threads (void)
1771
{
1772
  remote_threadlist_iterator (remote_newthread_step, 0,
1773
                              CRAZY_MAX_THREADS);
1774
  if (PIDGET (inferior_ptid) == MAGIC_NULL_PID) /* ack ack ack */
1775
    inferior_ptid = remote_current_thread (inferior_ptid);
1776
}
1777
 
1778
/*
1779
 * Find all threads for info threads command.
1780
 * Uses new thread protocol contributed by Cisco.
1781
 * Falls back and attempts to use the older method (above)
1782
 * if the target doesn't respond to the new method.
1783
 */
1784
 
1785
static void
1786
remote_threads_info (void)
1787
{
1788
  struct remote_state *rs = get_remote_state ();
1789
  char *buf = alloca (rs->remote_packet_size);
1790
  char *bufp;
1791
  int tid;
1792
 
1793
  if (remote_desc == 0)          /* paranoia */
1794
    error ("Command can only be used when connected to the remote target.");
1795
 
1796
  if (use_threadinfo_query)
1797
    {
1798
      putpkt ("qfThreadInfo");
1799
      bufp = buf;
1800
      getpkt (bufp, (rs->remote_packet_size), 0);
1801
      if (bufp[0] != '\0')               /* q packet recognized */
1802
        {
1803
          while (*bufp++ == 'm')        /* reply contains one or more TID */
1804
            {
1805
              do
1806
                {
1807
                  tid = strtol (bufp, &bufp, 16);
1808
                  if (tid != 0 && !in_thread_list (pid_to_ptid (tid)))
1809
                    add_thread (pid_to_ptid (tid));
1810
                }
1811
              while (*bufp++ == ',');   /* comma-separated list */
1812
              putpkt ("qsThreadInfo");
1813
              bufp = buf;
1814
              getpkt (bufp, (rs->remote_packet_size), 0);
1815
            }
1816
          return;       /* done */
1817
        }
1818
    }
1819
 
1820
  /* Else fall back to old method based on jmetzler protocol. */
1821
  use_threadinfo_query = 0;
1822
  remote_find_new_threads ();
1823
  return;
1824
}
1825
 
1826
/*
1827
 * Collect a descriptive string about the given thread.
1828
 * The target may say anything it wants to about the thread
1829
 * (typically info about its blocked / runnable state, name, etc.).
1830
 * This string will appear in the info threads display.
1831
 *
1832
 * Optional: targets are not required to implement this function.
1833
 */
1834
 
1835
static char *
1836
remote_threads_extra_info (struct thread_info *tp)
1837
{
1838
  struct remote_state *rs = get_remote_state ();
1839
  int result;
1840
  int set;
1841
  threadref id;
1842
  struct gdb_ext_thread_info threadinfo;
1843
  static char display_buf[100]; /* arbitrary... */
1844
  char *bufp = alloca (rs->remote_packet_size);
1845
  int n = 0;                    /* position in display_buf */
1846
 
1847
  if (remote_desc == 0)          /* paranoia */
1848
    internal_error (__FILE__, __LINE__,
1849
                    "remote_threads_extra_info");
1850
 
1851
  if (use_threadextra_query)
1852
    {
1853
      sprintf (bufp, "qThreadExtraInfo,%x", PIDGET (tp->ptid));
1854
      putpkt (bufp);
1855
      getpkt (bufp, (rs->remote_packet_size), 0);
1856
      if (bufp[0] != 0)
1857
        {
1858
          n = min (strlen (bufp) / 2, sizeof (display_buf));
1859
          result = hex2bin (bufp, display_buf, n);
1860
          display_buf [result] = '\0';
1861
          return display_buf;
1862
        }
1863
    }
1864
 
1865
  /* If the above query fails, fall back to the old method.  */
1866
  use_threadextra_query = 0;
1867
  set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
1868
    | TAG_MOREDISPLAY | TAG_DISPLAY;
1869
  int_to_threadref (&id, PIDGET (tp->ptid));
1870
  if (remote_get_threadinfo (&id, set, &threadinfo))
1871
    if (threadinfo.active)
1872
      {
1873
        if (*threadinfo.shortname)
1874
          n += sprintf(&display_buf[0], " Name: %s,", threadinfo.shortname);
1875
        if (*threadinfo.display)
1876
          n += sprintf(&display_buf[n], " State: %s,", threadinfo.display);
1877
        if (*threadinfo.more_display)
1878
          n += sprintf(&display_buf[n], " Priority: %s",
1879
                       threadinfo.more_display);
1880
 
1881
        if (n > 0)
1882
          {
1883
            /* for purely cosmetic reasons, clear up trailing commas */
1884
            if (',' == display_buf[n-1])
1885
              display_buf[n-1] = ' ';
1886
            return display_buf;
1887
          }
1888
      }
1889
  return NULL;
1890
}
1891
 
1892
 
1893
 
1894
/*  Restart the remote side; this is an extended protocol operation.  */
1895
 
1896
static void
1897
extended_remote_restart (void)
1898
{
1899
  struct remote_state *rs = get_remote_state ();
1900
  char *buf = alloca (rs->remote_packet_size);
1901
 
1902
  /* Send the restart command; for reasons I don't understand the
1903
     remote side really expects a number after the "R".  */
1904
  buf[0] = 'R';
1905
  sprintf (&buf[1], "%x", 0);
1906
  putpkt (buf);
1907
 
1908
  /* Now query for status so this looks just like we restarted
1909
     gdbserver from scratch.  */
1910
  putpkt ("?");
1911
  getpkt (buf, (rs->remote_packet_size), 0);
1912
}
1913
 
1914
/* Clean up connection to a remote debugger.  */
1915
 
1916
/* ARGSUSED */
1917
static void
1918
remote_close (int quitting)
1919
{
1920
  if (remote_desc)
1921
    serial_close (remote_desc);
1922
  remote_desc = NULL;
1923
}
1924
 
1925
/* Query the remote side for the text, data and bss offsets. */
1926
 
1927
static void
1928
get_offsets (void)
1929
{
1930
  struct remote_state *rs = get_remote_state ();
1931
  char *buf = alloca (rs->remote_packet_size);
1932
  char *ptr;
1933
  int lose;
1934
  CORE_ADDR text_addr, data_addr, bss_addr;
1935
  struct section_offsets *offs;
1936
 
1937
  putpkt ("qOffsets");
1938
 
1939
  getpkt (buf, (rs->remote_packet_size), 0);
1940
 
1941
  if (buf[0] == '\000')
1942
    return;                     /* Return silently.  Stub doesn't support
1943
                                   this command. */
1944
  if (buf[0] == 'E')
1945
    {
1946
      warning ("Remote failure reply: %s", buf);
1947
      return;
1948
    }
1949
 
1950
  /* Pick up each field in turn.  This used to be done with scanf, but
1951
     scanf will make trouble if CORE_ADDR size doesn't match
1952
     conversion directives correctly.  The following code will work
1953
     with any size of CORE_ADDR.  */
1954
  text_addr = data_addr = bss_addr = 0;
1955
  ptr = buf;
1956
  lose = 0;
1957
 
1958
  if (strncmp (ptr, "Text=", 5) == 0)
1959
    {
1960
      ptr += 5;
1961
      /* Don't use strtol, could lose on big values.  */
1962
      while (*ptr && *ptr != ';')
1963
        text_addr = (text_addr << 4) + fromhex (*ptr++);
1964
    }
1965
  else
1966
    lose = 1;
1967
 
1968
  if (!lose && strncmp (ptr, ";Data=", 6) == 0)
1969
    {
1970
      ptr += 6;
1971
      while (*ptr && *ptr != ';')
1972
        data_addr = (data_addr << 4) + fromhex (*ptr++);
1973
    }
1974
  else
1975
    lose = 1;
1976
 
1977
  if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
1978
    {
1979
      ptr += 5;
1980
      while (*ptr && *ptr != ';')
1981
        bss_addr = (bss_addr << 4) + fromhex (*ptr++);
1982
    }
1983
  else
1984
    lose = 1;
1985
 
1986
  if (lose)
1987
    error ("Malformed response to offset query, %s", buf);
1988
 
1989
  if (symfile_objfile == NULL)
1990
    return;
1991
 
1992
  offs = (struct section_offsets *) alloca (SIZEOF_SECTION_OFFSETS);
1993
  memcpy (offs, symfile_objfile->section_offsets, SIZEOF_SECTION_OFFSETS);
1994
 
1995
  offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
1996
 
1997
  /* This is a temporary kludge to force data and bss to use the same offsets
1998
     because that's what nlmconv does now.  The real solution requires changes
1999
     to the stub and remote.c that I don't have time to do right now.  */
2000
 
2001
  offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2002
  offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2003
 
2004
  objfile_relocate (symfile_objfile, offs);
2005
}
2006
 
2007
/*
2008
 * Cisco version of section offsets:
2009
 *
2010
 * Instead of having GDB query the target for the section offsets,
2011
 * Cisco lets the target volunteer the information!  It's also in
2012
 * a different format, so here are the functions that will decode
2013
 * a section offset packet from a Cisco target.
2014
 */
2015
 
2016
/*
2017
 * Function: remote_cisco_section_offsets
2018
 *
2019
 * Returns:  zero for success, non-zero for failure
2020
 */
2021
 
2022
static int
2023
remote_cisco_section_offsets (bfd_vma text_addr,
2024
                              bfd_vma data_addr,
2025
                              bfd_vma bss_addr,
2026
                              bfd_signed_vma *text_offs,
2027
                              bfd_signed_vma *data_offs,
2028
                              bfd_signed_vma *bss_offs)
2029
{
2030
  bfd_vma text_base, data_base, bss_base;
2031
  struct minimal_symbol *start;
2032
  asection *sect;
2033
  bfd *abfd;
2034
  int len;
2035
 
2036
  if (symfile_objfile == NULL)
2037
    return -1;                  /* no can do nothin' */
2038
 
2039
  start = lookup_minimal_symbol ("_start", NULL, NULL);
2040
  if (start == NULL)
2041
    return -1;                  /* Can't find "_start" symbol */
2042
 
2043
  data_base = bss_base = 0;
2044
  text_base = SYMBOL_VALUE_ADDRESS (start);
2045
 
2046
  abfd = symfile_objfile->obfd;
2047
  for (sect = abfd->sections;
2048
       sect != 0;
2049
       sect = sect->next)
2050
    {
2051
      const char *p = bfd_get_section_name (abfd, sect);
2052
      len = strlen (p);
2053
      if (strcmp (p + len - 4, "data") == 0)     /* ends in "data" */
2054
        if (data_base == 0 ||
2055
            data_base > bfd_get_section_vma (abfd, sect))
2056
          data_base = bfd_get_section_vma (abfd, sect);
2057
      if (strcmp (p + len - 3, "bss") == 0)      /* ends in "bss" */
2058
        if (bss_base == 0 ||
2059
            bss_base > bfd_get_section_vma (abfd, sect))
2060
          bss_base = bfd_get_section_vma (abfd, sect);
2061
    }
2062
  *text_offs = text_addr - text_base;
2063
  *data_offs = data_addr - data_base;
2064
  *bss_offs = bss_addr - bss_base;
2065
  if (remote_debug)
2066
    {
2067
      char tmp[128];
2068
 
2069
      sprintf (tmp, "VMA:          text = 0x");
2070
      sprintf_vma (tmp + strlen (tmp), text_addr);
2071
      sprintf (tmp + strlen (tmp), " data = 0x");
2072
      sprintf_vma (tmp + strlen (tmp), data_addr);
2073
      sprintf (tmp + strlen (tmp), " bss = 0x");
2074
      sprintf_vma (tmp + strlen (tmp), bss_addr);
2075
      fprintf_filtered (gdb_stdlog, tmp);
2076
      fprintf_filtered (gdb_stdlog,
2077
                        "Reloc offset: text = 0x%s data = 0x%s bss = 0x%s\n",
2078
                        paddr_nz (*text_offs),
2079
                        paddr_nz (*data_offs),
2080
                        paddr_nz (*bss_offs));
2081
    }
2082
 
2083
  return 0;
2084
}
2085
 
2086
/*
2087
 * Function: remote_cisco_objfile_relocate
2088
 *
2089
 * Relocate the symbol file for a remote target.
2090
 */
2091
 
2092
void
2093
remote_cisco_objfile_relocate (bfd_signed_vma text_off, bfd_signed_vma data_off,
2094
                               bfd_signed_vma bss_off)
2095
{
2096
  struct section_offsets *offs;
2097
 
2098
  if (text_off != 0 || data_off != 0 || bss_off != 0)
2099
    {
2100
      /* FIXME: This code assumes gdb-stabs.h is being used; it's
2101
         broken for xcoff, dwarf, sdb-coff, etc.  But there is no
2102
         simple canonical representation for this stuff.  */
2103
 
2104
      offs = (struct section_offsets *) alloca (SIZEOF_SECTION_OFFSETS);
2105
      memcpy (offs, symfile_objfile->section_offsets, SIZEOF_SECTION_OFFSETS);
2106
 
2107
      offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_off;
2108
      offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_off;
2109
      offs->offsets[SECT_OFF_BSS (symfile_objfile)] = bss_off;
2110
 
2111
      /* First call the standard objfile_relocate.  */
2112
      objfile_relocate (symfile_objfile, offs);
2113
 
2114
      /* Now we need to fix up the section entries already attached to
2115
         the exec target.  These entries will control memory transfers
2116
         from the exec file.  */
2117
 
2118
      exec_set_section_offsets (text_off, data_off, bss_off);
2119
    }
2120
}
2121
 
2122
/* Stub for catch_errors.  */
2123
 
2124
static int
2125
remote_start_remote_dummy (struct ui_out *uiout, void *dummy)
2126
{
2127
  start_remote ();              /* Initialize gdb process mechanisms */
2128
  /* NOTE: Return something >=0.  A -ve value is reserved for
2129
     catch_exceptions.  */
2130
  return 1;
2131
}
2132
 
2133
static int
2134
remote_start_remote (struct ui_out *uiout, void *dummy)
2135
{
2136
  immediate_quit++;             /* Allow user to interrupt it */
2137
 
2138
  /* Ack any packet which the remote side has already sent.  */
2139
  serial_write (remote_desc, "+", 1);
2140
 
2141
  /* Let the stub know that we want it to return the thread.  */
2142
  set_thread (-1, 0);
2143
 
2144
  inferior_ptid = remote_current_thread (inferior_ptid);
2145
 
2146
  get_offsets ();               /* Get text, data & bss offsets */
2147
 
2148
  putpkt ("?");                 /* initiate a query from remote machine */
2149
  immediate_quit--;
2150
 
2151
  /* NOTE: See comment above in remote_start_remote_dummy().  This
2152
     function returns something >=0.  */
2153
  return remote_start_remote_dummy (uiout, dummy);
2154
}
2155
 
2156
/* Open a connection to a remote debugger.
2157
   NAME is the filename used for communication.  */
2158
 
2159
static void
2160
remote_open (char *name, int from_tty)
2161
{
2162
  remote_open_1 (name, from_tty, &remote_ops, 0, 0);
2163
}
2164
 
2165
/* Just like remote_open, but with asynchronous support. */
2166
static void
2167
remote_async_open (char *name, int from_tty)
2168
{
2169
  remote_open_1 (name, from_tty, &remote_async_ops, 0, 1);
2170
}
2171
 
2172
/* Open a connection to a remote debugger using the extended
2173
   remote gdb protocol.  NAME is the filename used for communication.  */
2174
 
2175
static void
2176
extended_remote_open (char *name, int from_tty)
2177
{
2178
  remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */,
2179
 
2180
}
2181
 
2182
/* Just like extended_remote_open, but with asynchronous support. */
2183
static void
2184
extended_remote_async_open (char *name, int from_tty)
2185
{
2186
  remote_open_1 (name, from_tty, &extended_async_remote_ops,
2187
                 1 /*extended_p */, 1 /* async_p */);
2188
}
2189
 
2190
/* Generic code for opening a connection to a remote target.  */
2191
 
2192
static void
2193
init_all_packet_configs (void)
2194
{
2195
  int i;
2196
  update_packet_config (&remote_protocol_e);
2197
  update_packet_config (&remote_protocol_E);
2198
  update_packet_config (&remote_protocol_P);
2199
  update_packet_config (&remote_protocol_qSymbol);
2200
  for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2201
    update_packet_config (&remote_protocol_Z[i]);
2202
  /* Force remote_write_bytes to check whether target supports binary
2203
     downloading. */
2204
  update_packet_config (&remote_protocol_binary_download);
2205
}
2206
 
2207
/* Symbol look-up. */
2208
 
2209
static void
2210
remote_check_symbols (struct objfile *objfile)
2211
{
2212
  struct remote_state *rs = get_remote_state ();
2213
  char *msg, *reply, *tmp;
2214
  struct minimal_symbol *sym;
2215
  int end;
2216
 
2217
  if (remote_protocol_qSymbol.support == PACKET_DISABLE)
2218
    return;
2219
 
2220
  msg   = alloca (rs->remote_packet_size);
2221
  reply = alloca (rs->remote_packet_size);
2222
 
2223
  /* Invite target to request symbol lookups. */
2224
 
2225
  putpkt ("qSymbol::");
2226
  getpkt (reply, (rs->remote_packet_size), 0);
2227
  packet_ok (reply, &remote_protocol_qSymbol);
2228
 
2229
  while (strncmp (reply, "qSymbol:", 8) == 0)
2230
    {
2231
      tmp = &reply[8];
2232
      end = hex2bin (tmp, msg, strlen (tmp) / 2);
2233
      msg[end] = '\0';
2234
      sym = lookup_minimal_symbol (msg, NULL, NULL);
2235
      if (sym == NULL)
2236
        sprintf (msg, "qSymbol::%s", &reply[8]);
2237
      else
2238
        sprintf (msg, "qSymbol:%s:%s",
2239
                 paddr_nz (SYMBOL_VALUE_ADDRESS (sym)),
2240
                 &reply[8]);
2241
      putpkt (msg);
2242
      getpkt (reply, (rs->remote_packet_size), 0);
2243
    }
2244
}
2245
 
2246
static struct serial *
2247
remote_serial_open (char *name)
2248
{
2249
  static int udp_warning = 0;
2250
 
2251
  /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
2252
     of in ser-tcp.c, because it is the remote protocol assuming that the
2253
     serial connection is reliable and not the serial connection promising
2254
     to be.  */
2255
  if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2256
    {
2257
      warning ("The remote protocol may be unreliable over UDP.");
2258
      warning ("Some events may be lost, rendering further debugging "
2259
               "impossible.");
2260
      udp_warning = 1;
2261
    }
2262
 
2263
  return serial_open (name);
2264
}
2265
 
2266
static void
2267
remote_open_1 (char *name, int from_tty, struct target_ops *target,
2268
               int extended_p, int async_p)
2269
{
2270
  int ex;
2271
  struct remote_state *rs = get_remote_state ();
2272
  if (name == 0)
2273
    error ("To open a remote debug connection, you need to specify what\n"
2274
           "serial device is attached to the remote system\n"
2275
           "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
2276
 
2277
  /* See FIXME above */
2278
  if (!async_p)
2279
    wait_forever_enabled_p = 1;
2280
 
2281
  target_preopen (from_tty);
2282
 
2283
  unpush_target (target);
2284
 
2285
  remote_desc = remote_serial_open (name);
2286
  if (!remote_desc)
2287
    perror_with_name (name);
2288
 
2289
  if (baud_rate != -1)
2290
    {
2291
      if (serial_setbaudrate (remote_desc, baud_rate))
2292
        {
2293
          serial_close (remote_desc);
2294
          perror_with_name (name);
2295
        }
2296
    }
2297
 
2298
  serial_raw (remote_desc);
2299
 
2300
  /* If there is something sitting in the buffer we might take it as a
2301
     response to a command, which would be bad.  */
2302
  serial_flush_input (remote_desc);
2303
 
2304
  if (from_tty)
2305
    {
2306
      puts_filtered ("Remote debugging using ");
2307
      puts_filtered (name);
2308
      puts_filtered ("\n");
2309
    }
2310
  push_target (target);         /* Switch to using remote target now */
2311
 
2312
  init_all_packet_configs ();
2313
 
2314
  general_thread = -2;
2315
  continue_thread = -2;
2316
 
2317
  /* Probe for ability to use "ThreadInfo" query, as required.  */
2318
  use_threadinfo_query = 1;
2319
  use_threadextra_query = 1;
2320
 
2321
  /* Without this, some commands which require an active target (such
2322
     as kill) won't work.  This variable serves (at least) double duty
2323
     as both the pid of the target process (if it has such), and as a
2324
     flag indicating that a target is active.  These functions should
2325
     be split out into seperate variables, especially since GDB will
2326
     someday have a notion of debugging several processes.  */
2327
 
2328
  inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
2329
 
2330
  if (async_p)
2331
    {
2332
      /* With this target we start out by owning the terminal. */
2333
      remote_async_terminal_ours_p = 1;
2334
 
2335
      /* FIXME: cagney/1999-09-23: During the initial connection it is
2336
         assumed that the target is already ready and able to respond to
2337
         requests. Unfortunately remote_start_remote() eventually calls
2338
         wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
2339
         around this. Eventually a mechanism that allows
2340
         wait_for_inferior() to expect/get timeouts will be
2341
         implemented. */
2342
      wait_forever_enabled_p = 0;
2343
    }
2344
 
2345
#ifdef SOLIB_CREATE_INFERIOR_HOOK
2346
  /* First delete any symbols previously loaded from shared libraries. */
2347
  no_shared_libraries (NULL, 0);
2348
#endif
2349
 
2350
  /* Start the remote connection.  If error() or QUIT, discard this
2351
     target (we'd otherwise be in an inconsistent state) and then
2352
     propogate the error on up the exception chain.  This ensures that
2353
     the caller doesn't stumble along blindly assuming that the
2354
     function succeeded.  The CLI doesn't have this problem but other
2355
     UI's, such as MI do.
2356
 
2357
     FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
2358
     this function should return an error indication letting the
2359
     caller restore the previous state.  Unfortunatly the command
2360
     ``target remote'' is directly wired to this function making that
2361
     impossible.  On a positive note, the CLI side of this problem has
2362
     been fixed - the function set_cmd_context() makes it possible for
2363
     all the ``target ....'' commands to share a common callback
2364
     function.  See cli-dump.c.  */
2365
  ex = catch_exceptions (uiout,
2366
                         remote_start_remote, NULL,
2367
                         "Couldn't establish connection to remote"
2368
                         " target\n",
2369
                         RETURN_MASK_ALL);
2370
  if (ex < 0)
2371
    {
2372
      pop_target ();
2373
      if (async_p)
2374
        wait_forever_enabled_p = 1;
2375
      throw_exception (ex);
2376
    }
2377
 
2378
  if (async_p)
2379
    wait_forever_enabled_p = 1;
2380
 
2381
  if (extended_p)
2382
    {
2383
      /* Tell the remote that we are using the extended protocol.  */
2384
      char *buf = alloca (rs->remote_packet_size);
2385
      putpkt ("!");
2386
      getpkt (buf, (rs->remote_packet_size), 0);
2387
    }
2388
#ifdef SOLIB_CREATE_INFERIOR_HOOK
2389
  /* FIXME: need a master target_open vector from which all
2390
     remote_opens can be called, so that stuff like this can
2391
     go there.  Failing that, the following code must be copied
2392
     to the open function for any remote target that wants to
2393
     support svr4 shared libraries.  */
2394
 
2395
  /* Set up to detect and load shared libraries. */
2396
  if (exec_bfd)         /* No use without an exec file. */
2397
    {
2398
      SOLIB_CREATE_INFERIOR_HOOK (PIDGET (inferior_ptid));
2399
      remote_check_symbols (symfile_objfile);
2400
    }
2401
#endif
2402
}
2403
 
2404
/* This takes a program previously attached to and detaches it.  After
2405
   this is done, GDB can be used to debug some other program.  We
2406
   better not have left any breakpoints in the target program or it'll
2407
   die when it hits one.  */
2408
 
2409
static void
2410
remote_detach (char *args, int from_tty)
2411
{
2412
  struct remote_state *rs = get_remote_state ();
2413
  char *buf = alloca (rs->remote_packet_size);
2414
 
2415
  if (args)
2416
    error ("Argument given to \"detach\" when remotely debugging.");
2417
 
2418
  /* Tell the remote target to detach.  */
2419
  strcpy (buf, "D");
2420
  remote_send (buf, (rs->remote_packet_size));
2421
 
2422
  target_mourn_inferior ();
2423
  if (from_tty)
2424
    puts_filtered ("Ending remote debugging.\n");
2425
 
2426
}
2427
 
2428
/* Same as remote_detach, but with async support. */
2429
static void
2430
remote_async_detach (char *args, int from_tty)
2431
{
2432
  struct remote_state *rs = get_remote_state ();
2433
  char *buf = alloca (rs->remote_packet_size);
2434
 
2435
  if (args)
2436
    error ("Argument given to \"detach\" when remotely debugging.");
2437
 
2438
  /* Tell the remote target to detach.  */
2439
  strcpy (buf, "D");
2440
  remote_send (buf, (rs->remote_packet_size));
2441
 
2442
  /* Unregister the file descriptor from the event loop. */
2443
  if (target_is_async_p ())
2444
    serial_async (remote_desc, NULL, 0);
2445
 
2446
  target_mourn_inferior ();
2447
  if (from_tty)
2448
    puts_filtered ("Ending remote debugging.\n");
2449
}
2450
 
2451
/* Convert hex digit A to a number.  */
2452
 
2453
static int
2454
fromhex (int a)
2455
{
2456
  if (a >= '0' && a <= '9')
2457
    return a - '0';
2458
  else if (a >= 'a' && a <= 'f')
2459
    return a - 'a' + 10;
2460
  else if (a >= 'A' && a <= 'F')
2461
    return a - 'A' + 10;
2462
  else
2463
    error ("Reply contains invalid hex digit %d", a);
2464
}
2465
 
2466
static int
2467
hex2bin (const char *hex, char *bin, int count)
2468
{
2469
  int i;
2470
 
2471
  for (i = 0; i < count; i++)
2472
    {
2473
      if (hex[0] == 0 || hex[1] == 0)
2474
        {
2475
          /* Hex string is short, or of uneven length.
2476
             Return the count that has been converted so far. */
2477
          return i;
2478
        }
2479
      *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
2480
      hex += 2;
2481
    }
2482
  return i;
2483
}
2484
 
2485
/* Convert number NIB to a hex digit.  */
2486
 
2487
static int
2488
tohex (int nib)
2489
{
2490
  if (nib < 10)
2491
    return '0' + nib;
2492
  else
2493
    return 'a' + nib - 10;
2494
}
2495
 
2496
static int
2497
bin2hex (const char *bin, char *hex, int count)
2498
{
2499
  int i;
2500
  /* May use a length, or a nul-terminated string as input. */
2501
  if (count == 0)
2502
    count = strlen (bin);
2503
 
2504
  for (i = 0; i < count; i++)
2505
    {
2506
      *hex++ = tohex ((*bin >> 4) & 0xf);
2507
      *hex++ = tohex (*bin++ & 0xf);
2508
    }
2509
  *hex = 0;
2510
  return i;
2511
}
2512
 
2513
/* Tell the remote machine to resume.  */
2514
 
2515
static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
2516
 
2517
static int last_sent_step;
2518
 
2519
static void
2520
remote_resume (ptid_t ptid, int step, enum target_signal siggnal)
2521
{
2522
  struct remote_state *rs = get_remote_state ();
2523
  char *buf = alloca (rs->remote_packet_size);
2524
  int pid = PIDGET (ptid);
2525
  char *p;
2526
 
2527
  if (pid == -1)
2528
    set_thread (0, 0);            /* run any thread */
2529
  else
2530
    set_thread (pid, 0); /* run this thread */
2531
 
2532
  last_sent_signal = siggnal;
2533
  last_sent_step = step;
2534
 
2535
  /* A hook for when we need to do something at the last moment before
2536
     resumption.  */
2537
  if (target_resume_hook)
2538
    (*target_resume_hook) ();
2539
 
2540
 
2541
  /* The s/S/c/C packets do not return status.  So if the target does
2542
     not support the S or C packets, the debug agent returns an empty
2543
     string which is detected in remote_wait().  This protocol defect
2544
     is fixed in the e/E packets. */
2545
 
2546
  if (step && step_range_end)
2547
    {
2548
      /* If the target does not support the 'E' packet, we try the 'S'
2549
         packet.  Ideally we would fall back to the 'e' packet if that
2550
         too is not supported.  But that would require another copy of
2551
         the code to issue the 'e' packet (and fall back to 's' if not
2552
         supported) in remote_wait().  */
2553
 
2554
      if (siggnal != TARGET_SIGNAL_0)
2555
        {
2556
          if (remote_protocol_E.support != PACKET_DISABLE)
2557
            {
2558
              p = buf;
2559
              *p++ = 'E';
2560
              *p++ = tohex (((int) siggnal >> 4) & 0xf);
2561
              *p++ = tohex (((int) siggnal) & 0xf);
2562
              *p++ = ',';
2563
              p += hexnumstr (p, (ULONGEST) step_range_start);
2564
              *p++ = ',';
2565
              p += hexnumstr (p, (ULONGEST) step_range_end);
2566
              *p++ = 0;
2567
 
2568
              putpkt (buf);
2569
              getpkt (buf, (rs->remote_packet_size), 0);
2570
 
2571
              if (packet_ok (buf, &remote_protocol_E) == PACKET_OK)
2572
                return;
2573
            }
2574
        }
2575
      else
2576
        {
2577
          if (remote_protocol_e.support != PACKET_DISABLE)
2578
            {
2579
              p = buf;
2580
              *p++ = 'e';
2581
              p += hexnumstr (p, (ULONGEST) step_range_start);
2582
              *p++ = ',';
2583
              p += hexnumstr (p, (ULONGEST) step_range_end);
2584
              *p++ = 0;
2585
 
2586
              putpkt (buf);
2587
              getpkt (buf, (rs->remote_packet_size), 0);
2588
 
2589
              if (packet_ok (buf, &remote_protocol_e) == PACKET_OK)
2590
                return;
2591
            }
2592
        }
2593
    }
2594
 
2595
  if (siggnal != TARGET_SIGNAL_0)
2596
    {
2597
      buf[0] = step ? 'S' : 'C';
2598
      buf[1] = tohex (((int) siggnal >> 4) & 0xf);
2599
      buf[2] = tohex (((int) siggnal) & 0xf);
2600
      buf[3] = '\0';
2601
    }
2602
  else
2603
    strcpy (buf, step ? "s" : "c");
2604
 
2605
  putpkt (buf);
2606
}
2607
 
2608
/* Same as remote_resume, but with async support. */
2609
static void
2610
remote_async_resume (ptid_t ptid, int step, enum target_signal siggnal)
2611
{
2612
  struct remote_state *rs = get_remote_state ();
2613
  char *buf = alloca (rs->remote_packet_size);
2614
  int pid = PIDGET (ptid);
2615
  char *p;
2616
 
2617
  if (pid == -1)
2618
    set_thread (0, 0);            /* run any thread */
2619
  else
2620
    set_thread (pid, 0); /* run this thread */
2621
 
2622
  last_sent_signal = siggnal;
2623
  last_sent_step = step;
2624
 
2625
  /* A hook for when we need to do something at the last moment before
2626
     resumption.  */
2627
  if (target_resume_hook)
2628
    (*target_resume_hook) ();
2629
 
2630
  /* The s/S/c/C packets do not return status.  So if the target does
2631
     not support the S or C packets, the debug agent returns an empty
2632
     string which is detected in remote_wait().  This protocol defect
2633
     is fixed in the e/E packets. */
2634
 
2635
  if (step && step_range_end)
2636
    {
2637
      /* If the target does not support the 'E' packet, we try the 'S'
2638
         packet.  Ideally we would fall back to the 'e' packet if that
2639
         too is not supported.  But that would require another copy of
2640
         the code to issue the 'e' packet (and fall back to 's' if not
2641
         supported) in remote_wait().  */
2642
 
2643
      if (siggnal != TARGET_SIGNAL_0)
2644
        {
2645
          if (remote_protocol_E.support != PACKET_DISABLE)
2646
            {
2647
              p = buf;
2648
              *p++ = 'E';
2649
              *p++ = tohex (((int) siggnal >> 4) & 0xf);
2650
              *p++ = tohex (((int) siggnal) & 0xf);
2651
              *p++ = ',';
2652
              p += hexnumstr (p, (ULONGEST) step_range_start);
2653
              *p++ = ',';
2654
              p += hexnumstr (p, (ULONGEST) step_range_end);
2655
              *p++ = 0;
2656
 
2657
              putpkt (buf);
2658
              getpkt (buf, (rs->remote_packet_size), 0);
2659
 
2660
              if (packet_ok (buf, &remote_protocol_E) == PACKET_OK)
2661
                goto register_event_loop;
2662
            }
2663
        }
2664
      else
2665
        {
2666
          if (remote_protocol_e.support != PACKET_DISABLE)
2667
            {
2668
              p = buf;
2669
              *p++ = 'e';
2670
              p += hexnumstr (p, (ULONGEST) step_range_start);
2671
              *p++ = ',';
2672
              p += hexnumstr (p, (ULONGEST) step_range_end);
2673
              *p++ = 0;
2674
 
2675
              putpkt (buf);
2676
              getpkt (buf, (rs->remote_packet_size), 0);
2677
 
2678
              if (packet_ok (buf, &remote_protocol_e) == PACKET_OK)
2679
                goto register_event_loop;
2680
            }
2681
        }
2682
    }
2683
 
2684
  if (siggnal != TARGET_SIGNAL_0)
2685
    {
2686
      buf[0] = step ? 'S' : 'C';
2687
      buf[1] = tohex (((int) siggnal >> 4) & 0xf);
2688
      buf[2] = tohex ((int) siggnal & 0xf);
2689
      buf[3] = '\0';
2690
    }
2691
  else
2692
    strcpy (buf, step ? "s" : "c");
2693
 
2694
  putpkt (buf);
2695
 
2696
register_event_loop:
2697
  /* We are about to start executing the inferior, let's register it
2698
     with the event loop. NOTE: this is the one place where all the
2699
     execution commands end up. We could alternatively do this in each
2700
     of the execution commands in infcmd.c.*/
2701
  /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
2702
     into infcmd.c in order to allow inferior function calls to work
2703
     NOT asynchronously. */
2704
  if (event_loop_p && target_can_async_p ())
2705
    target_async (inferior_event_handler, 0);
2706
  /* Tell the world that the target is now executing. */
2707
  /* FIXME: cagney/1999-09-23: Is it the targets responsibility to set
2708
     this?  Instead, should the client of target just assume (for
2709
     async targets) that the target is going to start executing?  Is
2710
     this information already found in the continuation block?  */
2711
  if (target_is_async_p ())
2712
    target_executing = 1;
2713
}
2714
 
2715
 
2716
/* Set up the signal handler for SIGINT, while the target is
2717
   executing, ovewriting the 'regular' SIGINT signal handler. */
2718
static void
2719
initialize_sigint_signal_handler (void)
2720
{
2721
  sigint_remote_token =
2722
    create_async_signal_handler (async_remote_interrupt, NULL);
2723
  signal (SIGINT, handle_remote_sigint);
2724
}
2725
 
2726
/* Signal handler for SIGINT, while the target is executing. */
2727
static void
2728
handle_remote_sigint (int sig)
2729
{
2730
  signal (sig, handle_remote_sigint_twice);
2731
  sigint_remote_twice_token =
2732
    create_async_signal_handler (async_remote_interrupt_twice, NULL);
2733
  mark_async_signal_handler_wrapper (sigint_remote_token);
2734
}
2735
 
2736
/* Signal handler for SIGINT, installed after SIGINT has already been
2737
   sent once.  It will take effect the second time that the user sends
2738
   a ^C. */
2739
static void
2740
handle_remote_sigint_twice (int sig)
2741
{
2742
  signal (sig, handle_sigint);
2743
  sigint_remote_twice_token =
2744
    create_async_signal_handler (inferior_event_handler_wrapper, NULL);
2745
  mark_async_signal_handler_wrapper (sigint_remote_twice_token);
2746
}
2747
 
2748
/* Perform the real interruption of the target execution, in response
2749
   to a ^C. */
2750
static void
2751
async_remote_interrupt (gdb_client_data arg)
2752
{
2753
  if (remote_debug)
2754
    fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2755
 
2756
  target_stop ();
2757
}
2758
 
2759
/* Perform interrupt, if the first attempt did not succeed. Just give
2760
   up on the target alltogether. */
2761
void
2762
async_remote_interrupt_twice (gdb_client_data arg)
2763
{
2764
  if (remote_debug)
2765
    fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
2766
  /* Do something only if the target was not killed by the previous
2767
     cntl-C. */
2768
  if (target_executing)
2769
    {
2770
      interrupt_query ();
2771
      signal (SIGINT, handle_remote_sigint);
2772
    }
2773
}
2774
 
2775
/* Reinstall the usual SIGINT handlers, after the target has
2776
   stopped. */
2777
static void
2778
cleanup_sigint_signal_handler (void *dummy)
2779
{
2780
  signal (SIGINT, handle_sigint);
2781
  if (sigint_remote_twice_token)
2782
    delete_async_signal_handler ((struct async_signal_handler **) & sigint_remote_twice_token);
2783
  if (sigint_remote_token)
2784
    delete_async_signal_handler ((struct async_signal_handler **) & sigint_remote_token);
2785
}
2786
 
2787
/* Send ^C to target to halt it.  Target will respond, and send us a
2788
   packet.  */
2789
static void (*ofunc) (int);
2790
 
2791
/* The command line interface's stop routine. This function is installed
2792
   as a signal handler for SIGINT. The first time a user requests a
2793
   stop, we call remote_stop to send a break or ^C. If there is no
2794
   response from the target (it didn't stop when the user requested it),
2795
   we ask the user if he'd like to detach from the target. */
2796
static void
2797
remote_interrupt (int signo)
2798
{
2799
  /* If this doesn't work, try more severe steps. */
2800
  signal (signo, remote_interrupt_twice);
2801
 
2802
  if (remote_debug)
2803
    fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
2804
 
2805
  target_stop ();
2806
}
2807
 
2808
/* The user typed ^C twice.  */
2809
 
2810
static void
2811
remote_interrupt_twice (int signo)
2812
{
2813
  signal (signo, ofunc);
2814
  interrupt_query ();
2815
  signal (signo, remote_interrupt);
2816
}
2817
 
2818
/* This is the generic stop called via the target vector. When a target
2819
   interrupt is requested, either by the command line or the GUI, we
2820
   will eventually end up here. */
2821
static void
2822
remote_stop (void)
2823
{
2824
  /* Send a break or a ^C, depending on user preference.  */
2825
  if (remote_debug)
2826
    fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
2827
 
2828
  if (remote_break)
2829
    serial_send_break (remote_desc);
2830
  else
2831
    serial_write (remote_desc, "\003", 1);
2832
}
2833
 
2834
/* Ask the user what to do when an interrupt is received.  */
2835
 
2836
static void
2837
interrupt_query (void)
2838
{
2839
  target_terminal_ours ();
2840
 
2841
  if (query ("Interrupted while waiting for the program.\n\
2842
Give up (and stop debugging it)? "))
2843
    {
2844
      target_mourn_inferior ();
2845
      throw_exception (RETURN_QUIT);
2846
    }
2847
 
2848
  target_terminal_inferior ();
2849
}
2850
 
2851
/* Enable/disable target terminal ownership.  Most targets can use
2852
   terminal groups to control terminal ownership.  Remote targets are
2853
   different in that explicit transfer of ownership to/from GDB/target
2854
   is required. */
2855
 
2856
static void
2857
remote_async_terminal_inferior (void)
2858
{
2859
  /* FIXME: cagney/1999-09-27: Shouldn't need to test for
2860
     sync_execution here.  This function should only be called when
2861
     GDB is resuming the inferior in the forground.  A background
2862
     resume (``run&'') should leave GDB in control of the terminal and
2863
     consequently should not call this code. */
2864
  if (!sync_execution)
2865
    return;
2866
  /* FIXME: cagney/1999-09-27: Closely related to the above.  Make
2867
     calls target_terminal_*() idenpotent. The event-loop GDB talking
2868
     to an asynchronous target with a synchronous command calls this
2869
     function from both event-top.c and infrun.c/infcmd.c.  Once GDB
2870
     stops trying to transfer the terminal to the target when it
2871
     shouldn't this guard can go away.  */
2872
  if (!remote_async_terminal_ours_p)
2873
    return;
2874
  delete_file_handler (input_fd);
2875
  remote_async_terminal_ours_p = 0;
2876
  initialize_sigint_signal_handler ();
2877
  /* NOTE: At this point we could also register our selves as the
2878
     recipient of all input.  Any characters typed could then be
2879
     passed on down to the target. */
2880
}
2881
 
2882
static void
2883
remote_async_terminal_ours (void)
2884
{
2885
  /* See FIXME in remote_async_terminal_inferior. */
2886
  if (!sync_execution)
2887
    return;
2888
  /* See FIXME in remote_async_terminal_inferior. */
2889
  if (remote_async_terminal_ours_p)
2890
    return;
2891
  cleanup_sigint_signal_handler (NULL);
2892
  add_file_handler (input_fd, stdin_event_handler, 0);
2893
  remote_async_terminal_ours_p = 1;
2894
}
2895
 
2896
/* If nonzero, ignore the next kill.  */
2897
 
2898
int kill_kludge;
2899
 
2900
void
2901
remote_console_output (char *msg)
2902
{
2903
  char *p;
2904
 
2905
  for (p = msg; p[0] && p[1]; p += 2)
2906
    {
2907
      char tb[2];
2908
      char c = fromhex (p[0]) * 16 + fromhex (p[1]);
2909
      tb[0] = c;
2910
      tb[1] = 0;
2911
      fputs_unfiltered (tb, gdb_stdtarg);
2912
    }
2913
  gdb_flush (gdb_stdtarg);
2914
}
2915
 
2916
/* Wait until the remote machine stops, then return,
2917
   storing status in STATUS just as `wait' would.
2918
   Returns "pid", which in the case of a multi-threaded
2919
   remote OS, is the thread-id.  */
2920
 
2921
static ptid_t
2922
remote_wait (ptid_t ptid, struct target_waitstatus *status)
2923
{
2924
  struct remote_state *rs = get_remote_state ();
2925
  unsigned char *buf = alloca (rs->remote_packet_size);
2926
  ULONGEST thread_num = -1;
2927
  ULONGEST addr;
2928
 
2929
  status->kind = TARGET_WAITKIND_EXITED;
2930
  status->value.integer = 0;
2931
 
2932
  while (1)
2933
    {
2934
      unsigned char *p;
2935
 
2936
      ofunc = signal (SIGINT, remote_interrupt);
2937
      getpkt (buf, (rs->remote_packet_size), 1);
2938
      signal (SIGINT, ofunc);
2939
 
2940
      /* This is a hook for when we need to do something (perhaps the
2941
         collection of trace data) every time the target stops.  */
2942
      if (target_wait_loop_hook)
2943
        (*target_wait_loop_hook) ();
2944
 
2945
      remote_stopped_by_watchpoint_p = 0;
2946
 
2947
      switch (buf[0])
2948
        {
2949
        case 'E':               /* Error of some sort */
2950
          warning ("Remote failure reply: %s", buf);
2951
          continue;
2952
        case 'T':               /* Status with PC, SP, FP, ... */
2953
          {
2954
            int i;
2955
            char* regs = (char*) alloca (MAX_REGISTER_RAW_SIZE);
2956
 
2957
            /* Expedited reply, containing Signal, {regno, reg} repeat */
2958
            /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
2959
               ss = signal number
2960
               n... = register number
2961
               r... = register contents
2962
             */
2963
            p = &buf[3];        /* after Txx */
2964
 
2965
            while (*p)
2966
              {
2967
                unsigned char *p1;
2968
                char *p_temp;
2969
                int fieldsize;
2970
                LONGEST pnum = 0;
2971
 
2972
                /* If the packet contains a register number save it in pnum
2973
                   and set p1 to point to the character following it.
2974
                   Otherwise p1 points to p.  */
2975
 
2976
                /* If this packet is an awatch packet, don't parse the 'a'
2977
                   as a register number.  */
2978
 
2979
                if (strncmp (p, "awatch", strlen("awatch")) != 0)
2980
                  {
2981
                    /* Read the ``P'' register number.  */
2982
                    pnum = strtol (p, &p_temp, 16);
2983
                    p1 = (unsigned char *) p_temp;
2984
                  }
2985
                else
2986
                  p1 = p;
2987
 
2988
                if (p1 == p)    /* No register number present here */
2989
                  {
2990
                    p1 = (unsigned char *) strchr (p, ':');
2991
                    if (p1 == NULL)
2992
                      warning ("Malformed packet(a) (missing colon): %s\n\
2993
Packet: '%s'\n",
2994
                               p, buf);
2995
                    if (strncmp (p, "thread", p1 - p) == 0)
2996
                      {
2997
                        p_temp = unpack_varlen_hex (++p1, &thread_num);
2998
                        record_currthread (thread_num);
2999
                        p = (unsigned char *) p_temp;
3000
                      }
3001
                    else if ((strncmp (p, "watch", p1 - p) == 0)
3002
                             || (strncmp (p, "rwatch", p1 - p) == 0)
3003
                             || (strncmp (p, "awatch", p1 - p) == 0))
3004
                      {
3005
                        remote_stopped_by_watchpoint_p = 1;
3006
                        p = unpack_varlen_hex (++p1, &addr);
3007
                        remote_watch_data_address = (CORE_ADDR)addr;
3008
                      }
3009
                    else
3010
                      {
3011
                        /* Silently skip unknown optional info.  */
3012
                        p_temp = strchr (p1 + 1, ';');
3013
                        if (p_temp)
3014
                          p = (unsigned char *) p_temp;
3015
                      }
3016
                  }
3017
                else
3018
                  {
3019
                    struct packet_reg *reg = packet_reg_from_pnum (rs, pnum);
3020
                    p = p1;
3021
 
3022
                    if (*p++ != ':')
3023
                      warning ("Malformed packet(b) (missing colon): %s\n\
3024
Packet: '%s'\n",
3025
                               p, buf);
3026
 
3027
                    if (reg == NULL)
3028
                      warning ("Remote sent bad register number %s: %s\n\
3029
Packet: '%s'\n",
3030
                               phex_nz (pnum, 0), p, buf);
3031
 
3032
                    fieldsize = hex2bin (p, regs, REGISTER_RAW_SIZE (reg->regnum));
3033
                    p += 2 * fieldsize;
3034
                    if (fieldsize < REGISTER_RAW_SIZE (reg->regnum))
3035
                      warning ("Remote reply is too short: %s", buf);
3036
                    supply_register (reg->regnum, regs);
3037
                  }
3038
 
3039
                if (*p++ != ';')
3040
                  {
3041
                    warning ("Remote register badly formatted: %s", buf);
3042
                    warning ("            here: %s", p);
3043
                  }
3044
              }
3045
          }
3046
          /* fall through */
3047
        case 'S':               /* Old style status, just signal only */
3048
          status->kind = TARGET_WAITKIND_STOPPED;
3049
          status->value.sig = (enum target_signal)
3050
            (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3051
 
3052
          if (buf[3] == 'p')
3053
            {
3054
              /* Export Cisco kernel mode as a convenience variable
3055
                 (so that it can be used in the GDB prompt if desired). */
3056
 
3057
              if (cisco_kernel_mode == 1)
3058
                set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
3059
                                 value_from_string ("PDEBUG-"));
3060
              cisco_kernel_mode = 0;
3061
              thread_num = strtol ((const char *) &buf[4], NULL, 16);
3062
              record_currthread (thread_num);
3063
            }
3064
          else if (buf[3] == 'k')
3065
            {
3066
              /* Export Cisco kernel mode as a convenience variable
3067
                 (so that it can be used in the GDB prompt if desired). */
3068
 
3069
              if (cisco_kernel_mode == 1)
3070
                set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
3071
                                 value_from_string ("KDEBUG-"));
3072
              cisco_kernel_mode = 1;
3073
            }
3074
          goto got_status;
3075
        case 'N':               /* Cisco special: status and offsets */
3076
          {
3077
            bfd_vma text_addr, data_addr, bss_addr;
3078
            bfd_signed_vma text_off, data_off, bss_off;
3079
            unsigned char *p1;
3080
 
3081
            status->kind = TARGET_WAITKIND_STOPPED;
3082
            status->value.sig = (enum target_signal)
3083
              (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3084
 
3085
            if (symfile_objfile == NULL)
3086
              {
3087
                warning ("Relocation packet received with no symbol file.  \
3088
Packet Dropped");
3089
                goto got_status;
3090
              }
3091
 
3092
            /* Relocate object file.  Buffer format is NAATT;DD;BB
3093
             * where AA is the signal number, TT is the new text
3094
             * address, DD * is the new data address, and BB is the
3095
             * new bss address.  */
3096
 
3097
            p = &buf[3];
3098
            text_addr = strtoul (p, (char **) &p1, 16);
3099
            if (p1 == p || *p1 != ';')
3100
              warning ("Malformed relocation packet: Packet '%s'", buf);
3101
            p = p1 + 1;
3102
            data_addr = strtoul (p, (char **) &p1, 16);
3103
            if (p1 == p || *p1 != ';')
3104
              warning ("Malformed relocation packet: Packet '%s'", buf);
3105
            p = p1 + 1;
3106
            bss_addr = strtoul (p, (char **) &p1, 16);
3107
            if (p1 == p)
3108
              warning ("Malformed relocation packet: Packet '%s'", buf);
3109
 
3110
            if (remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
3111
                                              &text_off, &data_off, &bss_off)
3112
                == 0)
3113
              if (text_off != 0 || data_off != 0 || bss_off != 0)
3114
                remote_cisco_objfile_relocate (text_off, data_off, bss_off);
3115
 
3116
            goto got_status;
3117
          }
3118
        case 'W':               /* Target exited */
3119
          {
3120
            /* The remote process exited.  */
3121
            status->kind = TARGET_WAITKIND_EXITED;
3122
            status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3123
            goto got_status;
3124
          }
3125
        case 'X':
3126
          status->kind = TARGET_WAITKIND_SIGNALLED;
3127
          status->value.sig = (enum target_signal)
3128
            (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3129
          kill_kludge = 1;
3130
 
3131
          goto got_status;
3132
        case 'O':               /* Console output */
3133
          remote_console_output (buf + 1);
3134
          continue;
3135
        case '\0':
3136
          if (last_sent_signal != TARGET_SIGNAL_0)
3137
            {
3138
              /* Zero length reply means that we tried 'S' or 'C' and
3139
                 the remote system doesn't support it.  */
3140
              target_terminal_ours_for_output ();
3141
              printf_filtered
3142
                ("Can't send signals to this remote system.  %s not sent.\n",
3143
                 target_signal_to_name (last_sent_signal));
3144
              last_sent_signal = TARGET_SIGNAL_0;
3145
              target_terminal_inferior ();
3146
 
3147
              strcpy ((char *) buf, last_sent_step ? "s" : "c");
3148
              putpkt ((char *) buf);
3149
              continue;
3150
            }
3151
          /* else fallthrough */
3152
        default:
3153
          warning ("Invalid remote reply: %s", buf);
3154
          continue;
3155
        }
3156
    }
3157
got_status:
3158
  if (thread_num != -1)
3159
    {
3160
      return pid_to_ptid (thread_num);
3161
    }
3162
  return inferior_ptid;
3163
}
3164
 
3165
/* Async version of remote_wait. */
3166
static ptid_t
3167
remote_async_wait (ptid_t ptid, struct target_waitstatus *status)
3168
{
3169
  struct remote_state *rs = get_remote_state ();
3170
  unsigned char *buf = alloca (rs->remote_packet_size);
3171
  ULONGEST thread_num = -1;
3172
  ULONGEST addr;
3173
 
3174
  status->kind = TARGET_WAITKIND_EXITED;
3175
  status->value.integer = 0;
3176
 
3177
  remote_stopped_by_watchpoint_p = 0;
3178
 
3179
  while (1)
3180
    {
3181
      unsigned char *p;
3182
 
3183
      if (!target_is_async_p ())
3184
        ofunc = signal (SIGINT, remote_interrupt);
3185
      /* FIXME: cagney/1999-09-27: If we're in async mode we should
3186
         _never_ wait for ever -> test on target_is_async_p().
3187
         However, before we do that we need to ensure that the caller
3188
         knows how to take the target into/out of async mode. */
3189
      getpkt (buf, (rs->remote_packet_size), wait_forever_enabled_p);
3190
      if (!target_is_async_p ())
3191
        signal (SIGINT, ofunc);
3192
 
3193
      /* This is a hook for when we need to do something (perhaps the
3194
         collection of trace data) every time the target stops.  */
3195
      if (target_wait_loop_hook)
3196
        (*target_wait_loop_hook) ();
3197
 
3198
      switch (buf[0])
3199
        {
3200
        case 'E':               /* Error of some sort */
3201
          warning ("Remote failure reply: %s", buf);
3202
          continue;
3203
        case 'T':               /* Status with PC, SP, FP, ... */
3204
          {
3205
            int i;
3206
            char* regs = (char*) alloca (MAX_REGISTER_RAW_SIZE);
3207
 
3208
            /* Expedited reply, containing Signal, {regno, reg} repeat */
3209
            /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
3210
               ss = signal number
3211
               n... = register number
3212
               r... = register contents
3213
             */
3214
            p = &buf[3];        /* after Txx */
3215
 
3216
            while (*p)
3217
              {
3218
                unsigned char *p1;
3219
                char *p_temp;
3220
                int fieldsize;
3221
                long pnum = 0;
3222
 
3223
                /* If the packet contains a register number, save it in pnum
3224
                   and set p1 to point to the character following it.
3225
                   Otherwise p1 points to p.  */
3226
 
3227
                /* If this packet is an awatch packet, don't parse the 'a'
3228
                   as a register number.  */
3229
 
3230
                if (!strncmp (p, "awatch", strlen ("awatch")) != 0)
3231
                  {
3232
                    /* Read the register number.  */
3233
                    pnum = strtol (p, &p_temp, 16);
3234
                    p1 = (unsigned char *) p_temp;
3235
                  }
3236
                else
3237
                  p1 = p;
3238
 
3239
                if (p1 == p)    /* No register number present here */
3240
                  {
3241
                    p1 = (unsigned char *) strchr (p, ':');
3242
                    if (p1 == NULL)
3243
                      warning ("Malformed packet(a) (missing colon): %s\n\
3244
Packet: '%s'\n",
3245
                               p, buf);
3246
                    if (strncmp (p, "thread", p1 - p) == 0)
3247
                      {
3248
                        p_temp = unpack_varlen_hex (++p1, &thread_num);
3249
                        record_currthread (thread_num);
3250
                        p = (unsigned char *) p_temp;
3251
                      }
3252
                    else if ((strncmp (p, "watch", p1 - p) == 0)
3253
                             || (strncmp (p, "rwatch", p1 - p) == 0)
3254
                             || (strncmp (p, "awatch", p1 - p) == 0))
3255
                      {
3256
                        remote_stopped_by_watchpoint_p = 1;
3257
                        p = unpack_varlen_hex (++p1, &addr);
3258
                        remote_watch_data_address = (CORE_ADDR)addr;
3259
                      }
3260
                    else
3261
                      {
3262
                        /* Silently skip unknown optional info.  */
3263
                        p_temp = (unsigned char *) strchr (p1 + 1, ';');
3264
                        if (p_temp)
3265
                          p = p_temp;
3266
                      }
3267
                  }
3268
 
3269
                else
3270
                  {
3271
                    struct packet_reg *reg = packet_reg_from_pnum (rs, pnum);
3272
                    p = p1;
3273
                    if (*p++ != ':')
3274
                      warning ("Malformed packet(b) (missing colon): %s\n\
3275
Packet: '%s'\n",
3276
                               p, buf);
3277
 
3278
                    if (reg == NULL)
3279
                      warning ("Remote sent bad register number %ld: %s\n\
3280
Packet: '%s'\n",
3281
                               pnum, p, buf);
3282
 
3283
                    fieldsize = hex2bin (p, regs, REGISTER_RAW_SIZE (reg->regnum));
3284
                    p += 2 * fieldsize;
3285
                    if (fieldsize < REGISTER_RAW_SIZE (reg->regnum))
3286
                      warning ("Remote reply is too short: %s", buf);
3287
                    supply_register (reg->regnum, regs);
3288
                  }
3289
 
3290
                if (*p++ != ';')
3291
                  {
3292
                    warning ("Remote register badly formatted: %s", buf);
3293
                    warning ("            here: %s", p);
3294
                  }
3295
              }
3296
          }
3297
          /* fall through */
3298
        case 'S':               /* Old style status, just signal only */
3299
          status->kind = TARGET_WAITKIND_STOPPED;
3300
          status->value.sig = (enum target_signal)
3301
            (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3302
 
3303
          if (buf[3] == 'p')
3304
            {
3305
              /* Export Cisco kernel mode as a convenience variable
3306
                 (so that it can be used in the GDB prompt if desired). */
3307
 
3308
              if (cisco_kernel_mode == 1)
3309
                set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
3310
                                 value_from_string ("PDEBUG-"));
3311
              cisco_kernel_mode = 0;
3312
              thread_num = strtol ((const char *) &buf[4], NULL, 16);
3313
              record_currthread (thread_num);
3314
            }
3315
          else if (buf[3] == 'k')
3316
            {
3317
              /* Export Cisco kernel mode as a convenience variable
3318
                 (so that it can be used in the GDB prompt if desired). */
3319
 
3320
              if (cisco_kernel_mode == 1)
3321
                set_internalvar (lookup_internalvar ("cisco_kernel_mode"),
3322
                                 value_from_string ("KDEBUG-"));
3323
              cisco_kernel_mode = 1;
3324
            }
3325
          goto got_status;
3326
        case 'N':               /* Cisco special: status and offsets */
3327
          {
3328
            bfd_vma text_addr, data_addr, bss_addr;
3329
            bfd_signed_vma text_off, data_off, bss_off;
3330
            unsigned char *p1;
3331
 
3332
            status->kind = TARGET_WAITKIND_STOPPED;
3333
            status->value.sig = (enum target_signal)
3334
              (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3335
 
3336
            if (symfile_objfile == NULL)
3337
              {
3338
                warning ("Relocation packet recieved with no symbol file.  \
3339
Packet Dropped");
3340
                goto got_status;
3341
              }
3342
 
3343
            /* Relocate object file.  Buffer format is NAATT;DD;BB
3344
             * where AA is the signal number, TT is the new text
3345
             * address, DD * is the new data address, and BB is the
3346
             * new bss address.  */
3347
 
3348
            p = &buf[3];
3349
            text_addr = strtoul (p, (char **) &p1, 16);
3350
            if (p1 == p || *p1 != ';')
3351
              warning ("Malformed relocation packet: Packet '%s'", buf);
3352
            p = p1 + 1;
3353
            data_addr = strtoul (p, (char **) &p1, 16);
3354
            if (p1 == p || *p1 != ';')
3355
              warning ("Malformed relocation packet: Packet '%s'", buf);
3356
            p = p1 + 1;
3357
            bss_addr = strtoul (p, (char **) &p1, 16);
3358
            if (p1 == p)
3359
              warning ("Malformed relocation packet: Packet '%s'", buf);
3360
 
3361
            if (remote_cisco_section_offsets (text_addr, data_addr, bss_addr,
3362
                                              &text_off, &data_off, &bss_off)
3363
                == 0)
3364
              if (text_off != 0 || data_off != 0 || bss_off != 0)
3365
                remote_cisco_objfile_relocate (text_off, data_off, bss_off);
3366
 
3367
            goto got_status;
3368
          }
3369
        case 'W':               /* Target exited */
3370
          {
3371
            /* The remote process exited.  */
3372
            status->kind = TARGET_WAITKIND_EXITED;
3373
            status->value.integer = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
3374
            goto got_status;
3375
          }
3376
        case 'X':
3377
          status->kind = TARGET_WAITKIND_SIGNALLED;
3378
          status->value.sig = (enum target_signal)
3379
            (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
3380
          kill_kludge = 1;
3381
 
3382
          goto got_status;
3383
        case 'O':               /* Console output */
3384
          remote_console_output (buf + 1);
3385
          /* Return immediately to the event loop. The event loop will
3386
             still be waiting on the inferior afterwards. */
3387
          status->kind = TARGET_WAITKIND_IGNORE;
3388
          goto got_status;
3389
        case '\0':
3390
          if (last_sent_signal != TARGET_SIGNAL_0)
3391
            {
3392
              /* Zero length reply means that we tried 'S' or 'C' and
3393
                 the remote system doesn't support it.  */
3394
              target_terminal_ours_for_output ();
3395
              printf_filtered
3396
                ("Can't send signals to this remote system.  %s not sent.\n",
3397
                 target_signal_to_name (last_sent_signal));
3398
              last_sent_signal = TARGET_SIGNAL_0;
3399
              target_terminal_inferior ();
3400
 
3401
              strcpy ((char *) buf, last_sent_step ? "s" : "c");
3402
              putpkt ((char *) buf);
3403
              continue;
3404
            }
3405
          /* else fallthrough */
3406
        default:
3407
          warning ("Invalid remote reply: %s", buf);
3408
          continue;
3409
        }
3410
    }
3411
got_status:
3412
  if (thread_num != -1)
3413
    {
3414
      return pid_to_ptid (thread_num);
3415
    }
3416
  return inferior_ptid;
3417
}
3418
 
3419
/* Number of bytes of registers this stub implements.  */
3420
 
3421
static int register_bytes_found;
3422
 
3423
/* Read the remote registers into the block REGS.  */
3424
/* Currently we just read all the registers, so we don't use regnum.  */
3425
 
3426
/* ARGSUSED */
3427
static void
3428
remote_fetch_registers (int regnum)
3429
{
3430
  struct remote_state *rs = get_remote_state ();
3431
  char *buf = alloca (rs->remote_packet_size);
3432
  int i;
3433
  char *p;
3434
  char *regs = alloca (rs->sizeof_g_packet);
3435
 
3436
  set_thread (PIDGET (inferior_ptid), 1);
3437
 
3438
  if (regnum >= 0)
3439
    {
3440
      struct packet_reg *reg = packet_reg_from_regnum (rs, regnum);
3441
      gdb_assert (reg != NULL);
3442
      if (!reg->in_g_packet)
3443
        internal_error (__FILE__, __LINE__,
3444
                        "Attempt to fetch a non G-packet register when this "
3445
                        "remote.c does not support the p-packet.");
3446
    }
3447
 
3448
  sprintf (buf, "g");
3449
  remote_send (buf, (rs->remote_packet_size));
3450
 
3451
  /* Save the size of the packet sent to us by the target.  Its used
3452
     as a heuristic when determining the max size of packets that the
3453
     target can safely receive. */
3454
  if ((rs->actual_register_packet_size) == 0)
3455
    (rs->actual_register_packet_size) = strlen (buf);
3456
 
3457
  /* Unimplemented registers read as all bits zero.  */
3458
  memset (regs, 0, rs->sizeof_g_packet);
3459
 
3460
  /* We can get out of synch in various cases.  If the first character
3461
     in the buffer is not a hex character, assume that has happened
3462
     and try to fetch another packet to read.  */
3463
  while ((buf[0] < '0' || buf[0] > '9')
3464
         && (buf[0] < 'a' || buf[0] > 'f')
3465
         && buf[0] != 'x')       /* New: unavailable register value */
3466
    {
3467
      if (remote_debug)
3468
        fprintf_unfiltered (gdb_stdlog,
3469
                            "Bad register packet; fetching a new packet\n");
3470
      getpkt (buf, (rs->remote_packet_size), 0);
3471
    }
3472
 
3473
  /* Reply describes registers byte by byte, each byte encoded as two
3474
     hex characters.  Suck them all up, then supply them to the
3475
     register cacheing/storage mechanism.  */
3476
 
3477
  p = buf;
3478
  for (i = 0; i < rs->sizeof_g_packet; i++)
3479
    {
3480
      if (p[0] == 0)
3481
        break;
3482
      if (p[1] == 0)
3483
        {
3484
          warning ("Remote reply is of odd length: %s", buf);
3485
          /* Don't change register_bytes_found in this case, and don't
3486
             print a second warning.  */
3487
          goto supply_them;
3488
        }
3489
      if (p[0] == 'x' && p[1] == 'x')
3490
        regs[i] = 0;             /* 'x' */
3491
      else
3492
        regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
3493
      p += 2;
3494
    }
3495
 
3496
  if (i != register_bytes_found)
3497
    {
3498
      register_bytes_found = i;
3499
      if (REGISTER_BYTES_OK_P ()
3500
          && !REGISTER_BYTES_OK (i))
3501
        warning ("Remote reply is too short: %s", buf);
3502
    }
3503
 
3504
 supply_them:
3505
  {
3506
    int i;
3507
    for (i = 0; i < NUM_REGS + NUM_PSEUDO_REGS; i++)
3508
      {
3509
        struct packet_reg *r = &rs->regs[i];
3510
        if (r->in_g_packet)
3511
          {
3512
            supply_register (r->regnum, regs + r->offset);
3513
            if (buf[r->offset * 2] == 'x')
3514
              set_register_cached (i, -1);
3515
          }
3516
      }
3517
  }
3518
}
3519
 
3520
/* Prepare to store registers.  Since we may send them all (using a
3521
   'G' request), we have to read out the ones we don't want to change
3522
   first.  */
3523
 
3524
static void
3525
remote_prepare_to_store (void)
3526
{
3527
  /* Make sure the entire registers array is valid.  */
3528
  switch (remote_protocol_P.support)
3529
    {
3530
    case PACKET_DISABLE:
3531
    case PACKET_SUPPORT_UNKNOWN:
3532
      /* NOTE: This isn't rs->sizeof_g_packet because here, we are
3533
         forcing the register cache to read its and not the target
3534
         registers.  */
3535
      read_register_bytes (0, (char *) NULL, REGISTER_BYTES); /* OK use.  */
3536
      break;
3537
    case PACKET_ENABLE:
3538
      break;
3539
    }
3540
}
3541
 
3542
/* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
3543
   packet was not recognized. */
3544
 
3545
static int
3546
store_register_using_P (int regnum)
3547
{
3548
  struct remote_state *rs = get_remote_state ();
3549
  struct packet_reg *reg = packet_reg_from_regnum (rs, regnum);
3550
  /* Try storing a single register.  */
3551
  char *buf = alloca (rs->remote_packet_size);
3552
  char *regp = alloca (MAX_REGISTER_RAW_SIZE);
3553
  char *p;
3554
  int i;
3555
 
3556
  sprintf (buf, "P%s=", phex_nz (reg->pnum, 0));
3557
  p = buf + strlen (buf);
3558
  regcache_collect (reg->regnum, regp);
3559
  bin2hex (regp, p, REGISTER_RAW_SIZE (reg->regnum));
3560
  remote_send (buf, rs->remote_packet_size);
3561
 
3562
  return buf[0] != '\0';
3563
}
3564
 
3565
 
3566
/* Store register REGNUM, or all registers if REGNUM == -1, from the contents
3567
   of the register cache buffer.  FIXME: ignores errors.  */
3568
 
3569
static void
3570
remote_store_registers (int regnum)
3571
{
3572
  struct remote_state *rs = get_remote_state ();
3573
  char *buf;
3574
  char *regs;
3575
  int i;
3576
  char *p;
3577
 
3578
  set_thread (PIDGET (inferior_ptid), 1);
3579
 
3580
  if (regnum >= 0)
3581
    {
3582
      switch (remote_protocol_P.support)
3583
        {
3584
        case PACKET_DISABLE:
3585
          break;
3586
        case PACKET_ENABLE:
3587
          if (store_register_using_P (regnum))
3588
            return;
3589
          else
3590
            error ("Protocol error: P packet not recognized by stub");
3591
        case PACKET_SUPPORT_UNKNOWN:
3592
          if (store_register_using_P (regnum))
3593
            {
3594
              /* The stub recognized the 'P' packet.  Remember this.  */
3595
              remote_protocol_P.support = PACKET_ENABLE;
3596
              return;
3597
            }
3598
          else
3599
            {
3600
              /* The stub does not support the 'P' packet.  Use 'G'
3601
                 instead, and don't try using 'P' in the future (it
3602
                 will just waste our time).  */
3603
              remote_protocol_P.support = PACKET_DISABLE;
3604
              break;
3605
            }
3606
        }
3607
    }
3608
 
3609
  /* Extract all the registers in the regcache copying them into a
3610
     local buffer.  */
3611
  {
3612
    int i;
3613
    regs = alloca (rs->sizeof_g_packet);
3614
    memset (regs, rs->sizeof_g_packet, 0);
3615
    for (i = 0; i < NUM_REGS + NUM_PSEUDO_REGS; i++)
3616
      {
3617
        struct packet_reg *r = &rs->regs[i];
3618
        if (r->in_g_packet)
3619
          regcache_collect (r->regnum, regs + r->offset);
3620
      }
3621
  }
3622
 
3623
  /* Command describes registers byte by byte,
3624
     each byte encoded as two hex characters.  */
3625
  buf = alloca (rs->remote_packet_size);
3626
  p = buf;
3627
  *p++ = 'G';
3628
  /* remote_prepare_to_store insures that register_bytes_found gets set.  */
3629
  bin2hex (regs, p, register_bytes_found);
3630
  remote_send (buf, (rs->remote_packet_size));
3631
}
3632
 
3633
 
3634
/* Return the number of hex digits in num.  */
3635
 
3636
static int
3637
hexnumlen (ULONGEST num)
3638
{
3639
  int i;
3640
 
3641
  for (i = 0; num != 0; i++)
3642
    num >>= 4;
3643
 
3644
  return max (i, 1);
3645
}
3646
 
3647
/* Set BUF to the minimum number of hex digits representing NUM.  */
3648
 
3649
static int
3650
hexnumstr (char *buf, ULONGEST num)
3651
{
3652
  int len = hexnumlen (num);
3653
  return hexnumnstr (buf, num, len);
3654
}
3655
 
3656
 
3657
/* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
3658
 
3659
static int
3660
hexnumnstr (char *buf, ULONGEST num, int width)
3661
{
3662
  int i;
3663
 
3664
  buf[width] = '\0';
3665
 
3666
  for (i = width - 1; i >= 0; i--)
3667
    {
3668
      buf[i] = "0123456789abcdef"[(num & 0xf)];
3669
      num >>= 4;
3670
    }
3671
 
3672
  return width;
3673
}
3674
 
3675
/* Mask all but the least significant REMOTE_ADDRESS_SIZE bits. */
3676
 
3677
static CORE_ADDR
3678
remote_address_masked (CORE_ADDR addr)
3679
{
3680
  if (remote_address_size > 0
3681
      && remote_address_size < (sizeof (ULONGEST) * 8))
3682
    {
3683
      /* Only create a mask when that mask can safely be constructed
3684
         in a ULONGEST variable. */
3685
      ULONGEST mask = 1;
3686
      mask = (mask << remote_address_size) - 1;
3687
      addr &= mask;
3688
    }
3689
  return addr;
3690
}
3691
 
3692
/* Determine whether the remote target supports binary downloading.
3693
   This is accomplished by sending a no-op memory write of zero length
3694
   to the target at the specified address. It does not suffice to send
3695
   the whole packet, since many stubs strip the eighth bit and subsequently
3696
   compute a wrong checksum, which causes real havoc with remote_write_bytes.
3697
 
3698
   NOTE: This can still lose if the serial line is not eight-bit
3699
   clean. In cases like this, the user should clear "remote
3700
   X-packet". */
3701
 
3702
static void
3703
check_binary_download (CORE_ADDR addr)
3704
{
3705
  struct remote_state *rs = get_remote_state ();
3706
  switch (remote_protocol_binary_download.support)
3707
    {
3708
    case PACKET_DISABLE:
3709
      break;
3710
    case PACKET_ENABLE:
3711
      break;
3712
    case PACKET_SUPPORT_UNKNOWN:
3713
      {
3714
        char *buf = alloca (rs->remote_packet_size);
3715
        char *p;
3716
 
3717
        p = buf;
3718
        *p++ = 'X';
3719
        p += hexnumstr (p, (ULONGEST) addr);
3720
        *p++ = ',';
3721
        p += hexnumstr (p, (ULONGEST) 0);
3722
        *p++ = ':';
3723
        *p = '\0';
3724
 
3725
        putpkt_binary (buf, (int) (p - buf));
3726
        getpkt (buf, (rs->remote_packet_size), 0);
3727
 
3728
        if (buf[0] == '\0')
3729
          {
3730
            if (remote_debug)
3731
              fprintf_unfiltered (gdb_stdlog,
3732
                                  "binary downloading NOT suppported by target\n");
3733
            remote_protocol_binary_download.support = PACKET_DISABLE;
3734
          }
3735
        else
3736
          {
3737
            if (remote_debug)
3738
              fprintf_unfiltered (gdb_stdlog,
3739
                                  "binary downloading suppported by target\n");
3740
            remote_protocol_binary_download.support = PACKET_ENABLE;
3741
          }
3742
        break;
3743
      }
3744
    }
3745
}
3746
 
3747
/* Write memory data directly to the remote machine.
3748
   This does not inform the data cache; the data cache uses this.
3749
   MEMADDR is the address in the remote memory space.
3750
   MYADDR is the address of the buffer in our space.
3751
   LEN is the number of bytes.
3752
 
3753
   Returns number of bytes transferred, or 0 (setting errno) for
3754
   error.  Only transfer a single packet. */
3755
 
3756
static int
3757
remote_write_bytes (CORE_ADDR memaddr, char *myaddr, int len)
3758
{
3759
  unsigned char *buf;
3760
  int max_buf_size;             /* Max size of packet output buffer */
3761
  unsigned char *p;
3762
  unsigned char *plen;
3763
  long sizeof_buf;
3764
  int plenlen;
3765
  int todo;
3766
  int nr_bytes;
3767
 
3768
  /* Verify that the target can support a binary download */
3769
  check_binary_download (memaddr);
3770
 
3771
  /* Determine the max packet size. */
3772
  max_buf_size = get_memory_write_packet_size ();
3773
  sizeof_buf = max_buf_size + 1; /* Space for trailing NUL */
3774
  buf = alloca (sizeof_buf);
3775
 
3776
  /* Subtract header overhead from max payload size -  $M<memaddr>,<len>:#nn */
3777
  max_buf_size -= 2 + hexnumlen (memaddr + len - 1) + 1 + hexnumlen (len) + 4;
3778
 
3779
  /* construct "M"<memaddr>","<len>":" */
3780
  /* sprintf (buf, "M%lx,%x:", (unsigned long) memaddr, todo); */
3781
  p = buf;
3782
 
3783
  /* Append [XM].  Compute a best guess of the number of bytes
3784
     actually transfered. */
3785
  switch (remote_protocol_binary_download.support)
3786
    {
3787
    case PACKET_ENABLE:
3788
      *p++ = 'X';
3789
      /* Best guess at number of bytes that will fit. */
3790
      todo = min (len, max_buf_size);
3791
      break;
3792
    case PACKET_DISABLE:
3793
      *p++ = 'M';
3794
      /* num bytes that will fit */
3795
      todo = min (len, max_buf_size / 2);
3796
      break;
3797
    case PACKET_SUPPORT_UNKNOWN:
3798
      internal_error (__FILE__, __LINE__,
3799
                      "remote_write_bytes: bad internal state");
3800
    default:
3801
      internal_error (__FILE__, __LINE__, "bad switch");
3802
    }
3803
 
3804
  /* Append <memaddr> */
3805
  memaddr = remote_address_masked (memaddr);
3806
  p += hexnumstr (p, (ULONGEST) memaddr);
3807
  *p++ = ',';
3808
 
3809
  /* Append <len>.  Retain the location/size of <len>.  It may
3810
     need to be adjusted once the packet body has been created. */
3811
  plen = p;
3812
  plenlen = hexnumstr (p, (ULONGEST) todo);
3813
  p += plenlen;
3814
  *p++ = ':';
3815
  *p = '\0';
3816
 
3817
  /* Append the packet body. */
3818
  switch (remote_protocol_binary_download.support)
3819
    {
3820
    case PACKET_ENABLE:
3821
      /* Binary mode.  Send target system values byte by byte, in
3822
         increasing byte addresses.  Only escape certain critical
3823
         characters.  */
3824
      for (nr_bytes = 0;
3825
           (nr_bytes < todo) && (p - buf) < (max_buf_size - 2);
3826
           nr_bytes++)
3827
        {
3828
          switch (myaddr[nr_bytes] & 0xff)
3829
            {
3830
            case '$':
3831
            case '#':
3832
            case 0x7d:
3833
              /* These must be escaped */
3834
              *p++ = 0x7d;
3835
              *p++ = (myaddr[nr_bytes] & 0xff) ^ 0x20;
3836
              break;
3837
            default:
3838
              *p++ = myaddr[nr_bytes] & 0xff;
3839
              break;
3840
            }
3841
        }
3842
      if (nr_bytes < todo)
3843
        {
3844
          /* Escape chars have filled up the buffer prematurely,
3845
             and we have actually sent fewer bytes than planned.
3846
             Fix-up the length field of the packet.  Use the same
3847
             number of characters as before.  */
3848
 
3849
          plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
3850
          *plen = ':';  /* overwrite \0 from hexnumnstr() */
3851
        }
3852
      break;
3853
    case PACKET_DISABLE:
3854
      /* Normal mode: Send target system values byte by byte, in
3855
         increasing byte addresses.  Each byte is encoded as a two hex
3856
         value.  */
3857
      nr_bytes = bin2hex (myaddr, p, todo);
3858
      p += 2 * nr_bytes;
3859
      break;
3860
    case PACKET_SUPPORT_UNKNOWN:
3861
      internal_error (__FILE__, __LINE__,
3862
                      "remote_write_bytes: bad internal state");
3863
    default:
3864
      internal_error (__FILE__, __LINE__, "bad switch");
3865
    }
3866
 
3867
  putpkt_binary (buf, (int) (p - buf));
3868
  getpkt (buf, sizeof_buf, 0);
3869
 
3870
  if (buf[0] == 'E')
3871
    {
3872
      /* There is no correspondance between what the remote protocol
3873
         uses for errors and errno codes.  We would like a cleaner way
3874
         of representing errors (big enough to include errno codes,
3875
         bfd_error codes, and others).  But for now just return EIO.  */
3876
      errno = EIO;
3877
      return 0;
3878
    }
3879
 
3880
  /* Return NR_BYTES, not TODO, in case escape chars caused us to send fewer
3881
     bytes than we'd planned.  */
3882
  return nr_bytes;
3883
}
3884
 
3885
/* Read memory data directly from the remote machine.
3886
   This does not use the data cache; the data cache uses this.
3887
   MEMADDR is the address in the remote memory space.
3888
   MYADDR is the address of the buffer in our space.
3889
   LEN is the number of bytes.
3890
 
3891
   Returns number of bytes transferred, or 0 for error.  */
3892
 
3893
/* NOTE: cagney/1999-10-18: This function (and its siblings in other
3894
   remote targets) shouldn't attempt to read the entire buffer.
3895
   Instead it should read a single packet worth of data and then
3896
   return the byte size of that packet to the caller.  The caller (its
3897
   caller and its callers caller ;-) already contains code for
3898
   handling partial reads. */
3899
 
3900
static int
3901
remote_read_bytes (CORE_ADDR memaddr, char *myaddr, int len)
3902
{
3903
  char *buf;
3904
  int max_buf_size;             /* Max size of packet output buffer */
3905
  long sizeof_buf;
3906
  int origlen;
3907
 
3908
  /* Create a buffer big enough for this packet. */
3909
  max_buf_size = get_memory_read_packet_size ();
3910
  sizeof_buf = max_buf_size + 1; /* Space for trailing NUL */
3911
  buf = alloca (sizeof_buf);
3912
 
3913
  origlen = len;
3914
  while (len > 0)
3915
    {
3916
      char *p;
3917
      int todo;
3918
      int i;
3919
 
3920
      todo = min (len, max_buf_size / 2);       /* num bytes that will fit */
3921
 
3922
      /* construct "m"<memaddr>","<len>" */
3923
      /* sprintf (buf, "m%lx,%x", (unsigned long) memaddr, todo); */
3924
      memaddr = remote_address_masked (memaddr);
3925
      p = buf;
3926
      *p++ = 'm';
3927
      p += hexnumstr (p, (ULONGEST) memaddr);
3928
      *p++ = ',';
3929
      p += hexnumstr (p, (ULONGEST) todo);
3930
      *p = '\0';
3931
 
3932
      putpkt (buf);
3933
      getpkt (buf, sizeof_buf, 0);
3934
 
3935
      if (buf[0] == 'E'
3936
          && isxdigit (buf[1]) && isxdigit (buf[2])
3937
          && buf[3] == '\0')
3938
        {
3939
          /* There is no correspondance between what the remote protocol uses
3940
             for errors and errno codes.  We would like a cleaner way of
3941
             representing errors (big enough to include errno codes, bfd_error
3942
             codes, and others).  But for now just return EIO.  */
3943
          errno = EIO;
3944
          return 0;
3945
        }
3946
 
3947
      /* Reply describes memory byte by byte,
3948
         each byte encoded as two hex characters.  */
3949
 
3950
      p = buf;
3951
      if ((i = hex2bin (p, myaddr, todo)) < todo)
3952
        {
3953
          /* Reply is short.  This means that we were able to read
3954
             only part of what we wanted to. */
3955
          return i + (origlen - len);
3956
        }
3957
      myaddr += todo;
3958
      memaddr += todo;
3959
      len -= todo;
3960
    }
3961
  return origlen;
3962
}
3963
 
3964
/* Read or write LEN bytes from inferior memory at MEMADDR,
3965
   transferring to or from debugger address BUFFER.  Write to inferior if
3966
   SHOULD_WRITE is nonzero.  Returns length of data written or read; 0
3967
   for error.  TARGET is unused.  */
3968
 
3969
/* ARGSUSED */
3970
static int
3971
remote_xfer_memory (CORE_ADDR mem_addr, char *buffer, int mem_len,
3972
                    int should_write, struct mem_attrib *attrib,
3973
                    struct target_ops *target)
3974
{
3975
  CORE_ADDR targ_addr;
3976
  int targ_len;
3977
  int res;
3978
 
3979
  REMOTE_TRANSLATE_XFER_ADDRESS (mem_addr, mem_len, &targ_addr, &targ_len);
3980
  if (targ_len <= 0)
3981
    return 0;
3982
 
3983
  if (should_write)
3984
    res = remote_write_bytes (targ_addr, buffer, targ_len);
3985
  else
3986
    res = remote_read_bytes (targ_addr, buffer, targ_len);
3987
 
3988
  return res;
3989
}
3990
 
3991
 
3992
#if 0
3993
/* Enable after 4.12.  */
3994
 
3995
void
3996
remote_search (int len, char *data, char *mask, CORE_ADDR startaddr,
3997
               int increment, CORE_ADDR lorange, CORE_ADDR hirange,
3998
               CORE_ADDR *addr_found, char *data_found)
3999
{
4000
  if (increment == -4 && len == 4)
4001
    {
4002
      long mask_long, data_long;
4003
      long data_found_long;
4004
      CORE_ADDR addr_we_found;
4005
      char *buf = alloca (rs->remote_packet_size);
4006
      long returned_long[2];
4007
      char *p;
4008
 
4009
      mask_long = extract_unsigned_integer (mask, len);
4010
      data_long = extract_unsigned_integer (data, len);
4011
      sprintf (buf, "t%x:%x,%x", startaddr, data_long, mask_long);
4012
      putpkt (buf);
4013
      getpkt (buf, (rs->remote_packet_size), 0);
4014
      if (buf[0] == '\0')
4015
        {
4016
          /* The stub doesn't support the 't' request.  We might want to
4017
             remember this fact, but on the other hand the stub could be
4018
             switched on us.  Maybe we should remember it only until
4019
             the next "target remote".  */
4020
          generic_search (len, data, mask, startaddr, increment, lorange,
4021
                          hirange, addr_found, data_found);
4022
          return;
4023
        }
4024
 
4025
      if (buf[0] == 'E')
4026
        /* There is no correspondance between what the remote protocol uses
4027
           for errors and errno codes.  We would like a cleaner way of
4028
           representing errors (big enough to include errno codes, bfd_error
4029
           codes, and others).  But for now just use EIO.  */
4030
        memory_error (EIO, startaddr);
4031
      p = buf;
4032
      addr_we_found = 0;
4033
      while (*p != '\0' && *p != ',')
4034
        addr_we_found = (addr_we_found << 4) + fromhex (*p++);
4035
      if (*p == '\0')
4036
        error ("Protocol error: short return for search");
4037
 
4038
      data_found_long = 0;
4039
      while (*p != '\0' && *p != ',')
4040
        data_found_long = (data_found_long << 4) + fromhex (*p++);
4041
      /* Ignore anything after this comma, for future extensions.  */
4042
 
4043
      if (addr_we_found < lorange || addr_we_found >= hirange)
4044
        {
4045
          *addr_found = 0;
4046
          return;
4047
        }
4048
 
4049
      *addr_found = addr_we_found;
4050
      *data_found = store_unsigned_integer (data_we_found, len);
4051
      return;
4052
    }
4053
  generic_search (len, data, mask, startaddr, increment, lorange,
4054
                  hirange, addr_found, data_found);
4055
}
4056
#endif /* 0 */
4057
 
4058
static void
4059
remote_files_info (struct target_ops *ignore)
4060
{
4061
  puts_filtered ("Debugging a target over a serial line.\n");
4062
}
4063
 
4064
/* Stuff for dealing with the packets which are part of this protocol.
4065
   See comment at top of file for details.  */
4066
 
4067
/* Read a single character from the remote end, masking it down to 7 bits. */
4068
 
4069
static int
4070
readchar (int timeout)
4071
{
4072
  int ch;
4073
 
4074
  ch = serial_readchar (remote_desc, timeout);
4075
 
4076
  if (ch >= 0)
4077
    return (ch & 0x7f);
4078
 
4079
  switch ((enum serial_rc) ch)
4080
    {
4081
    case SERIAL_EOF:
4082
      target_mourn_inferior ();
4083
      error ("Remote connection closed");
4084
      /* no return */
4085
    case SERIAL_ERROR:
4086
      perror_with_name ("Remote communication error");
4087
      /* no return */
4088
    case SERIAL_TIMEOUT:
4089
      break;
4090
    }
4091
  return ch;
4092
}
4093
 
4094
/* Send the command in BUF to the remote machine, and read the reply
4095
   into BUF.  Report an error if we get an error reply.  */
4096
 
4097
static void
4098
remote_send (char *buf,
4099
             long sizeof_buf)
4100
{
4101
  putpkt (buf);
4102
  getpkt (buf, sizeof_buf, 0);
4103
 
4104
  if (buf[0] == 'E')
4105
    error ("Remote failure reply: %s", buf);
4106
}
4107
 
4108
/* Display a null-terminated packet on stdout, for debugging, using C
4109
   string notation.  */
4110
 
4111
static void
4112
print_packet (char *buf)
4113
{
4114
  puts_filtered ("\"");
4115
  fputstr_filtered (buf, '"', gdb_stdout);
4116
  puts_filtered ("\"");
4117
}
4118
 
4119
int
4120
putpkt (char *buf)
4121
{
4122
  return putpkt_binary (buf, strlen (buf));
4123
}
4124
 
4125
/* Send a packet to the remote machine, with error checking.  The data
4126
   of the packet is in BUF.  The string in BUF can be at most  (rs->remote_packet_size) - 5
4127
   to account for the $, # and checksum, and for a possible /0 if we are
4128
   debugging (remote_debug) and want to print the sent packet as a string */
4129
 
4130
static int
4131
putpkt_binary (char *buf, int cnt)
4132
{
4133
  struct remote_state *rs = get_remote_state ();
4134
  int i;
4135
  unsigned char csum = 0;
4136
  char *buf2 = alloca (cnt + 6);
4137
  long sizeof_junkbuf = (rs->remote_packet_size);
4138
  char *junkbuf = alloca (sizeof_junkbuf);
4139
 
4140
  int ch;
4141
  int tcount = 0;
4142
  char *p;
4143
 
4144
  /* Copy the packet into buffer BUF2, encapsulating it
4145
     and giving it a checksum.  */
4146
 
4147
  p = buf2;
4148
  *p++ = '$';
4149
 
4150
  for (i = 0; i < cnt; i++)
4151
    {
4152
      csum += buf[i];
4153
      *p++ = buf[i];
4154
    }
4155
  *p++ = '#';
4156
  *p++ = tohex ((csum >> 4) & 0xf);
4157
  *p++ = tohex (csum & 0xf);
4158
 
4159
  /* Send it over and over until we get a positive ack.  */
4160
 
4161
  while (1)
4162
    {
4163
      int started_error_output = 0;
4164
 
4165
      if (remote_debug)
4166
        {
4167
          *p = '\0';
4168
          fprintf_unfiltered (gdb_stdlog, "Sending packet: ");
4169
          fputstrn_unfiltered (buf2, p - buf2, 0, gdb_stdlog);
4170
          fprintf_unfiltered (gdb_stdlog, "...");
4171
          gdb_flush (gdb_stdlog);
4172
        }
4173
      if (serial_write (remote_desc, buf2, p - buf2))
4174
        perror_with_name ("putpkt: write failed");
4175
 
4176
      /* read until either a timeout occurs (-2) or '+' is read */
4177
      while (1)
4178
        {
4179
          ch = readchar (remote_timeout);
4180
 
4181
          if (remote_debug)
4182
            {
4183
              switch (ch)
4184
                {
4185
                case '+':
4186
                case '-':
4187
                case SERIAL_TIMEOUT:
4188
                case '$':
4189
                  if (started_error_output)
4190
                    {
4191
                      putchar_unfiltered ('\n');
4192
                      started_error_output = 0;
4193
                    }
4194
                }
4195
            }
4196
 
4197
          switch (ch)
4198
            {
4199
            case '+':
4200
              if (remote_debug)
4201
                fprintf_unfiltered (gdb_stdlog, "Ack\n");
4202
              return 1;
4203
            case '-':
4204
              if (remote_debug)
4205
                fprintf_unfiltered (gdb_stdlog, "Nak\n");
4206
            case SERIAL_TIMEOUT:
4207
              tcount++;
4208
              if (tcount > 3)
4209
                return 0;
4210
              break;            /* Retransmit buffer */
4211
            case '$':
4212
              {
4213
                if (remote_debug)
4214
                  fprintf_unfiltered (gdb_stdlog, "Packet instead of Ack, ignoring it\n");
4215
                /* It's probably an old response, and we're out of sync.
4216
                   Just gobble up the packet and ignore it.  */
4217
                read_frame (junkbuf, sizeof_junkbuf);
4218
                continue;       /* Now, go look for + */
4219
              }
4220
            default:
4221
              if (remote_debug)
4222
                {
4223
                  if (!started_error_output)
4224
                    {
4225
                      started_error_output = 1;
4226
                      fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
4227
                    }
4228
                  fputc_unfiltered (ch & 0177, gdb_stdlog);
4229
                }
4230
              continue;
4231
            }
4232
          break;                /* Here to retransmit */
4233
        }
4234
 
4235
#if 0
4236
      /* This is wrong.  If doing a long backtrace, the user should be
4237
         able to get out next time we call QUIT, without anything as
4238
         violent as interrupt_query.  If we want to provide a way out of
4239
         here without getting to the next QUIT, it should be based on
4240
         hitting ^C twice as in remote_wait.  */
4241
      if (quit_flag)
4242
        {
4243
          quit_flag = 0;
4244
          interrupt_query ();
4245
        }
4246
#endif
4247
    }
4248
}
4249
 
4250
static int remote_cisco_mode;
4251
 
4252
/* Come here after finding the start of the frame.  Collect the rest
4253
   into BUF, verifying the checksum, length, and handling run-length
4254
   compression.  No more than sizeof_buf-1 characters are read so that
4255
   the buffer can be NUL terminated.
4256
 
4257
   Returns -1 on error, number of characters in buffer (ignoring the
4258
   trailing NULL) on success. (could be extended to return one of the
4259
   SERIAL status indications). */
4260
 
4261
static long
4262
read_frame (char *buf,
4263
            long sizeof_buf)
4264
{
4265
  unsigned char csum;
4266
  long bc;
4267
  int c;
4268
 
4269
  csum = 0;
4270
  bc = 0;
4271
 
4272
  while (1)
4273
    {
4274
      /* ASSERT (bc < sizeof_buf - 1) - space for trailing NUL */
4275
      c = readchar (remote_timeout);
4276
      switch (c)
4277
        {
4278
        case SERIAL_TIMEOUT:
4279
          if (remote_debug)
4280
            fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
4281
          return -1;
4282
        case '$':
4283
          if (remote_debug)
4284
            fputs_filtered ("Saw new packet start in middle of old one\n",
4285
                            gdb_stdlog);
4286
          return -1;            /* Start a new packet, count retries */
4287
        case '#':
4288
          {
4289
            unsigned char pktcsum;
4290
            int check_0 = 0;
4291
            int check_1 = 0;
4292
 
4293
            buf[bc] = '\0';
4294
 
4295
            check_0 = readchar (remote_timeout);
4296
            if (check_0 >= 0)
4297
              check_1 = readchar (remote_timeout);
4298
 
4299
            if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
4300
              {
4301
                if (remote_debug)
4302
                  fputs_filtered ("Timeout in checksum, retrying\n", gdb_stdlog);
4303
                return -1;
4304
              }
4305
            else if (check_0 < 0 || check_1 < 0)
4306
              {
4307
                if (remote_debug)
4308
                  fputs_filtered ("Communication error in checksum\n", gdb_stdlog);
4309
                return -1;
4310
              }
4311
 
4312
            pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
4313
            if (csum == pktcsum)
4314
              return bc;
4315
 
4316
            if (remote_debug)
4317
              {
4318
                fprintf_filtered (gdb_stdlog,
4319
                              "Bad checksum, sentsum=0x%x, csum=0x%x, buf=",
4320
                                  pktcsum, csum);
4321
                fputs_filtered (buf, gdb_stdlog);
4322
                fputs_filtered ("\n", gdb_stdlog);
4323
              }
4324
            /* Number of characters in buffer ignoring trailing
4325
               NUL. */
4326
            return -1;
4327
          }
4328
        case '*':               /* Run length encoding */
4329
          {
4330
            int repeat;
4331
            csum += c;
4332
 
4333
            if (remote_cisco_mode == 0)
4334
              {
4335
                c = readchar (remote_timeout);
4336
                csum += c;
4337
                repeat = c - ' ' + 3;   /* Compute repeat count */
4338
              }
4339
            else
4340
              {
4341
                /* Cisco's run-length encoding variant uses two
4342
                   hex chars to represent the repeat count. */
4343
 
4344
                c = readchar (remote_timeout);
4345
                csum += c;
4346
                repeat  = fromhex (c) << 4;
4347
                c = readchar (remote_timeout);
4348
                csum += c;
4349
                repeat += fromhex (c);
4350
              }
4351
 
4352
            /* The character before ``*'' is repeated. */
4353
 
4354
            if (repeat > 0 && repeat <= 255
4355
                && bc > 0
4356
                && bc + repeat - 1 < sizeof_buf - 1)
4357
              {
4358
                memset (&buf[bc], buf[bc - 1], repeat);
4359
                bc += repeat;
4360
                continue;
4361
              }
4362
 
4363
            buf[bc] = '\0';
4364
            printf_filtered ("Repeat count %d too large for buffer: ", repeat);
4365
            puts_filtered (buf);
4366
            puts_filtered ("\n");
4367
            return -1;
4368
          }
4369
        default:
4370
          if (bc < sizeof_buf - 1)
4371
            {
4372
              buf[bc++] = c;
4373
              csum += c;
4374
              continue;
4375
            }
4376
 
4377
          buf[bc] = '\0';
4378
          puts_filtered ("Remote packet too long: ");
4379
          puts_filtered (buf);
4380
          puts_filtered ("\n");
4381
 
4382
          return -1;
4383
        }
4384
    }
4385
}
4386
 
4387
/* Read a packet from the remote machine, with error checking, and
4388
   store it in BUF.  If FOREVER, wait forever rather than timing out;
4389
   this is used (in synchronous mode) to wait for a target that is is
4390
   executing user code to stop.  */
4391
/* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
4392
   don't have to change all the calls to getpkt to deal with the
4393
   return value, because at the moment I don't know what the right
4394
   thing to do it for those. */
4395
void
4396
getpkt (char *buf,
4397
        long sizeof_buf,
4398
        int forever)
4399
{
4400
  int timed_out;
4401
 
4402
  timed_out = getpkt_sane (buf, sizeof_buf, forever);
4403
}
4404
 
4405
 
4406
/* Read a packet from the remote machine, with error checking, and
4407
   store it in BUF.  If FOREVER, wait forever rather than timing out;
4408
   this is used (in synchronous mode) to wait for a target that is is
4409
   executing user code to stop. If FOREVER == 0, this function is
4410
   allowed to time out gracefully and return an indication of this to
4411
   the caller. */
4412
static int
4413
getpkt_sane (char *buf,
4414
        long sizeof_buf,
4415
        int forever)
4416
{
4417
  int c;
4418
  int tries;
4419
  int timeout;
4420
  int val;
4421
 
4422
  strcpy (buf, "timeout");
4423
 
4424
  if (forever)
4425
    {
4426
      timeout = watchdog > 0 ? watchdog : -1;
4427
    }
4428
 
4429
  else
4430
    timeout = remote_timeout;
4431
 
4432
#define MAX_TRIES 3
4433
 
4434
  for (tries = 1; tries <= MAX_TRIES; tries++)
4435
    {
4436
      /* This can loop forever if the remote side sends us characters
4437
         continuously, but if it pauses, we'll get a zero from readchar
4438
         because of timeout.  Then we'll count that as a retry.  */
4439
 
4440
      /* Note that we will only wait forever prior to the start of a packet.
4441
         After that, we expect characters to arrive at a brisk pace.  They
4442
         should show up within remote_timeout intervals.  */
4443
 
4444
      do
4445
        {
4446
          c = readchar (timeout);
4447
 
4448
          if (c == SERIAL_TIMEOUT)
4449
            {
4450
              if (forever)      /* Watchdog went off?  Kill the target. */
4451
                {
4452
                  QUIT;
4453
                  target_mourn_inferior ();
4454
                  error ("Watchdog has expired.  Target detached.\n");
4455
                }
4456
              if (remote_debug)
4457
                fputs_filtered ("Timed out.\n", gdb_stdlog);
4458
              goto retry;
4459
            }
4460
        }
4461
      while (c != '$');
4462
 
4463
      /* We've found the start of a packet, now collect the data.  */
4464
 
4465
      val = read_frame (buf, sizeof_buf);
4466
 
4467
      if (val >= 0)
4468
        {
4469
          if (remote_debug)
4470
            {
4471
              fprintf_unfiltered (gdb_stdlog, "Packet received: ");
4472
              fputstr_unfiltered (buf, 0, gdb_stdlog);
4473
              fprintf_unfiltered (gdb_stdlog, "\n");
4474
            }
4475
          serial_write (remote_desc, "+", 1);
4476
          return 0;
4477
        }
4478
 
4479
      /* Try the whole thing again.  */
4480
    retry:
4481
      serial_write (remote_desc, "-", 1);
4482
    }
4483
 
4484
  /* We have tried hard enough, and just can't receive the packet.  Give up. */
4485
 
4486
  printf_unfiltered ("Ignoring packet error, continuing...\n");
4487
  serial_write (remote_desc, "+", 1);
4488
  return 1;
4489
}
4490
 
4491
static void
4492
remote_kill (void)
4493
{
4494
  /* For some mysterious reason, wait_for_inferior calls kill instead of
4495
     mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
4496
  if (kill_kludge)
4497
    {
4498
      kill_kludge = 0;
4499
      target_mourn_inferior ();
4500
      return;
4501
    }
4502
 
4503
  /* Use catch_errors so the user can quit from gdb even when we aren't on
4504
     speaking terms with the remote system.  */
4505
  catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4506
 
4507
  /* Don't wait for it to die.  I'm not really sure it matters whether
4508
     we do or not.  For the existing stubs, kill is a noop.  */
4509
  target_mourn_inferior ();
4510
}
4511
 
4512
/* Async version of remote_kill. */
4513
static void
4514
remote_async_kill (void)
4515
{
4516
  /* Unregister the file descriptor from the event loop. */
4517
  if (target_is_async_p ())
4518
    serial_async (remote_desc, NULL, 0);
4519
 
4520
  /* For some mysterious reason, wait_for_inferior calls kill instead of
4521
     mourn after it gets TARGET_WAITKIND_SIGNALLED.  Work around it.  */
4522
  if (kill_kludge)
4523
    {
4524
      kill_kludge = 0;
4525
      target_mourn_inferior ();
4526
      return;
4527
    }
4528
 
4529
  /* Use catch_errors so the user can quit from gdb even when we aren't on
4530
     speaking terms with the remote system.  */
4531
  catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
4532
 
4533
  /* Don't wait for it to die.  I'm not really sure it matters whether
4534
     we do or not.  For the existing stubs, kill is a noop.  */
4535
  target_mourn_inferior ();
4536
}
4537
 
4538
static void
4539
remote_mourn (void)
4540
{
4541
  remote_mourn_1 (&remote_ops);
4542
}
4543
 
4544
static void
4545
remote_async_mourn (void)
4546
{
4547
  remote_mourn_1 (&remote_async_ops);
4548
}
4549
 
4550
static void
4551
extended_remote_mourn (void)
4552
{
4553
  /* We do _not_ want to mourn the target like this; this will
4554
     remove the extended remote target  from the target stack,
4555
     and the next time the user says "run" it'll fail.
4556
 
4557
     FIXME: What is the right thing to do here?  */
4558
#if 0
4559
  remote_mourn_1 (&extended_remote_ops);
4560
#endif
4561
}
4562
 
4563
/* Worker function for remote_mourn.  */
4564
static void
4565
remote_mourn_1 (struct target_ops *target)
4566
{
4567
  unpush_target (target);
4568
  generic_mourn_inferior ();
4569
}
4570
 
4571
/* In the extended protocol we want to be able to do things like
4572
   "run" and have them basically work as expected.  So we need
4573
   a special create_inferior function.
4574
 
4575
   FIXME: One day add support for changing the exec file
4576
   we're debugging, arguments and an environment.  */
4577
 
4578
static void
4579
extended_remote_create_inferior (char *exec_file, char *args, char **env)
4580
{
4581
  /* Rip out the breakpoints; we'll reinsert them after restarting
4582
     the remote server.  */
4583
  remove_breakpoints ();
4584
 
4585
  /* Now restart the remote server.  */
4586
  extended_remote_restart ();
4587
 
4588
  /* Now put the breakpoints back in.  This way we're safe if the
4589
     restart function works via a unix fork on the remote side.  */
4590
  insert_breakpoints ();
4591
 
4592
  /* Clean up from the last time we were running.  */
4593
  clear_proceed_status ();
4594
 
4595
  /* Let the remote process run.  */
4596
  proceed (-1, TARGET_SIGNAL_0, 0);
4597
}
4598
 
4599
/* Async version of extended_remote_create_inferior. */
4600
static void
4601
extended_remote_async_create_inferior (char *exec_file, char *args, char **env)
4602
{
4603
  /* Rip out the breakpoints; we'll reinsert them after restarting
4604
     the remote server.  */
4605
  remove_breakpoints ();
4606
 
4607
  /* If running asynchronously, register the target file descriptor
4608
     with the event loop. */
4609
  if (event_loop_p && target_can_async_p ())
4610
    target_async (inferior_event_handler, 0);
4611
 
4612
  /* Now restart the remote server.  */
4613
  extended_remote_restart ();
4614
 
4615
  /* Now put the breakpoints back in.  This way we're safe if the
4616
     restart function works via a unix fork on the remote side.  */
4617
  insert_breakpoints ();
4618
 
4619
  /* Clean up from the last time we were running.  */
4620
  clear_proceed_status ();
4621
 
4622
  /* Let the remote process run.  */
4623
  proceed (-1, TARGET_SIGNAL_0, 0);
4624
}
4625
 
4626
 
4627
/* On some machines, e.g. 68k, we may use a different breakpoint instruction
4628
   than other targets; in those use REMOTE_BREAKPOINT instead of just
4629
   BREAKPOINT.  Also, bi-endian targets may define LITTLE_REMOTE_BREAKPOINT
4630
   and BIG_REMOTE_BREAKPOINT.  If none of these are defined, we just call
4631
   the standard routines that are in mem-break.c.  */
4632
 
4633
/* FIXME, these ought to be done in a more dynamic fashion.  For instance,
4634
   the choice of breakpoint instruction affects target program design and
4635
   vice versa, and by making it user-tweakable, the special code here
4636
   goes away and we need fewer special GDB configurations.  */
4637
 
4638
#if defined (LITTLE_REMOTE_BREAKPOINT) && defined (BIG_REMOTE_BREAKPOINT) && !defined(REMOTE_BREAKPOINT)
4639
#define REMOTE_BREAKPOINT
4640
#endif
4641
 
4642
#ifdef REMOTE_BREAKPOINT
4643
 
4644
/* If the target isn't bi-endian, just pretend it is.  */
4645
#if !defined (LITTLE_REMOTE_BREAKPOINT) && !defined (BIG_REMOTE_BREAKPOINT)
4646
#define LITTLE_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
4647
#define BIG_REMOTE_BREAKPOINT REMOTE_BREAKPOINT
4648
#endif
4649
 
4650
static unsigned char big_break_insn[] = BIG_REMOTE_BREAKPOINT;
4651
static unsigned char little_break_insn[] = LITTLE_REMOTE_BREAKPOINT;
4652
 
4653
#endif /* REMOTE_BREAKPOINT */
4654
 
4655
/* Insert a breakpoint on targets that don't have any better breakpoint
4656
   support.  We read the contents of the target location and stash it,
4657
   then overwrite it with a breakpoint instruction.  ADDR is the target
4658
   location in the target machine.  CONTENTS_CACHE is a pointer to
4659
   memory allocated for saving the target contents.  It is guaranteed
4660
   by the caller to be long enough to save sizeof BREAKPOINT bytes (this
4661
   is accomplished via BREAKPOINT_MAX).  */
4662
 
4663
static int
4664
remote_insert_breakpoint (CORE_ADDR addr, char *contents_cache)
4665
{
4666
  struct remote_state *rs = get_remote_state ();
4667
  int val;
4668
  int bp_size;
4669
 
4670
  /* Try the "Z" s/w breakpoint packet if it is not already disabled.
4671
     If it succeeds, then set the support to PACKET_ENABLE.  If it
4672
     fails, and the user has explicitly requested the Z support then
4673
     report an error, otherwise, mark it disabled and go on. */
4674
 
4675
  if (remote_protocol_Z[Z_PACKET_SOFTWARE_BP].support != PACKET_DISABLE)
4676
    {
4677
      char *buf = alloca (rs->remote_packet_size);
4678
      char *p = buf;
4679
 
4680
      addr = remote_address_masked (addr);
4681
      *(p++) = 'Z';
4682
      *(p++) = '0';
4683
      *(p++) = ',';
4684
      p += hexnumstr (p, (ULONGEST) addr);
4685
      BREAKPOINT_FROM_PC (&addr, &bp_size);
4686
      sprintf (p, ",%d", bp_size);
4687
 
4688
      putpkt (buf);
4689
      getpkt (buf, (rs->remote_packet_size), 0);
4690
 
4691
      switch (packet_ok (buf, &remote_protocol_Z[Z_PACKET_SOFTWARE_BP]))
4692
        {
4693
        case PACKET_ERROR:
4694 1258 hpanther
        {
4695
                if (remote_protocol_Z[Z_PACKET_HARDWARE_BP].support != PACKET_DISABLE)
4696
                        return remote_insert_hw_breakpoint (addr, contents_cache);
4697
                else
4698
                        return -1;
4699
        }
4700 1181 sfurman
        case PACKET_OK:
4701
          return 0;
4702
        case PACKET_UNKNOWN:
4703
          break;
4704
        }
4705
    }
4706
 
4707
#ifdef REMOTE_BREAKPOINT  
4708
  val = target_read_memory (addr, contents_cache, sizeof big_break_insn);
4709
 
4710
  if (val == 0)
4711
    {
4712
      if (TARGET_BYTE_ORDER == BFD_ENDIAN_BIG)
4713
        val = target_write_memory (addr, (char *) big_break_insn,
4714
                                   sizeof big_break_insn);
4715
      else
4716
        val = target_write_memory (addr, (char *) little_break_insn,
4717
                                   sizeof little_break_insn);
4718
    }
4719
#else
4720 1258 hpanther
  val = memory_insert_breakpoint (addr, contents_cache);
4721 1181 sfurman
#endif /* REMOTE_BREAKPOINT */
4722 1258 hpanther
 
4723
  if ((val != 0) && (remote_protocol_Z[Z_PACKET_HARDWARE_BP].support != PACKET_DISABLE))
4724
          val = remote_insert_hw_breakpoint (addr, contents_cache);
4725
 
4726
  return val;
4727 1181 sfurman
}
4728
 
4729
static int
4730
remote_remove_breakpoint (CORE_ADDR addr, char *contents_cache)
4731
{
4732
  struct remote_state *rs = get_remote_state ();
4733
  int bp_size;
4734 1258 hpanther
  int val;
4735
 
4736 1181 sfurman
  if (remote_protocol_Z[Z_PACKET_SOFTWARE_BP].support != PACKET_DISABLE)
4737
    {
4738
      char *buf = alloca (rs->remote_packet_size);
4739
      char *p = buf;
4740
 
4741
      *(p++) = 'z';
4742
      *(p++) = '0';
4743
      *(p++) = ',';
4744
 
4745
      addr = remote_address_masked (addr);
4746
      p += hexnumstr (p, (ULONGEST) addr);
4747
      BREAKPOINT_FROM_PC (&addr, &bp_size);
4748
      sprintf (p, ",%d", bp_size);
4749
 
4750
      putpkt (buf);
4751
      getpkt (buf, (rs->remote_packet_size), 0);
4752
 
4753 1258 hpanther
          if (buf[0] == 'E')
4754
                  return remote_remove_hw_breakpoint (addr, contents_cache);
4755
          else
4756
                  return 0;
4757 1181 sfurman
    }
4758 1258 hpanther
 
4759 1181 sfurman
#ifdef REMOTE_BREAKPOINT
4760 1258 hpanther
  val = target_write_memory (addr, contents_cache, sizeof big_break_insn);
4761 1181 sfurman
#else
4762 1258 hpanther
  val = memory_remove_breakpoint (addr, contents_cache);
4763 1181 sfurman
#endif /* REMOTE_BREAKPOINT */
4764 1258 hpanther
 
4765
  if ((val != 0) && (remote_protocol_Z[Z_PACKET_HARDWARE_BP].support != PACKET_DISABLE))
4766
          val = remote_remove_hw_breakpoint (addr, contents_cache);
4767
  return val;
4768 1181 sfurman
}
4769
 
4770
static int
4771
watchpoint_to_Z_packet (int type)
4772
{
4773
  switch (type)
4774
    {
4775
    case hw_write:
4776
      return 2;
4777
      break;
4778
    case hw_read:
4779
      return 3;
4780
      break;
4781
    case hw_access:
4782
      return 4;
4783
      break;
4784
    default:
4785
      internal_error (__FILE__, __LINE__,
4786
                      "hw_bp_to_z: bad watchpoint type %d", type);
4787
    }
4788
}
4789
 
4790
static int
4791
remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
4792
{
4793
  struct remote_state *rs = get_remote_state ();
4794
  char *buf = alloca (rs->remote_packet_size);
4795
  char *p;
4796
  enum Z_packet_type packet = watchpoint_to_Z_packet (type);
4797
 
4798
  if (remote_protocol_Z[packet].support == PACKET_DISABLE)
4799
    error ("Can't set hardware watchpoints without the '%s' (%s) packet\n",
4800
           remote_protocol_Z[packet].name,
4801
           remote_protocol_Z[packet].title);
4802
 
4803
  sprintf (buf, "Z%x,", packet);
4804
  p = strchr (buf, '\0');
4805
  addr = remote_address_masked (addr);
4806
  p += hexnumstr (p, (ULONGEST) addr);
4807
  sprintf (p, ",%x", len);
4808
 
4809
  putpkt (buf);
4810
  getpkt (buf, (rs->remote_packet_size), 0);
4811
 
4812
  switch (packet_ok (buf, &remote_protocol_Z[packet]))
4813
    {
4814
    case PACKET_ERROR:
4815
    case PACKET_UNKNOWN:
4816
      return -1;
4817
    case PACKET_OK:
4818
      return 0;
4819
    }
4820
  internal_error (__FILE__, __LINE__,
4821
                  "remote_insert_watchpoint: reached end of function");
4822
}
4823
 
4824
 
4825
static int
4826
remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
4827
{
4828
  struct remote_state *rs = get_remote_state ();
4829
  char *buf = alloca (rs->remote_packet_size);
4830
  char *p;
4831
  enum Z_packet_type packet = watchpoint_to_Z_packet (type);
4832
 
4833
  if (remote_protocol_Z[packet].support == PACKET_DISABLE)
4834
    error ("Can't clear hardware watchpoints without the '%s' (%s) packet\n",
4835
           remote_protocol_Z[packet].name,
4836
           remote_protocol_Z[packet].title);
4837
 
4838
  sprintf (buf, "z%x,", packet);
4839
  p = strchr (buf, '\0');
4840
  addr = remote_address_masked (addr);
4841
  p += hexnumstr (p, (ULONGEST) addr);
4842
  sprintf (p, ",%x", len);
4843
  putpkt (buf);
4844
  getpkt (buf, (rs->remote_packet_size), 0);
4845
 
4846
  switch (packet_ok (buf, &remote_protocol_Z[packet]))
4847
    {
4848
    case PACKET_ERROR:
4849
    case PACKET_UNKNOWN:
4850
      return -1;
4851
    case PACKET_OK:
4852
      return 0;
4853
    }
4854
  internal_error (__FILE__, __LINE__,
4855
                  "remote_remove_watchpoint: reached end of function");
4856
}
4857
 
4858
 
4859
int remote_hw_watchpoint_limit = 0;
4860
int remote_hw_breakpoint_limit = 0;
4861
 
4862
int
4863
remote_check_watch_resources (int type, int cnt, int ot)
4864
{
4865
  if (type == bp_hardware_breakpoint)
4866
    {
4867
      if (remote_hw_breakpoint_limit == 0)
4868
        return 0;
4869
      else if (cnt <= remote_hw_breakpoint_limit)
4870
        return 1;
4871
    }
4872
  else
4873
    {
4874
      if (remote_hw_watchpoint_limit == 0)
4875
        return 0;
4876
      else if (ot)
4877
        return -1;
4878
      else if (cnt <= remote_hw_watchpoint_limit)
4879
        return 1;
4880
    }
4881
  return -1;
4882
}
4883
 
4884
int
4885
remote_stopped_by_watchpoint (void)
4886
{
4887
    return remote_stopped_by_watchpoint_p;
4888
}
4889
 
4890
CORE_ADDR
4891
remote_stopped_data_address (void)
4892
{
4893
  if (remote_stopped_by_watchpoint ())
4894
    return remote_watch_data_address;
4895
  return (CORE_ADDR)0;
4896
}
4897
 
4898
 
4899
static int
4900
remote_insert_hw_breakpoint (CORE_ADDR addr, char *shadow)
4901
{
4902
  int len = 0;
4903
  struct remote_state *rs = get_remote_state ();
4904
  char *buf = alloca (rs->remote_packet_size);
4905
  char *p = buf;
4906
 
4907
  /* The length field should be set to the size of a breakpoint
4908
     instruction.  */
4909
 
4910
  BREAKPOINT_FROM_PC (&addr, &len);
4911
 
4912
  if (remote_protocol_Z[Z_PACKET_HARDWARE_BP].support == PACKET_DISABLE)
4913
    error ("Can't set hardware breakpoint without the '%s' (%s) packet\n",
4914
           remote_protocol_Z[Z_PACKET_HARDWARE_BP].name,
4915
           remote_protocol_Z[Z_PACKET_HARDWARE_BP].title);
4916
 
4917
  *(p++) = 'Z';
4918
  *(p++) = '1';
4919
  *(p++) = ',';
4920
 
4921
  addr = remote_address_masked (addr);
4922
  p += hexnumstr (p, (ULONGEST) addr);
4923
  sprintf (p, ",%x", len);
4924
 
4925
  putpkt (buf);
4926
  getpkt (buf, (rs->remote_packet_size), 0);
4927
 
4928
  switch (packet_ok (buf, &remote_protocol_Z[Z_PACKET_HARDWARE_BP]))
4929
    {
4930
    case PACKET_ERROR:
4931
    case PACKET_UNKNOWN:
4932
      return -1;
4933
    case PACKET_OK:
4934
      return 0;
4935
    }
4936
  internal_error (__FILE__, __LINE__,
4937
                  "remote_insert_hw_breakpoint: reached end of function");
4938
}
4939
 
4940
 
4941
static int
4942
remote_remove_hw_breakpoint (CORE_ADDR addr, char *shadow)
4943
{
4944
  int len;
4945
  struct remote_state *rs = get_remote_state ();
4946
  char *buf = alloca (rs->remote_packet_size);
4947
  char *p = buf;
4948
 
4949
  /* The length field should be set to the size of a breakpoint
4950
     instruction.  */
4951
 
4952
  BREAKPOINT_FROM_PC (&addr, &len);
4953
 
4954
  if (remote_protocol_Z[Z_PACKET_HARDWARE_BP].support == PACKET_DISABLE)
4955
    error ("Can't clear hardware breakpoint without the '%s' (%s) packet\n",
4956
           remote_protocol_Z[Z_PACKET_HARDWARE_BP].name,
4957
           remote_protocol_Z[Z_PACKET_HARDWARE_BP].title);
4958
 
4959
  *(p++) = 'z';
4960
  *(p++) = '1';
4961
  *(p++) = ',';
4962
 
4963
  addr = remote_address_masked (addr);
4964
  p += hexnumstr (p, (ULONGEST) addr);
4965
  sprintf (p, ",%x", len);
4966
 
4967
  putpkt(buf);
4968
  getpkt (buf, (rs->remote_packet_size), 0);
4969
 
4970
  switch (packet_ok (buf, &remote_protocol_Z[Z_PACKET_HARDWARE_BP]))
4971
    {
4972
    case PACKET_ERROR:
4973
    case PACKET_UNKNOWN:
4974
      return -1;
4975
    case PACKET_OK:
4976
      return 0;
4977
    }
4978
  internal_error (__FILE__, __LINE__,
4979
                  "remote_remove_hw_breakpoint: reached end of function");
4980
}
4981
 
4982
/* Some targets are only capable of doing downloads, and afterwards
4983
   they switch to the remote serial protocol.  This function provides
4984
   a clean way to get from the download target to the remote target.
4985
   It's basically just a wrapper so that we don't have to expose any
4986
   of the internal workings of remote.c.
4987
 
4988
   Prior to calling this routine, you should shutdown the current
4989
   target code, else you will get the "A program is being debugged
4990
   already..." message.  Usually a call to pop_target() suffices.  */
4991
 
4992
void
4993
push_remote_target (char *name, int from_tty)
4994
{
4995
  printf_filtered ("Switching to remote protocol\n");
4996
  remote_open (name, from_tty);
4997
}
4998
 
4999
/* Table used by the crc32 function to calcuate the checksum. */
5000
 
5001
static unsigned long crc32_table[256] =
5002
{0, 0};
5003
 
5004
static unsigned long
5005
crc32 (unsigned char *buf, int len, unsigned int crc)
5006
{
5007
  if (!crc32_table[1])
5008
    {
5009
      /* Initialize the CRC table and the decoding table. */
5010
      int i, j;
5011
      unsigned int c;
5012
 
5013
      for (i = 0; i < 256; i++)
5014
        {
5015
          for (c = i << 24, j = 8; j > 0; --j)
5016
            c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
5017
          crc32_table[i] = c;
5018
        }
5019
    }
5020
 
5021
  while (len--)
5022
    {
5023
      crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
5024
      buf++;
5025
    }
5026
  return crc;
5027
}
5028
 
5029
/* compare-sections command
5030
 
5031
   With no arguments, compares each loadable section in the exec bfd
5032
   with the same memory range on the target, and reports mismatches.
5033
   Useful for verifying the image on the target against the exec file.
5034
   Depends on the target understanding the new "qCRC:" request.  */
5035
 
5036
/* FIXME: cagney/1999-10-26: This command should be broken down into a
5037
   target method (target verify memory) and generic version of the
5038
   actual command.  This will allow other high-level code (especially
5039
   generic_load()) to make use of this target functionality. */
5040
 
5041
static void
5042
compare_sections_command (char *args, int from_tty)
5043
{
5044
  struct remote_state *rs = get_remote_state ();
5045
  asection *s;
5046
  unsigned long host_crc, target_crc;
5047
  extern bfd *exec_bfd;
5048
  struct cleanup *old_chain;
5049
  char *tmp;
5050
  char *sectdata;
5051
  const char *sectname;
5052
  char *buf = alloca (rs->remote_packet_size);
5053
  bfd_size_type size;
5054
  bfd_vma lma;
5055
  int matched = 0;
5056
  int mismatched = 0;
5057
 
5058
  if (!exec_bfd)
5059
    error ("command cannot be used without an exec file");
5060
  if (!current_target.to_shortname ||
5061
      strcmp (current_target.to_shortname, "remote") != 0)
5062
    error ("command can only be used with remote target");
5063
 
5064
  for (s = exec_bfd->sections; s; s = s->next)
5065
    {
5066
      if (!(s->flags & SEC_LOAD))
5067
        continue;               /* skip non-loadable section */
5068
 
5069
      size = bfd_get_section_size_before_reloc (s);
5070
      if (size == 0)
5071
        continue;               /* skip zero-length section */
5072
 
5073
      sectname = bfd_get_section_name (exec_bfd, s);
5074
      if (args && strcmp (args, sectname) != 0)
5075
        continue;               /* not the section selected by user */
5076
 
5077
      matched = 1;              /* do this section */
5078
      lma = s->lma;
5079
      /* FIXME: assumes lma can fit into long */
5080
      sprintf (buf, "qCRC:%lx,%lx", (long) lma, (long) size);
5081
      putpkt (buf);
5082
 
5083
      /* be clever; compute the host_crc before waiting for target reply */
5084
      sectdata = xmalloc (size);
5085
      old_chain = make_cleanup (xfree, sectdata);
5086
      bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
5087
      host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
5088
 
5089
      getpkt (buf, (rs->remote_packet_size), 0);
5090
      if (buf[0] == 'E')
5091
        error ("target memory fault, section %s, range 0x%s -- 0x%s",
5092
               sectname, paddr (lma), paddr (lma + size));
5093
      if (buf[0] != 'C')
5094
        error ("remote target does not support this operation");
5095
 
5096
      for (target_crc = 0, tmp = &buf[1]; *tmp; tmp++)
5097
        target_crc = target_crc * 16 + fromhex (*tmp);
5098
 
5099
      printf_filtered ("Section %s, range 0x%s -- 0x%s: ",
5100
                       sectname, paddr (lma), paddr (lma + size));
5101
      if (host_crc == target_crc)
5102
        printf_filtered ("matched.\n");
5103
      else
5104
        {
5105
          printf_filtered ("MIS-MATCHED!\n");
5106
          mismatched++;
5107
        }
5108
 
5109
      do_cleanups (old_chain);
5110
    }
5111
  if (mismatched > 0)
5112
    warning ("One or more sections of the remote executable does not match\n\
5113
the loaded file\n");
5114
  if (args && !matched)
5115
    printf_filtered ("No loaded section named '%s'.\n", args);
5116
}
5117
 
5118
static int
5119
remote_query (int query_type, char *buf, char *outbuf, int *bufsiz)
5120
{
5121
  struct remote_state *rs = get_remote_state ();
5122
  int i;
5123
  char *buf2 = alloca (rs->remote_packet_size);
5124
  char *p2 = &buf2[0];
5125
 
5126
  if (!bufsiz)
5127
    error ("null pointer to remote bufer size specified");
5128
 
5129
  /* minimum outbuf size is (rs->remote_packet_size) - if bufsiz is not large enough let
5130
     the caller know and return what the minimum size is   */
5131
  /* Note: a zero bufsiz can be used to query the minimum buffer size */
5132
  if (*bufsiz < (rs->remote_packet_size))
5133
    {
5134
      *bufsiz = (rs->remote_packet_size);
5135
      return -1;
5136
    }
5137
 
5138
  /* except for querying the minimum buffer size, target must be open */
5139
  if (!remote_desc)
5140
    error ("remote query is only available after target open");
5141
 
5142
  /* we only take uppercase letters as query types, at least for now */
5143
  if ((query_type < 'A') || (query_type > 'Z'))
5144
    error ("invalid remote query type");
5145
 
5146
  if (!buf)
5147
    error ("null remote query specified");
5148
 
5149
  if (!outbuf)
5150
    error ("remote query requires a buffer to receive data");
5151
 
5152
  outbuf[0] = '\0';
5153
 
5154
  *p2++ = 'q';
5155
  *p2++ = query_type;
5156
 
5157
  /* we used one buffer char for the remote protocol q command and another
5158
     for the query type.  As the remote protocol encapsulation uses 4 chars
5159
     plus one extra in case we are debugging (remote_debug),
5160
     we have PBUFZIZ - 7 left to pack the query string */
5161
  i = 0;
5162
  while (buf[i] && (i < ((rs->remote_packet_size) - 8)))
5163
    {
5164
      /* bad caller may have sent forbidden characters */
5165
      if ((!isprint (buf[i])) || (buf[i] == '$') || (buf[i] == '#'))
5166
        error ("illegal characters in query string");
5167
 
5168
      *p2++ = buf[i];
5169
      i++;
5170
    }
5171
  *p2 = buf[i];
5172
 
5173
  if (buf[i])
5174
    error ("query larger than available buffer");
5175
 
5176
  i = putpkt (buf2);
5177
  if (i < 0)
5178
    return i;
5179
 
5180
  getpkt (outbuf, *bufsiz, 0);
5181
 
5182
  return 0;
5183
}
5184
 
5185
static void
5186
remote_rcmd (char *command,
5187
             struct ui_file *outbuf)
5188
{
5189
  struct remote_state *rs = get_remote_state ();
5190
  int i;
5191
  char *buf = alloca (rs->remote_packet_size);
5192
  char *p = buf;
5193
 
5194
  if (!remote_desc)
5195
    error ("remote rcmd is only available after target open");
5196
 
5197
  /* Send a NULL command across as an empty command */
5198
  if (command == NULL)
5199
    command = "";
5200
 
5201
  /* The query prefix */
5202
  strcpy (buf, "qRcmd,");
5203
  p = strchr (buf, '\0');
5204
 
5205
  if ((strlen (buf) + strlen (command) * 2 + 8/*misc*/) > (rs->remote_packet_size))
5206
    error ("\"monitor\" command ``%s'' is too long\n", command);
5207
 
5208
  /* Encode the actual command */
5209
  bin2hex (command, p, 0);
5210
 
5211
  if (putpkt (buf) < 0)
5212
    error ("Communication problem with target\n");
5213
 
5214
  /* get/display the response */
5215
  while (1)
5216
    {
5217
      /* XXX - see also tracepoint.c:remote_get_noisy_reply() */
5218
      buf[0] = '\0';
5219
      getpkt (buf, (rs->remote_packet_size), 0);
5220
      if (buf[0] == '\0')
5221
        error ("Target does not support this command\n");
5222
      if (buf[0] == 'O' && buf[1] != 'K')
5223
        {
5224
          remote_console_output (buf + 1); /* 'O' message from stub */
5225
          continue;
5226
        }
5227
      if (strcmp (buf, "OK") == 0)
5228
        break;
5229
      if (strlen (buf) == 3 && buf[0] == 'E'
5230
          && isdigit (buf[1]) && isdigit (buf[2]))
5231
        {
5232
          error ("Protocol error with Rcmd");
5233
        }
5234
      for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
5235
        {
5236
          char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
5237
          fputc_unfiltered (c, outbuf);
5238
        }
5239
      break;
5240
    }
5241
}
5242
 
5243
static void
5244
packet_command (char *args, int from_tty)
5245
{
5246
  struct remote_state *rs = get_remote_state ();
5247
  char *buf = alloca (rs->remote_packet_size);
5248
 
5249
  if (!remote_desc)
5250
    error ("command can only be used with remote target");
5251
 
5252
  if (!args)
5253
    error ("remote-packet command requires packet text as argument");
5254
 
5255
  puts_filtered ("sending: ");
5256
  print_packet (args);
5257
  puts_filtered ("\n");
5258
  putpkt (args);
5259
 
5260
  getpkt (buf, (rs->remote_packet_size), 0);
5261
  puts_filtered ("received: ");
5262
  print_packet (buf);
5263
  puts_filtered ("\n");
5264
}
5265
 
5266
#if 0
5267
/* --------- UNIT_TEST for THREAD oriented PACKETS ------------------------- */
5268
 
5269
static void display_thread_info (struct gdb_ext_thread_info *info);
5270
 
5271
static void threadset_test_cmd (char *cmd, int tty);
5272
 
5273
static void threadalive_test (char *cmd, int tty);
5274
 
5275
static void threadlist_test_cmd (char *cmd, int tty);
5276
 
5277
int get_and_display_threadinfo (threadref * ref);
5278
 
5279
static void threadinfo_test_cmd (char *cmd, int tty);
5280
 
5281
static int thread_display_step (threadref * ref, void *context);
5282
 
5283
static void threadlist_update_test_cmd (char *cmd, int tty);
5284
 
5285
static void init_remote_threadtests (void);
5286
 
5287
#define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid */
5288
 
5289
static void
5290
threadset_test_cmd (char *cmd, int tty)
5291
{
5292
  int sample_thread = SAMPLE_THREAD;
5293
 
5294
  printf_filtered ("Remote threadset test\n");
5295
  set_thread (sample_thread, 1);
5296
}
5297
 
5298
 
5299
static void
5300
threadalive_test (char *cmd, int tty)
5301
{
5302
  int sample_thread = SAMPLE_THREAD;
5303
 
5304
  if (remote_thread_alive (pid_to_ptid (sample_thread)))
5305
    printf_filtered ("PASS: Thread alive test\n");
5306
  else
5307
    printf_filtered ("FAIL: Thread alive test\n");
5308
}
5309
 
5310
void output_threadid (char *title, threadref * ref);
5311
 
5312
void
5313
output_threadid (char *title, threadref *ref)
5314
{
5315
  char hexid[20];
5316
 
5317
  pack_threadid (&hexid[0], ref);        /* Convert threead id into hex */
5318
  hexid[16] = 0;
5319
  printf_filtered ("%s  %s\n", title, (&hexid[0]));
5320
}
5321
 
5322
static void
5323
threadlist_test_cmd (char *cmd, int tty)
5324
{
5325
  int startflag = 1;
5326
  threadref nextthread;
5327
  int done, result_count;
5328
  threadref threadlist[3];
5329
 
5330
  printf_filtered ("Remote Threadlist test\n");
5331
  if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
5332
                              &result_count, &threadlist[0]))
5333
    printf_filtered ("FAIL: threadlist test\n");
5334
  else
5335
    {
5336
      threadref *scan = threadlist;
5337
      threadref *limit = scan + result_count;
5338
 
5339
      while (scan < limit)
5340
        output_threadid (" thread ", scan++);
5341
    }
5342
}
5343
 
5344
void
5345
display_thread_info (struct gdb_ext_thread_info *info)
5346
{
5347
  output_threadid ("Threadid: ", &info->threadid);
5348
  printf_filtered ("Name: %s\n ", info->shortname);
5349
  printf_filtered ("State: %s\n", info->display);
5350
  printf_filtered ("other: %s\n\n", info->more_display);
5351
}
5352
 
5353
int
5354
get_and_display_threadinfo (threadref *ref)
5355
{
5356
  int result;
5357
  int set;
5358
  struct gdb_ext_thread_info threadinfo;
5359
 
5360
  set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
5361
    | TAG_MOREDISPLAY | TAG_DISPLAY;
5362
  if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
5363
    display_thread_info (&threadinfo);
5364
  return result;
5365
}
5366
 
5367
static void
5368
threadinfo_test_cmd (char *cmd, int tty)
5369
{
5370
  int athread = SAMPLE_THREAD;
5371
  threadref thread;
5372
  int set;
5373
 
5374
  int_to_threadref (&thread, athread);
5375
  printf_filtered ("Remote Threadinfo test\n");
5376
  if (!get_and_display_threadinfo (&thread))
5377
    printf_filtered ("FAIL cannot get thread info\n");
5378
}
5379
 
5380
static int
5381
thread_display_step (threadref *ref, void *context)
5382
{
5383
  /* output_threadid(" threadstep ",ref); *//* simple test */
5384
  return get_and_display_threadinfo (ref);
5385
}
5386
 
5387
static void
5388
threadlist_update_test_cmd (char *cmd, int tty)
5389
{
5390
  printf_filtered ("Remote Threadlist update test\n");
5391
  remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
5392
}
5393
 
5394
static void
5395
init_remote_threadtests (void)
5396
{
5397
  add_com ("tlist", class_obscure, threadlist_test_cmd,
5398
     "Fetch and print the remote list of thread identifiers, one pkt only");
5399
  add_com ("tinfo", class_obscure, threadinfo_test_cmd,
5400
           "Fetch and display info about one thread");
5401
  add_com ("tset", class_obscure, threadset_test_cmd,
5402
           "Test setting to a different thread");
5403
  add_com ("tupd", class_obscure, threadlist_update_test_cmd,
5404
           "Iterate through updating all remote thread info");
5405
  add_com ("talive", class_obscure, threadalive_test,
5406
           " Remote thread alive test ");
5407
}
5408
 
5409
#endif /* 0 */
5410
 
5411
/* Convert a thread ID to a string.  Returns the string in a static
5412
   buffer.  */
5413
 
5414
static char *
5415
remote_pid_to_str (ptid_t ptid)
5416
{
5417
  static char buf[30];
5418
 
5419
  sprintf (buf, "Thread %d", PIDGET (ptid));
5420
  return buf;
5421
}
5422
 
5423
static void
5424
init_remote_ops (void)
5425
{
5426
  remote_ops.to_shortname = "remote";
5427
  remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
5428
  remote_ops.to_doc =
5429
    "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5430
Specify the serial device it is connected to\n\
5431
(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
5432
  remote_ops.to_open = remote_open;
5433
  remote_ops.to_close = remote_close;
5434
  remote_ops.to_detach = remote_detach;
5435
  remote_ops.to_resume = remote_resume;
5436
  remote_ops.to_wait = remote_wait;
5437
  remote_ops.to_fetch_registers = remote_fetch_registers;
5438
  remote_ops.to_store_registers = remote_store_registers;
5439
  remote_ops.to_prepare_to_store = remote_prepare_to_store;
5440
  remote_ops.to_xfer_memory = remote_xfer_memory;
5441
  remote_ops.to_files_info = remote_files_info;
5442
  remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
5443
  remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
5444
  remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
5445
  remote_ops.to_stopped_data_address = remote_stopped_data_address;
5446
  remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
5447
  remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
5448
  remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
5449
  remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
5450
  remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
5451
  remote_ops.to_kill = remote_kill;
5452
  remote_ops.to_load = generic_load;
5453
  remote_ops.to_mourn_inferior = remote_mourn;
5454
  remote_ops.to_thread_alive = remote_thread_alive;
5455
  remote_ops.to_find_new_threads = remote_threads_info;
5456
  remote_ops.to_pid_to_str = remote_pid_to_str;
5457
  remote_ops.to_extra_thread_info = remote_threads_extra_info;
5458
  remote_ops.to_stop = remote_stop;
5459
  remote_ops.to_query = remote_query;
5460
  remote_ops.to_rcmd = remote_rcmd;
5461
  remote_ops.to_stratum = process_stratum;
5462
  remote_ops.to_has_all_memory = 1;
5463
  remote_ops.to_has_memory = 1;
5464
  remote_ops.to_has_stack = 1;
5465
  remote_ops.to_has_registers = 1;
5466
  remote_ops.to_has_execution = 1;
5467
  remote_ops.to_has_thread_control = tc_schedlock;      /* can lock scheduler */
5468
  remote_ops.to_magic = OPS_MAGIC;
5469
}
5470
 
5471
/* Set up the extended remote vector by making a copy of the standard
5472
   remote vector and adding to it.  */
5473
 
5474
static void
5475
init_extended_remote_ops (void)
5476
{
5477
  extended_remote_ops = remote_ops;
5478
 
5479
  extended_remote_ops.to_shortname = "extended-remote";
5480
  extended_remote_ops.to_longname =
5481
    "Extended remote serial target in gdb-specific protocol";
5482
  extended_remote_ops.to_doc =
5483
    "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5484
Specify the serial device it is connected to (e.g. /dev/ttya).",
5485
    extended_remote_ops.to_open = extended_remote_open;
5486
  extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
5487
  extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
5488
}
5489
 
5490
/*
5491
 * Command: info remote-process
5492
 *
5493
 * This implements Cisco's version of the "info proc" command.
5494
 *
5495
 * This query allows the target stub to return an arbitrary string
5496
 * (or strings) giving arbitrary information about the target process.
5497
 * This is optional; the target stub isn't required to implement it.
5498
 *
5499
 * Syntax: qfProcessInfo        request first string
5500
 *         qsProcessInfo        request subsequent string
5501
 * reply:  'O'<hex-encoded-string>
5502
 *         'l'                  last reply (empty)
5503
 */
5504
 
5505
static void
5506
remote_info_process (char *args, int from_tty)
5507
{
5508
  struct remote_state *rs = get_remote_state ();
5509
  char *buf = alloca (rs->remote_packet_size);
5510
 
5511
  if (remote_desc == 0)
5512
    error ("Command can only be used when connected to the remote target.");
5513
 
5514
  putpkt ("qfProcessInfo");
5515
  getpkt (buf, (rs->remote_packet_size), 0);
5516
  if (buf[0] == 0)
5517
    return;                     /* Silently: target does not support this feature. */
5518
 
5519
  if (buf[0] == 'E')
5520
    error ("info proc: target error.");
5521
 
5522
  while (buf[0] == 'O')          /* Capitol-O packet */
5523
    {
5524
      remote_console_output (&buf[1]);
5525
      putpkt ("qsProcessInfo");
5526
      getpkt (buf, (rs->remote_packet_size), 0);
5527
    }
5528
}
5529
 
5530
/*
5531
 * Target Cisco
5532
 */
5533
 
5534
static void
5535
remote_cisco_open (char *name, int from_tty)
5536
{
5537
  int ex;
5538
  if (name == 0)
5539
    error ("To open a remote debug connection, you need to specify what \n"
5540
           "device is attached to the remote system (e.g. host:port).");
5541
 
5542
  /* See FIXME above */
5543
  wait_forever_enabled_p = 1;
5544
 
5545
  target_preopen (from_tty);
5546
 
5547
  unpush_target (&remote_cisco_ops);
5548
 
5549
  remote_desc = remote_serial_open (name);
5550
  if (!remote_desc)
5551
    perror_with_name (name);
5552
 
5553
  /*
5554
   * If a baud rate was specified on the gdb  command line it will
5555
   * be greater than the initial value of -1.  If it is, use it otherwise
5556
   * default to 9600
5557
   */
5558
 
5559
  baud_rate = (baud_rate > 0) ? baud_rate : 9600;
5560
  if (serial_setbaudrate (remote_desc, baud_rate))
5561
    {
5562
      serial_close (remote_desc);
5563
      perror_with_name (name);
5564
    }
5565
 
5566
  serial_raw (remote_desc);
5567
 
5568
  /* If there is something sitting in the buffer we might take it as a
5569
     response to a command, which would be bad.  */
5570
  serial_flush_input (remote_desc);
5571
 
5572
  if (from_tty)
5573
    {
5574
      puts_filtered ("Remote debugging using ");
5575
      puts_filtered (name);
5576
      puts_filtered ("\n");
5577
    }
5578
 
5579
  remote_cisco_mode = 1;
5580
 
5581
  push_target (&remote_cisco_ops);      /* Switch to using cisco target now */
5582
 
5583
  init_all_packet_configs ();
5584
 
5585
  general_thread = -2;
5586
  continue_thread = -2;
5587
 
5588
  /* Probe for ability to use "ThreadInfo" query, as required.  */
5589
  use_threadinfo_query = 1;
5590
  use_threadextra_query = 1;
5591
 
5592
  /* Without this, some commands which require an active target (such
5593
     as kill) won't work.  This variable serves (at least) double duty
5594
     as both the pid of the target process (if it has such), and as a
5595
     flag indicating that a target is active.  These functions should
5596
     be split out into seperate variables, especially since GDB will
5597
     someday have a notion of debugging several processes.  */
5598
  inferior_ptid = pid_to_ptid (MAGIC_NULL_PID);
5599
 
5600
  /* Start the remote connection; if error, discard this target.  See
5601
     the comments in remote_open_1() for further details such as the
5602
     need to re-throw the exception.  */
5603
  ex = catch_exceptions (uiout,
5604
                         remote_start_remote_dummy, NULL,
5605
                         "Couldn't establish connection to remote"
5606
                         " target\n",
5607
                         RETURN_MASK_ALL);
5608
  if (ex < 0)
5609
    {
5610
      pop_target ();
5611
      throw_exception (ex);
5612
    }
5613
}
5614
 
5615
static void
5616
remote_cisco_close (int quitting)
5617
{
5618
  remote_cisco_mode = 0;
5619
  remote_close (quitting);
5620
}
5621
 
5622
static void
5623
remote_cisco_mourn (void)
5624
{
5625
  remote_mourn_1 (&remote_cisco_ops);
5626
}
5627
 
5628
enum
5629
{
5630
  READ_MORE,
5631
  FATAL_ERROR,
5632
  ENTER_DEBUG,
5633
  DISCONNECT_TELNET
5634
}
5635
minitelnet_return;
5636
 
5637
/* Shared between readsocket() and readtty().  The size is arbitrary,
5638
   however all targets are known to support a 400 character packet.  */
5639
static char tty_input[400];
5640
 
5641
static int escape_count;
5642
static int echo_check;
5643
extern int quit_flag;
5644
 
5645
static int
5646
readsocket (void)
5647
{
5648
  int data;
5649
 
5650
  /* Loop until the socket doesn't have any more data */
5651
 
5652
  while ((data = readchar (0)) >= 0)
5653
    {
5654
      /* Check for the escape sequence */
5655
      if (data == '|')
5656
        {
5657
          /* If this is the fourth escape, get out */
5658
          if (++escape_count == 4)
5659
            {
5660
              return ENTER_DEBUG;
5661
            }
5662
          else
5663
            {                   /* This is a '|', but not the fourth in a row.
5664
                                   Continue without echoing it.  If it isn't actually
5665
                                   one of four in a row, it'll be echoed later.  */
5666
              continue;
5667
            }
5668
        }
5669
      else
5670
        /* Not a '|' */
5671
        {
5672
          /* Ensure any pending '|'s are flushed.  */
5673
 
5674
          for (; escape_count > 0; escape_count--)
5675
            putchar ('|');
5676
        }
5677
 
5678
      if (data == '\r')         /* If this is a return character, */
5679
        continue;               /*  - just supress it. */
5680
 
5681
      if (echo_check != -1)     /* Check for echo of user input.  */
5682
        {
5683
          if (tty_input[echo_check] == data)
5684
            {
5685
              gdb_assert (echo_check <= sizeof (tty_input));
5686
              echo_check++;     /* Character matched user input: */
5687
              continue;         /* Continue without echoing it.  */
5688
            }
5689
          else if ((data == '\n') && (tty_input[echo_check] == '\r'))
5690
            {                   /* End of the line (and of echo checking).  */
5691
              echo_check = -1;  /* No more echo supression */
5692
              continue;         /* Continue without echoing.  */
5693
            }
5694
          else
5695
            {                   /* Failed check for echo of user input.
5696
                                   We now have some suppressed output to flush!  */
5697
              int j;
5698
 
5699
              for (j = 0; j < echo_check; j++)
5700
                putchar (tty_input[j]);
5701
              echo_check = -1;
5702
            }
5703
        }
5704
      putchar (data);           /* Default case: output the char.  */
5705
    }
5706
 
5707
  if (data == SERIAL_TIMEOUT)   /* Timeout returned from readchar.  */
5708
    return READ_MORE;           /* Try to read some more */
5709
  else
5710
    return FATAL_ERROR;         /* Trouble, bail out */
5711
}
5712
 
5713
static int
5714
readtty (void)
5715
{
5716
  int tty_bytecount;
5717
 
5718
  /* First, read a buffer full from the terminal */
5719
  tty_bytecount = read (fileno (stdin), tty_input, sizeof (tty_input) - 1);
5720
  if (tty_bytecount == -1)
5721
    {
5722
      perror ("readtty: read failed");
5723
      return FATAL_ERROR;
5724
    }
5725
 
5726
  /* Remove a quoted newline.  */
5727
  if (tty_input[tty_bytecount - 1] == '\n' &&
5728
      tty_input[tty_bytecount - 2] == '\\')     /* line ending in backslash */
5729
    {
5730
      tty_input[--tty_bytecount] = 0;    /* remove newline */
5731
      tty_input[--tty_bytecount] = 0;    /* remove backslash */
5732
    }
5733
 
5734
  /* Turn trailing newlines into returns */
5735
  if (tty_input[tty_bytecount - 1] == '\n')
5736
    tty_input[tty_bytecount - 1] = '\r';
5737
 
5738
  /* If the line consists of a ~, enter debugging mode.  */
5739
  if ((tty_input[0] == '~') && (tty_bytecount == 2))
5740
    return ENTER_DEBUG;
5741
 
5742
  /* Make this a zero terminated string and write it out */
5743
  tty_input[tty_bytecount] = 0;
5744
  if (serial_write (remote_desc, tty_input, tty_bytecount))
5745
    {
5746
      perror_with_name ("readtty: write failed");
5747
      return FATAL_ERROR;
5748
    }
5749
 
5750
  return READ_MORE;
5751
}
5752
 
5753
static int
5754
minitelnet (void)
5755
{
5756
  fd_set input;                 /* file descriptors for select */
5757
  int tablesize;                /* max number of FDs for select */
5758
  int status;
5759
  int quit_count = 0;
5760
 
5761
  extern int escape_count;      /* global shared by readsocket */
5762
  extern int echo_check;        /* ditto */
5763
 
5764
  escape_count = 0;
5765
  echo_check = -1;
5766
 
5767
  tablesize = 8 * sizeof (input);
5768
 
5769
  for (;;)
5770
    {
5771
      /* Check for anything from our socket - doesn't block. Note that
5772
         this must be done *before* the select as there may be
5773
         buffered I/O waiting to be processed.  */
5774
 
5775
      if ((status = readsocket ()) == FATAL_ERROR)
5776
        {
5777
          error ("Debugging terminated by communications error");
5778
        }
5779
      else if (status != READ_MORE)
5780
        {
5781
          return (status);
5782
        }
5783
 
5784
      fflush (stdout);          /* Flush output before blocking */
5785
 
5786
      /* Now block on more socket input or TTY input */
5787
 
5788
      FD_ZERO (&input);
5789
      FD_SET (fileno (stdin), &input);
5790
      FD_SET (deprecated_serial_fd (remote_desc), &input);
5791
 
5792
      status = select (tablesize, &input, 0, 0, 0);
5793
      if ((status == -1) && (errno != EINTR))
5794
        {
5795
          error ("Communications error on select %d", errno);
5796
        }
5797
 
5798
      /* Handle Control-C typed */
5799
 
5800
      if (quit_flag)
5801
        {
5802
          if ((++quit_count) == 2)
5803
            {
5804
              if (query ("Interrupt GDB? "))
5805
                {
5806
                  printf_filtered ("Interrupted by user.\n");
5807
                  throw_exception (RETURN_QUIT);
5808
                }
5809
              quit_count = 0;
5810
            }
5811
          quit_flag = 0;
5812
 
5813
          if (remote_break)
5814
            serial_send_break (remote_desc);
5815
          else
5816
            serial_write (remote_desc, "\003", 1);
5817
 
5818
          continue;
5819
        }
5820
 
5821
      /* Handle console input */
5822
 
5823
      if (FD_ISSET (fileno (stdin), &input))
5824
        {
5825
          quit_count = 0;
5826
          echo_check = 0;
5827
          status = readtty ();
5828
          if (status == READ_MORE)
5829
            continue;
5830
 
5831
          return status;        /* telnet session ended */
5832
        }
5833
    }
5834
}
5835
 
5836
static ptid_t
5837
remote_cisco_wait (ptid_t ptid, struct target_waitstatus *status)
5838
{
5839
  if (minitelnet () != ENTER_DEBUG)
5840
    {
5841
      error ("Debugging session terminated by protocol error");
5842
    }
5843
  putpkt ("?");
5844
  return remote_wait (ptid, status);
5845
}
5846
 
5847
static void
5848
init_remote_cisco_ops (void)
5849
{
5850
  remote_cisco_ops.to_shortname = "cisco";
5851
  remote_cisco_ops.to_longname = "Remote serial target in cisco-specific protocol";
5852
  remote_cisco_ops.to_doc =
5853
    "Use a remote machine via TCP, using a cisco-specific protocol.\n\
5854
Specify the serial device it is connected to (e.g. host:2020).";
5855
  remote_cisco_ops.to_open = remote_cisco_open;
5856
  remote_cisco_ops.to_close = remote_cisco_close;
5857
  remote_cisco_ops.to_detach = remote_detach;
5858
  remote_cisco_ops.to_resume = remote_resume;
5859
  remote_cisco_ops.to_wait = remote_cisco_wait;
5860
  remote_cisco_ops.to_fetch_registers = remote_fetch_registers;
5861
  remote_cisco_ops.to_store_registers = remote_store_registers;
5862
  remote_cisco_ops.to_prepare_to_store = remote_prepare_to_store;
5863
  remote_cisco_ops.to_xfer_memory = remote_xfer_memory;
5864
  remote_cisco_ops.to_files_info = remote_files_info;
5865
  remote_cisco_ops.to_insert_breakpoint = remote_insert_breakpoint;
5866
  remote_cisco_ops.to_remove_breakpoint = remote_remove_breakpoint;
5867
  remote_cisco_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
5868
  remote_cisco_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
5869
  remote_cisco_ops.to_insert_watchpoint = remote_insert_watchpoint;
5870
  remote_cisco_ops.to_remove_watchpoint = remote_remove_watchpoint;
5871
  remote_cisco_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
5872
  remote_cisco_ops.to_stopped_data_address = remote_stopped_data_address;
5873
  remote_cisco_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
5874
  remote_cisco_ops.to_kill = remote_kill;
5875
  remote_cisco_ops.to_load = generic_load;
5876
  remote_cisco_ops.to_mourn_inferior = remote_cisco_mourn;
5877
  remote_cisco_ops.to_thread_alive = remote_thread_alive;
5878
  remote_cisco_ops.to_find_new_threads = remote_threads_info;
5879
  remote_cisco_ops.to_pid_to_str = remote_pid_to_str;
5880
  remote_cisco_ops.to_extra_thread_info = remote_threads_extra_info;
5881
  remote_cisco_ops.to_stratum = process_stratum;
5882
  remote_cisco_ops.to_has_all_memory = 1;
5883
  remote_cisco_ops.to_has_memory = 1;
5884
  remote_cisco_ops.to_has_stack = 1;
5885
  remote_cisco_ops.to_has_registers = 1;
5886
  remote_cisco_ops.to_has_execution = 1;
5887
  remote_cisco_ops.to_magic = OPS_MAGIC;
5888
}
5889
 
5890
static int
5891
remote_can_async_p (void)
5892
{
5893
  /* We're async whenever the serial device is. */
5894
  return (current_target.to_async_mask_value) && serial_can_async_p (remote_desc);
5895
}
5896
 
5897
static int
5898
remote_is_async_p (void)
5899
{
5900
  /* We're async whenever the serial device is. */
5901
  return (current_target.to_async_mask_value) && serial_is_async_p (remote_desc);
5902
}
5903
 
5904
/* Pass the SERIAL event on and up to the client.  One day this code
5905
   will be able to delay notifying the client of an event until the
5906
   point where an entire packet has been received. */
5907
 
5908
static void (*async_client_callback) (enum inferior_event_type event_type, void *context);
5909
static void *async_client_context;
5910
static serial_event_ftype remote_async_serial_handler;
5911
 
5912
static void
5913
remote_async_serial_handler (struct serial *scb, void *context)
5914
{
5915
  /* Don't propogate error information up to the client.  Instead let
5916
     the client find out about the error by querying the target.  */
5917
  async_client_callback (INF_REG_EVENT, async_client_context);
5918
}
5919
 
5920
static void
5921
remote_async (void (*callback) (enum inferior_event_type event_type, void *context), void *context)
5922
{
5923
  if (current_target.to_async_mask_value == 0)
5924
    internal_error (__FILE__, __LINE__,
5925
                    "Calling remote_async when async is masked");
5926
 
5927
  if (callback != NULL)
5928
    {
5929
      serial_async (remote_desc, remote_async_serial_handler, NULL);
5930
      async_client_callback = callback;
5931
      async_client_context = context;
5932
    }
5933
  else
5934
    serial_async (remote_desc, NULL, NULL);
5935
}
5936
 
5937
/* Target async and target extended-async.
5938
 
5939
   This are temporary targets, until it is all tested.  Eventually
5940
   async support will be incorporated int the usual 'remote'
5941
   target. */
5942
 
5943
static void
5944
init_remote_async_ops (void)
5945
{
5946
  remote_async_ops.to_shortname = "async";
5947
  remote_async_ops.to_longname = "Remote serial target in async version of the gdb-specific protocol";
5948
  remote_async_ops.to_doc =
5949
    "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
5950
Specify the serial device it is connected to (e.g. /dev/ttya).";
5951
  remote_async_ops.to_open = remote_async_open;
5952
  remote_async_ops.to_close = remote_close;
5953
  remote_async_ops.to_detach = remote_async_detach;
5954
  remote_async_ops.to_resume = remote_async_resume;
5955
  remote_async_ops.to_wait = remote_async_wait;
5956
  remote_async_ops.to_fetch_registers = remote_fetch_registers;
5957
  remote_async_ops.to_store_registers = remote_store_registers;
5958
  remote_async_ops.to_prepare_to_store = remote_prepare_to_store;
5959
  remote_async_ops.to_xfer_memory = remote_xfer_memory;
5960
  remote_async_ops.to_files_info = remote_files_info;
5961
  remote_async_ops.to_insert_breakpoint = remote_insert_breakpoint;
5962
  remote_async_ops.to_remove_breakpoint = remote_remove_breakpoint;
5963
  remote_async_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
5964
  remote_async_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
5965
  remote_async_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
5966
  remote_async_ops.to_insert_watchpoint = remote_insert_watchpoint;
5967
  remote_async_ops.to_remove_watchpoint = remote_remove_watchpoint;
5968
  remote_async_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
5969
  remote_async_ops.to_stopped_data_address = remote_stopped_data_address;
5970
  remote_async_ops.to_terminal_inferior = remote_async_terminal_inferior;
5971
  remote_async_ops.to_terminal_ours = remote_async_terminal_ours;
5972
  remote_async_ops.to_kill = remote_async_kill;
5973
  remote_async_ops.to_load = generic_load;
5974
  remote_async_ops.to_mourn_inferior = remote_async_mourn;
5975
  remote_async_ops.to_thread_alive = remote_thread_alive;
5976
  remote_async_ops.to_find_new_threads = remote_threads_info;
5977
  remote_async_ops.to_pid_to_str = remote_pid_to_str;
5978
  remote_async_ops.to_extra_thread_info = remote_threads_extra_info;
5979
  remote_async_ops.to_stop = remote_stop;
5980
  remote_async_ops.to_query = remote_query;
5981
  remote_async_ops.to_rcmd = remote_rcmd;
5982
  remote_async_ops.to_stratum = process_stratum;
5983
  remote_async_ops.to_has_all_memory = 1;
5984
  remote_async_ops.to_has_memory = 1;
5985
  remote_async_ops.to_has_stack = 1;
5986
  remote_async_ops.to_has_registers = 1;
5987
  remote_async_ops.to_has_execution = 1;
5988
  remote_async_ops.to_has_thread_control = tc_schedlock;        /* can lock scheduler */
5989
  remote_async_ops.to_can_async_p = remote_can_async_p;
5990
  remote_async_ops.to_is_async_p = remote_is_async_p;
5991
  remote_async_ops.to_async = remote_async;
5992
  remote_async_ops.to_async_mask_value = 1;
5993
  remote_async_ops.to_magic = OPS_MAGIC;
5994
}
5995
 
5996
/* Set up the async extended remote vector by making a copy of the standard
5997
   remote vector and adding to it.  */
5998
 
5999
static void
6000
init_extended_async_remote_ops (void)
6001
{
6002
  extended_async_remote_ops = remote_async_ops;
6003
 
6004
  extended_async_remote_ops.to_shortname = "extended-async";
6005
  extended_async_remote_ops.to_longname =
6006
    "Extended remote serial target in async gdb-specific protocol";
6007
  extended_async_remote_ops.to_doc =
6008
    "Use a remote computer via a serial line, using an async gdb-specific protocol.\n\
6009
Specify the serial device it is connected to (e.g. /dev/ttya).",
6010
    extended_async_remote_ops.to_open = extended_remote_async_open;
6011
  extended_async_remote_ops.to_create_inferior = extended_remote_async_create_inferior;
6012
  extended_async_remote_ops.to_mourn_inferior = extended_remote_mourn;
6013
}
6014
 
6015
static void
6016
set_remote_cmd (char *args, int from_tty)
6017
{
6018
}
6019
 
6020
static void
6021
show_remote_cmd (char *args, int from_tty)
6022
{
6023
  /* FIXME: cagney/2002-06-15: This function should iterate over
6024
     remote_show_cmdlist for a list of sub commands to show.  */
6025
  show_remote_protocol_Z_packet_cmd (args, from_tty, NULL);
6026
  show_remote_protocol_e_packet_cmd (args, from_tty, NULL);
6027
  show_remote_protocol_E_packet_cmd (args, from_tty, NULL);
6028
  show_remote_protocol_P_packet_cmd (args, from_tty, NULL);
6029
  show_remote_protocol_qSymbol_packet_cmd (args, from_tty, NULL);
6030
  show_remote_protocol_binary_download_cmd (args, from_tty, NULL);
6031
}
6032
 
6033
static void
6034
build_remote_gdbarch_data (void)
6035
{
6036
  remote_address_size = TARGET_ADDR_BIT;
6037
}
6038
 
6039
/* Saved pointer to previous owner of the new_objfile event. */
6040
static void (*remote_new_objfile_chain) (struct objfile *);
6041
 
6042
/* Function to be called whenever a new objfile (shlib) is detected. */
6043
static void
6044
remote_new_objfile (struct objfile *objfile)
6045
{
6046
  if (remote_desc != 0)          /* Have a remote connection */
6047
    {
6048
      remote_check_symbols (objfile);
6049
    }
6050
  /* Call predecessor on chain, if any. */
6051
  if (remote_new_objfile_chain != 0 &&
6052
      remote_desc == 0)
6053
    remote_new_objfile_chain (objfile);
6054
}
6055
 
6056
void
6057
_initialize_remote (void)
6058
{
6059
  static struct cmd_list_element *remote_set_cmdlist;
6060
  static struct cmd_list_element *remote_show_cmdlist;
6061
  struct cmd_list_element *tmpcmd;
6062
 
6063
  /* architecture specific data */
6064
  remote_gdbarch_data_handle = register_gdbarch_data (init_remote_state,
6065
                                                      free_remote_state);
6066
 
6067
  /* Old tacky stuff.  NOTE: This comes after the remote protocol so
6068
     that the remote protocol has been initialized.  */
6069
  register_gdbarch_swap (&remote_address_size,
6070
                         sizeof (&remote_address_size), NULL);
6071
  register_gdbarch_swap (NULL, 0, build_remote_gdbarch_data);
6072
 
6073
  init_remote_ops ();
6074
  add_target (&remote_ops);
6075
 
6076
  init_extended_remote_ops ();
6077
  add_target (&extended_remote_ops);
6078
 
6079
  init_remote_async_ops ();
6080
  add_target (&remote_async_ops);
6081
 
6082
  init_extended_async_remote_ops ();
6083
  add_target (&extended_async_remote_ops);
6084
 
6085
  init_remote_cisco_ops ();
6086
  add_target (&remote_cisco_ops);
6087
 
6088
  /* Hook into new objfile notification.  */
6089
  remote_new_objfile_chain = target_new_objfile_hook;
6090
  target_new_objfile_hook  = remote_new_objfile;
6091
 
6092
#if 0
6093
  init_remote_threadtests ();
6094
#endif
6095
 
6096
  /* set/show remote ... */
6097
 
6098
  add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, "\
6099
Remote protocol specific variables\n\
6100
Configure various remote-protocol specific variables such as\n\
6101
the packets being used",
6102
                  &remote_set_cmdlist, "set remote ",
6103
                  0/*allow-unknown*/, &setlist);
6104
  add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, "\
6105
Remote protocol specific variables\n\
6106
Configure various remote-protocol specific variables such as\n\
6107
the packets being used",
6108
                  &remote_show_cmdlist, "show remote ",
6109
                  0/*allow-unknown*/, &showlist);
6110
 
6111
  add_cmd ("compare-sections", class_obscure, compare_sections_command,
6112
           "Compare section data on target to the exec file.\n\
6113
Argument is a single section name (default: all loaded sections).",
6114
           &cmdlist);
6115
 
6116
  add_cmd ("packet", class_maintenance, packet_command,
6117
           "Send an arbitrary packet to a remote target.\n\
6118
   maintenance packet TEXT\n\
6119
If GDB is talking to an inferior via the GDB serial protocol, then\n\
6120
this command sends the string TEXT to the inferior, and displays the\n\
6121
response packet.  GDB supplies the initial `$' character, and the\n\
6122
terminating `#' character and checksum.",
6123
           &maintenancelist);
6124
 
6125
  add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break,
6126
                           "Set whether to send break if interrupted.\n",
6127
                           "Show whether to send break if interrupted.\n",
6128
                           NULL, NULL,
6129
                           &setlist, &showlist);
6130
 
6131
  /* Install commands for configuring memory read/write packets. */
6132
 
6133
  add_cmd ("remotewritesize", no_class, set_memory_write_packet_size,
6134
           "Set the maximum number of bytes per memory write packet (deprecated).\n",
6135
           &setlist);
6136
  add_cmd ("remotewritesize", no_class, show_memory_write_packet_size,
6137
           "Show the maximum number of bytes per memory write packet (deprecated).\n",
6138
           &showlist);
6139
  add_cmd ("memory-write-packet-size", no_class,
6140
           set_memory_write_packet_size,
6141
           "Set the maximum number of bytes per memory-write packet.\n"
6142
           "Specify the number of bytes in a packet or 0 (zero) for the\n"
6143
           "default packet size.  The actual limit is further reduced\n"
6144
           "dependent on the target.  Specify ``fixed'' to disable the\n"
6145
           "further restriction and ``limit'' to enable that restriction\n",
6146
           &remote_set_cmdlist);
6147
  add_cmd ("memory-read-packet-size", no_class,
6148
           set_memory_read_packet_size,
6149
           "Set the maximum number of bytes per memory-read packet.\n"
6150
           "Specify the number of bytes in a packet or 0 (zero) for the\n"
6151
           "default packet size.  The actual limit is further reduced\n"
6152
           "dependent on the target.  Specify ``fixed'' to disable the\n"
6153
           "further restriction and ``limit'' to enable that restriction\n",
6154
           &remote_set_cmdlist);
6155
  add_cmd ("memory-write-packet-size", no_class,
6156
           show_memory_write_packet_size,
6157
           "Show the maximum number of bytes per memory-write packet.\n",
6158
           &remote_show_cmdlist);
6159
  add_cmd ("memory-read-packet-size", no_class,
6160
           show_memory_read_packet_size,
6161
           "Show the maximum number of bytes per memory-read packet.\n",
6162
           &remote_show_cmdlist);
6163
 
6164
  add_show_from_set
6165
    (add_set_cmd ("remoteaddresssize", class_obscure,
6166
                  var_integer, (char *) &remote_address_size,
6167
                  "Set the maximum size of the address (in bits) \
6168
in a memory packet.\n",
6169
                  &setlist),
6170
     &showlist);
6171
 
6172
  add_packet_config_cmd (&remote_protocol_binary_download,
6173
                         "X", "binary-download",
6174
                         set_remote_protocol_binary_download_cmd,
6175
                         show_remote_protocol_binary_download_cmd,
6176
                         &remote_set_cmdlist, &remote_show_cmdlist,
6177
                         1);
6178
#if 0
6179
  /* XXXX - should ``set remotebinarydownload'' be retained for
6180
     compatibility. */
6181
  add_show_from_set
6182
    (add_set_cmd ("remotebinarydownload", no_class,
6183
                  var_boolean, (char *) &remote_binary_download,
6184
                  "Set binary downloads.\n", &setlist),
6185
     &showlist);
6186
#endif
6187
 
6188
  add_info ("remote-process", remote_info_process,
6189
            "Query the remote system for process info.");
6190
 
6191
  add_packet_config_cmd (&remote_protocol_qSymbol,
6192
                         "qSymbol", "symbol-lookup",
6193
                         set_remote_protocol_qSymbol_packet_cmd,
6194
                         show_remote_protocol_qSymbol_packet_cmd,
6195
                         &remote_set_cmdlist, &remote_show_cmdlist,
6196
                         0);
6197
 
6198
  add_packet_config_cmd (&remote_protocol_e,
6199
                         "e", "step-over-range",
6200
                         set_remote_protocol_e_packet_cmd,
6201
                         show_remote_protocol_e_packet_cmd,
6202
                         &remote_set_cmdlist, &remote_show_cmdlist,
6203
                         0);
6204
  /* Disable by default.  The ``e'' packet has nasty interactions with
6205
     the threading code - it relies on global state.  */
6206
  remote_protocol_e.detect = AUTO_BOOLEAN_FALSE;
6207
  update_packet_config (&remote_protocol_e);
6208
 
6209
  add_packet_config_cmd (&remote_protocol_E,
6210
                         "E", "step-over-range-w-signal",
6211
                         set_remote_protocol_E_packet_cmd,
6212
                         show_remote_protocol_E_packet_cmd,
6213
                         &remote_set_cmdlist, &remote_show_cmdlist,
6214
                         0);
6215
  /* Disable by default.  The ``e'' packet has nasty interactions with
6216
     the threading code - it relies on global state.  */
6217
  remote_protocol_E.detect = AUTO_BOOLEAN_FALSE;
6218
  update_packet_config (&remote_protocol_E);
6219
 
6220
  add_packet_config_cmd (&remote_protocol_P,
6221
                         "P", "set-register",
6222
                         set_remote_protocol_P_packet_cmd,
6223
                         show_remote_protocol_P_packet_cmd,
6224
                         &remote_set_cmdlist, &remote_show_cmdlist,
6225
                         1);
6226
 
6227
  add_packet_config_cmd (&remote_protocol_Z[Z_PACKET_SOFTWARE_BP],
6228
                         "Z0", "software-breakpoint",
6229
                         set_remote_protocol_Z_software_bp_packet_cmd,
6230
                         show_remote_protocol_Z_software_bp_packet_cmd,
6231
                         &remote_set_cmdlist, &remote_show_cmdlist,
6232
                         0);
6233
 
6234
  add_packet_config_cmd (&remote_protocol_Z[Z_PACKET_HARDWARE_BP],
6235
                         "Z1", "hardware-breakpoint",
6236
                         set_remote_protocol_Z_hardware_bp_packet_cmd,
6237
                         show_remote_protocol_Z_hardware_bp_packet_cmd,
6238
                         &remote_set_cmdlist, &remote_show_cmdlist,
6239
                         0);
6240
 
6241
  add_packet_config_cmd (&remote_protocol_Z[Z_PACKET_WRITE_WP],
6242
                         "Z2", "write-watchpoint",
6243
                         set_remote_protocol_Z_write_wp_packet_cmd,
6244
                         show_remote_protocol_Z_write_wp_packet_cmd,
6245
                         &remote_set_cmdlist, &remote_show_cmdlist,
6246
                         0);
6247
 
6248
  add_packet_config_cmd (&remote_protocol_Z[Z_PACKET_READ_WP],
6249
                         "Z3", "read-watchpoint",
6250
                         set_remote_protocol_Z_read_wp_packet_cmd,
6251
                         show_remote_protocol_Z_read_wp_packet_cmd,
6252
                         &remote_set_cmdlist, &remote_show_cmdlist,
6253
                         0);
6254
 
6255
  add_packet_config_cmd (&remote_protocol_Z[Z_PACKET_ACCESS_WP],
6256
                         "Z4", "access-watchpoint",
6257
                         set_remote_protocol_Z_access_wp_packet_cmd,
6258
                         show_remote_protocol_Z_access_wp_packet_cmd,
6259
                         &remote_set_cmdlist, &remote_show_cmdlist,
6260
                         0);
6261
 
6262
  /* Keep the old ``set remote Z-packet ...'' working. */
6263
  add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
6264
                                &remote_Z_packet_detect, "\
6265
Set use of remote protocol `Z' packets",
6266
                                "Show use of remote protocol `Z' packets ",
6267
                                set_remote_protocol_Z_packet_cmd,
6268
                                show_remote_protocol_Z_packet_cmd,
6269
                                &remote_set_cmdlist, &remote_show_cmdlist);
6270
}

powered by: WebSVN 2.1.0

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