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