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