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