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