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