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