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