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