2009-07-21 Paul Pluzhnikov <ppluzhnikov@google.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, 2008, 2009
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 #include "gdb/fileio.h"
62 #include "gdb_stat.h"
63
64 #include "memory-map.h"
65
66 /* The size to align memory write packets, when practical.  The protocol
67    does not guarantee any alignment, and gdb will generate short
68    writes and unaligned writes, but even as a best-effort attempt this
69    can improve bulk transfers.  For instance, if a write is misaligned
70    relative to the target's data bus, the stub may need to make an extra
71    round trip fetching data from the target.  This doesn't make a
72    huge difference, but it's easy to do, so we try to be helpful.
73
74    The alignment chosen is arbitrary; usually data bus width is
75    important here, not the possibly larger cache line size.  */
76 enum { REMOTE_ALIGN_WRITES = 16 };
77
78 /* Prototypes for local functions.  */
79 static void cleanup_sigint_signal_handler (void *dummy);
80 static void initialize_sigint_signal_handler (void);
81 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
82 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
83                                  int forever);
84
85 static void handle_remote_sigint (int);
86 static void handle_remote_sigint_twice (int);
87 static void async_remote_interrupt (gdb_client_data);
88 void async_remote_interrupt_twice (gdb_client_data);
89
90 static void remote_files_info (struct target_ops *ignore);
91
92 static void remote_prepare_to_store (struct regcache *regcache);
93
94 static void remote_open (char *name, int from_tty);
95
96 static void extended_remote_open (char *name, int from_tty);
97
98 static void remote_open_1 (char *, int, struct target_ops *, int extended_p);
99
100 static void remote_close (int quitting);
101
102 static void remote_mourn (struct target_ops *ops);
103
104 static void extended_remote_restart (void);
105
106 static void extended_remote_mourn (struct target_ops *);
107
108 static void remote_mourn_1 (struct target_ops *);
109
110 static void remote_send (char **buf, long *sizeof_buf_p);
111
112 static int readchar (int timeout);
113
114 static void remote_kill (struct target_ops *ops);
115
116 static int tohex (int nib);
117
118 static int remote_can_async_p (void);
119
120 static int remote_is_async_p (void);
121
122 static void remote_async (void (*callback) (enum inferior_event_type event_type,
123                                             void *context), void *context);
124
125 static int remote_async_mask (int new_mask);
126
127 static void remote_detach (struct target_ops *ops, char *args, int from_tty);
128
129 static void remote_interrupt (int signo);
130
131 static void remote_interrupt_twice (int signo);
132
133 static void interrupt_query (void);
134
135 static void set_general_thread (struct ptid ptid);
136 static void set_continue_thread (struct ptid ptid);
137
138 static void get_offsets (void);
139
140 static void skip_frame (void);
141
142 static long read_frame (char **buf_p, long *sizeof_buf);
143
144 static int hexnumlen (ULONGEST num);
145
146 static void init_remote_ops (void);
147
148 static void init_extended_remote_ops (void);
149
150 static void remote_stop (ptid_t);
151
152 static int ishex (int ch, int *val);
153
154 static int stubhex (int ch);
155
156 static int hexnumstr (char *, ULONGEST);
157
158 static int hexnumnstr (char *, ULONGEST, int);
159
160 static CORE_ADDR remote_address_masked (CORE_ADDR);
161
162 static void print_packet (char *);
163
164 static unsigned long crc32 (unsigned char *, int, unsigned int);
165
166 static void compare_sections_command (char *, int);
167
168 static void packet_command (char *, int);
169
170 static int stub_unpack_int (char *buff, int fieldlength);
171
172 static ptid_t remote_current_thread (ptid_t oldptid);
173
174 static void remote_find_new_threads (void);
175
176 static void record_currthread (ptid_t currthread);
177
178 static int fromhex (int a);
179
180 static int hex2bin (const char *hex, gdb_byte *bin, int count);
181
182 static int bin2hex (const gdb_byte *bin, char *hex, int count);
183
184 static int putpkt_binary (char *buf, int cnt);
185
186 static void check_binary_download (CORE_ADDR addr);
187
188 struct packet_config;
189
190 static void show_packet_config_cmd (struct packet_config *config);
191
192 static void update_packet_config (struct packet_config *config);
193
194 static void set_remote_protocol_packet_cmd (char *args, int from_tty,
195                                             struct cmd_list_element *c);
196
197 static void show_remote_protocol_packet_cmd (struct ui_file *file,
198                                              int from_tty,
199                                              struct cmd_list_element *c,
200                                              const char *value);
201
202 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
203 static ptid_t read_ptid (char *buf, char **obuf);
204
205 static void remote_query_supported (void);
206
207 static void remote_check_symbols (struct objfile *objfile);
208
209 void _initialize_remote (void);
210
211 struct stop_reply;
212 static struct stop_reply *stop_reply_xmalloc (void);
213 static void stop_reply_xfree (struct stop_reply *);
214 static void do_stop_reply_xfree (void *arg);
215 static void remote_parse_stop_reply (char *buf, struct stop_reply *);
216 static void push_stop_reply (struct stop_reply *);
217 static void remote_get_pending_stop_replies (void);
218 static void discard_pending_stop_replies (int pid);
219 static int peek_stop_reply (ptid_t ptid);
220
221 static void remote_async_inferior_event_handler (gdb_client_data);
222 static void remote_async_get_pending_events_handler (gdb_client_data);
223
224 static void remote_terminal_ours (void);
225
226 static int remote_read_description_p (struct target_ops *target);
227
228 /* The non-stop remote protocol provisions for one pending stop reply.
229    This is where we keep it until it is acknowledged.  */
230
231 static struct stop_reply *pending_stop_reply = NULL;
232
233 /* For "remote".  */
234
235 static struct cmd_list_element *remote_cmdlist;
236
237 /* For "set remote" and "show remote".  */
238
239 static struct cmd_list_element *remote_set_cmdlist;
240 static struct cmd_list_element *remote_show_cmdlist;
241
242 /* Description of the remote protocol state for the currently
243    connected target.  This is per-target state, and independent of the
244    selected architecture.  */
245
246 struct remote_state
247 {
248   /* A buffer to use for incoming packets, and its current size.  The
249      buffer is grown dynamically for larger incoming packets.
250      Outgoing packets may also be constructed in this buffer.
251      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
252      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
253      packets.  */
254   char *buf;
255   long buf_size;
256
257   /* If we negotiated packet size explicitly (and thus can bypass
258      heuristics for the largest packet size that will not overflow
259      a buffer in the stub), this will be set to that packet size.
260      Otherwise zero, meaning to use the guessed size.  */
261   long explicit_packet_size;
262
263   /* remote_wait is normally called when the target is running and
264      waits for a stop reply packet.  But sometimes we need to call it
265      when the target is already stopped.  We can send a "?" packet
266      and have remote_wait read the response.  Or, if we already have
267      the response, we can stash it in BUF and tell remote_wait to
268      skip calling getpkt.  This flag is set when BUF contains a
269      stop reply packet and the target is not waiting.  */
270   int cached_wait_status;
271
272   /* True, if in no ack mode.  That is, neither GDB nor the stub will
273      expect acks from each other.  The connection is assumed to be
274      reliable.  */
275   int noack_mode;
276
277   /* True if we're connected in extended remote mode.  */
278   int extended;
279
280   /* True if the stub reported support for multi-process
281      extensions.  */
282   int multi_process_aware;
283
284   /* True if we resumed the target and we're waiting for the target to
285      stop.  In the mean time, we can't start another command/query.
286      The remote server wouldn't be ready to process it, so we'd
287      timeout waiting for a reply that would never come and eventually
288      we'd close the connection.  This can happen in asynchronous mode
289      because we allow GDB commands while the target is running.  */
290   int waiting_for_stop_reply;
291
292   /* True if the stub reports support for non-stop mode.  */
293   int non_stop_aware;
294
295   /* True if the stub reports support for vCont;t.  */
296   int support_vCont_t;
297
298   /* True if the stub reports support for conditional tracepoints.  */
299   int cond_tracepoints;
300 };
301
302 /* Returns true if the multi-process extensions are in effect.  */
303 static int
304 remote_multi_process_p (struct remote_state *rs)
305 {
306   return rs->extended && rs->multi_process_aware;
307 }
308
309 /* This data could be associated with a target, but we do not always
310    have access to the current target when we need it, so for now it is
311    static.  This will be fine for as long as only one target is in use
312    at a time.  */
313 static struct remote_state remote_state;
314
315 static struct remote_state *
316 get_remote_state_raw (void)
317 {
318   return &remote_state;
319 }
320
321 /* Description of the remote protocol for a given architecture.  */
322
323 struct packet_reg
324 {
325   long offset; /* Offset into G packet.  */
326   long regnum; /* GDB's internal register number.  */
327   LONGEST pnum; /* Remote protocol register number.  */
328   int in_g_packet; /* Always part of G packet.  */
329   /* long size in bytes;  == register_size (target_gdbarch, regnum);
330      at present.  */
331   /* char *name; == gdbarch_register_name (target_gdbarch, regnum);
332      at present.  */
333 };
334
335 struct remote_arch_state
336 {
337   /* Description of the remote protocol registers.  */
338   long sizeof_g_packet;
339
340   /* Description of the remote protocol registers indexed by REGNUM
341      (making an array gdbarch_num_regs in size).  */
342   struct packet_reg *regs;
343
344   /* This is the size (in chars) of the first response to the ``g''
345      packet.  It is used as a heuristic when determining the maximum
346      size of memory-read and memory-write packets.  A target will
347      typically only reserve a buffer large enough to hold the ``g''
348      packet.  The size does not include packet overhead (headers and
349      trailers).  */
350   long actual_register_packet_size;
351
352   /* This is the maximum size (in chars) of a non read/write packet.
353      It is also used as a cap on the size of read/write packets.  */
354   long remote_packet_size;
355 };
356
357
358 /* Handle for retreving the remote protocol data from gdbarch.  */
359 static struct gdbarch_data *remote_gdbarch_data_handle;
360
361 static struct remote_arch_state *
362 get_remote_arch_state (void)
363 {
364   return gdbarch_data (target_gdbarch, remote_gdbarch_data_handle);
365 }
366
367 /* Fetch the global remote target state.  */
368
369 static struct remote_state *
370 get_remote_state (void)
371 {
372   /* Make sure that the remote architecture state has been
373      initialized, because doing so might reallocate rs->buf.  Any
374      function which calls getpkt also needs to be mindful of changes
375      to rs->buf, but this call limits the number of places which run
376      into trouble.  */
377   get_remote_arch_state ();
378
379   return get_remote_state_raw ();
380 }
381
382 static int
383 compare_pnums (const void *lhs_, const void *rhs_)
384 {
385   const struct packet_reg * const *lhs = lhs_;
386   const struct packet_reg * const *rhs = rhs_;
387
388   if ((*lhs)->pnum < (*rhs)->pnum)
389     return -1;
390   else if ((*lhs)->pnum == (*rhs)->pnum)
391     return 0;
392   else
393     return 1;
394 }
395
396 static void *
397 init_remote_state (struct gdbarch *gdbarch)
398 {
399   int regnum, num_remote_regs, offset;
400   struct remote_state *rs = get_remote_state_raw ();
401   struct remote_arch_state *rsa;
402   struct packet_reg **remote_regs;
403
404   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
405
406   /* Use the architecture to build a regnum<->pnum table, which will be
407      1:1 unless a feature set specifies otherwise.  */
408   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
409                                       gdbarch_num_regs (gdbarch),
410                                       struct packet_reg);
411   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
412     {
413       struct packet_reg *r = &rsa->regs[regnum];
414
415       if (register_size (gdbarch, regnum) == 0)
416         /* Do not try to fetch zero-sized (placeholder) registers.  */
417         r->pnum = -1;
418       else
419         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
420
421       r->regnum = regnum;
422     }
423
424   /* Define the g/G packet format as the contents of each register
425      with a remote protocol number, in order of ascending protocol
426      number.  */
427
428   remote_regs = alloca (gdbarch_num_regs (gdbarch)
429                           * sizeof (struct packet_reg *));
430   for (num_remote_regs = 0, regnum = 0;
431        regnum < gdbarch_num_regs (gdbarch);
432        regnum++)
433     if (rsa->regs[regnum].pnum != -1)
434       remote_regs[num_remote_regs++] = &rsa->regs[regnum];
435
436   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
437          compare_pnums);
438
439   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
440     {
441       remote_regs[regnum]->in_g_packet = 1;
442       remote_regs[regnum]->offset = offset;
443       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
444     }
445
446   /* Record the maximum possible size of the g packet - it may turn out
447      to be smaller.  */
448   rsa->sizeof_g_packet = offset;
449
450   /* Default maximum number of characters in a packet body. Many
451      remote stubs have a hardwired buffer size of 400 bytes
452      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
453      as the maximum packet-size to ensure that the packet and an extra
454      NUL character can always fit in the buffer.  This stops GDB
455      trashing stubs that try to squeeze an extra NUL into what is
456      already a full buffer (As of 1999-12-04 that was most stubs).  */
457   rsa->remote_packet_size = 400 - 1;
458
459   /* This one is filled in when a ``g'' packet is received.  */
460   rsa->actual_register_packet_size = 0;
461
462   /* Should rsa->sizeof_g_packet needs more space than the
463      default, adjust the size accordingly. Remember that each byte is
464      encoded as two characters. 32 is the overhead for the packet
465      header / footer. NOTE: cagney/1999-10-26: I suspect that 8
466      (``$NN:G...#NN'') is a better guess, the below has been padded a
467      little.  */
468   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
469     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
470
471   /* Make sure that the packet buffer is plenty big enough for
472      this architecture.  */
473   if (rs->buf_size < rsa->remote_packet_size)
474     {
475       rs->buf_size = 2 * rsa->remote_packet_size;
476       rs->buf = xrealloc (rs->buf, rs->buf_size);
477     }
478
479   return rsa;
480 }
481
482 /* Return the current allowed size of a remote packet.  This is
483    inferred from the current architecture, and should be used to
484    limit the length of outgoing packets.  */
485 static long
486 get_remote_packet_size (void)
487 {
488   struct remote_state *rs = get_remote_state ();
489   struct remote_arch_state *rsa = get_remote_arch_state ();
490
491   if (rs->explicit_packet_size)
492     return rs->explicit_packet_size;
493
494   return rsa->remote_packet_size;
495 }
496
497 static struct packet_reg *
498 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
499 {
500   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch))
501     return NULL;
502   else
503     {
504       struct packet_reg *r = &rsa->regs[regnum];
505       gdb_assert (r->regnum == regnum);
506       return r;
507     }
508 }
509
510 static struct packet_reg *
511 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
512 {
513   int i;
514   for (i = 0; i < gdbarch_num_regs (target_gdbarch); i++)
515     {
516       struct packet_reg *r = &rsa->regs[i];
517       if (r->pnum == pnum)
518         return r;
519     }
520   return NULL;
521 }
522
523 /* FIXME: graces/2002-08-08: These variables should eventually be
524    bound to an instance of the target object (as in gdbarch-tdep()),
525    when such a thing exists.  */
526
527 /* This is set to the data address of the access causing the target
528    to stop for a watchpoint.  */
529 static CORE_ADDR remote_watch_data_address;
530
531 /* This is non-zero if target stopped for a watchpoint.  */
532 static int remote_stopped_by_watchpoint_p;
533
534 static struct target_ops remote_ops;
535
536 static struct target_ops extended_remote_ops;
537
538 static int remote_async_mask_value = 1;
539
540 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
541    ``forever'' still use the normal timeout mechanism.  This is
542    currently used by the ASYNC code to guarentee that target reads
543    during the initial connect always time-out.  Once getpkt has been
544    modified to return a timeout indication and, in turn
545    remote_wait()/wait_for_inferior() have gained a timeout parameter
546    this can go away.  */
547 static int wait_forever_enabled_p = 1;
548
549
550 /* This variable chooses whether to send a ^C or a break when the user
551    requests program interruption.  Although ^C is usually what remote
552    systems expect, and that is the default here, sometimes a break is
553    preferable instead.  */
554
555 static int remote_break;
556
557 /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
558    remote_open knows that we don't have a file open when the program
559    starts.  */
560 static struct serial *remote_desc = NULL;
561
562 /* This variable sets the number of bits in an address that are to be
563    sent in a memory ("M" or "m") packet.  Normally, after stripping
564    leading zeros, the entire address would be sent. This variable
565    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
566    initial implementation of remote.c restricted the address sent in
567    memory packets to ``host::sizeof long'' bytes - (typically 32
568    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
569    address was never sent.  Since fixing this bug may cause a break in
570    some remote targets this variable is principly provided to
571    facilitate backward compatibility.  */
572
573 static int remote_address_size;
574
575 /* Temporary to track who currently owns the terminal.  See
576    remote_terminal_* for more details.  */
577
578 static int remote_async_terminal_ours_p;
579
580 /* The executable file to use for "run" on the remote side.  */
581
582 static char *remote_exec_file = "";
583
584 \f
585 /* User configurable variables for the number of characters in a
586    memory read/write packet.  MIN (rsa->remote_packet_size,
587    rsa->sizeof_g_packet) is the default.  Some targets need smaller
588    values (fifo overruns, et.al.) and some users need larger values
589    (speed up transfers).  The variables ``preferred_*'' (the user
590    request), ``current_*'' (what was actually set) and ``forced_*''
591    (Positive - a soft limit, negative - a hard limit).  */
592
593 struct memory_packet_config
594 {
595   char *name;
596   long size;
597   int fixed_p;
598 };
599
600 /* Compute the current size of a read/write packet.  Since this makes
601    use of ``actual_register_packet_size'' the computation is dynamic.  */
602
603 static long
604 get_memory_packet_size (struct memory_packet_config *config)
605 {
606   struct remote_state *rs = get_remote_state ();
607   struct remote_arch_state *rsa = get_remote_arch_state ();
608
609   /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
610      law?) that some hosts don't cope very well with large alloca()
611      calls.  Eventually the alloca() code will be replaced by calls to
612      xmalloc() and make_cleanups() allowing this restriction to either
613      be lifted or removed.  */
614 #ifndef MAX_REMOTE_PACKET_SIZE
615 #define MAX_REMOTE_PACKET_SIZE 16384
616 #endif
617   /* NOTE: 20 ensures we can write at least one byte.  */
618 #ifndef MIN_REMOTE_PACKET_SIZE
619 #define MIN_REMOTE_PACKET_SIZE 20
620 #endif
621   long what_they_get;
622   if (config->fixed_p)
623     {
624       if (config->size <= 0)
625         what_they_get = MAX_REMOTE_PACKET_SIZE;
626       else
627         what_they_get = config->size;
628     }
629   else
630     {
631       what_they_get = get_remote_packet_size ();
632       /* Limit the packet to the size specified by the user.  */
633       if (config->size > 0
634           && what_they_get > config->size)
635         what_they_get = config->size;
636
637       /* Limit it to the size of the targets ``g'' response unless we have
638          permission from the stub to use a larger packet size.  */
639       if (rs->explicit_packet_size == 0
640           && rsa->actual_register_packet_size > 0
641           && what_they_get > rsa->actual_register_packet_size)
642         what_they_get = rsa->actual_register_packet_size;
643     }
644   if (what_they_get > MAX_REMOTE_PACKET_SIZE)
645     what_they_get = MAX_REMOTE_PACKET_SIZE;
646   if (what_they_get < MIN_REMOTE_PACKET_SIZE)
647     what_they_get = MIN_REMOTE_PACKET_SIZE;
648
649   /* Make sure there is room in the global buffer for this packet
650      (including its trailing NUL byte).  */
651   if (rs->buf_size < what_they_get + 1)
652     {
653       rs->buf_size = 2 * what_they_get;
654       rs->buf = xrealloc (rs->buf, 2 * what_they_get);
655     }
656
657   return what_they_get;
658 }
659
660 /* Update the size of a read/write packet. If they user wants
661    something really big then do a sanity check.  */
662
663 static void
664 set_memory_packet_size (char *args, struct memory_packet_config *config)
665 {
666   int fixed_p = config->fixed_p;
667   long size = config->size;
668   if (args == NULL)
669     error (_("Argument required (integer, `fixed' or `limited')."));
670   else if (strcmp (args, "hard") == 0
671       || strcmp (args, "fixed") == 0)
672     fixed_p = 1;
673   else if (strcmp (args, "soft") == 0
674            || strcmp (args, "limit") == 0)
675     fixed_p = 0;
676   else
677     {
678       char *end;
679       size = strtoul (args, &end, 0);
680       if (args == end)
681         error (_("Invalid %s (bad syntax)."), config->name);
682 #if 0
683       /* Instead of explicitly capping the size of a packet to
684          MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
685          instead allowed to set the size to something arbitrarily
686          large.  */
687       if (size > MAX_REMOTE_PACKET_SIZE)
688         error (_("Invalid %s (too large)."), config->name);
689 #endif
690     }
691   /* Extra checks?  */
692   if (fixed_p && !config->fixed_p)
693     {
694       if (! query (_("The target may not be able to correctly handle a %s\n"
695                    "of %ld bytes. Change the packet size? "),
696                    config->name, size))
697         error (_("Packet size not changed."));
698     }
699   /* Update the config.  */
700   config->fixed_p = fixed_p;
701   config->size = size;
702 }
703
704 static void
705 show_memory_packet_size (struct memory_packet_config *config)
706 {
707   printf_filtered (_("The %s is %ld. "), config->name, config->size);
708   if (config->fixed_p)
709     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
710                      get_memory_packet_size (config));
711   else
712     printf_filtered (_("Packets are limited to %ld bytes.\n"),
713                      get_memory_packet_size (config));
714 }
715
716 static struct memory_packet_config memory_write_packet_config =
717 {
718   "memory-write-packet-size",
719 };
720
721 static void
722 set_memory_write_packet_size (char *args, int from_tty)
723 {
724   set_memory_packet_size (args, &memory_write_packet_config);
725 }
726
727 static void
728 show_memory_write_packet_size (char *args, int from_tty)
729 {
730   show_memory_packet_size (&memory_write_packet_config);
731 }
732
733 static long
734 get_memory_write_packet_size (void)
735 {
736   return get_memory_packet_size (&memory_write_packet_config);
737 }
738
739 static struct memory_packet_config memory_read_packet_config =
740 {
741   "memory-read-packet-size",
742 };
743
744 static void
745 set_memory_read_packet_size (char *args, int from_tty)
746 {
747   set_memory_packet_size (args, &memory_read_packet_config);
748 }
749
750 static void
751 show_memory_read_packet_size (char *args, int from_tty)
752 {
753   show_memory_packet_size (&memory_read_packet_config);
754 }
755
756 static long
757 get_memory_read_packet_size (void)
758 {
759   long size = get_memory_packet_size (&memory_read_packet_config);
760   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
761      extra buffer size argument before the memory read size can be
762      increased beyond this.  */
763   if (size > get_remote_packet_size ())
764     size = get_remote_packet_size ();
765   return size;
766 }
767
768 \f
769 /* Generic configuration support for packets the stub optionally
770    supports. Allows the user to specify the use of the packet as well
771    as allowing GDB to auto-detect support in the remote stub.  */
772
773 enum packet_support
774   {
775     PACKET_SUPPORT_UNKNOWN = 0,
776     PACKET_ENABLE,
777     PACKET_DISABLE
778   };
779
780 struct packet_config
781   {
782     const char *name;
783     const char *title;
784     enum auto_boolean detect;
785     enum packet_support support;
786   };
787
788 /* Analyze a packet's return value and update the packet config
789    accordingly.  */
790
791 enum packet_result
792 {
793   PACKET_ERROR,
794   PACKET_OK,
795   PACKET_UNKNOWN
796 };
797
798 static void
799 update_packet_config (struct packet_config *config)
800 {
801   switch (config->detect)
802     {
803     case AUTO_BOOLEAN_TRUE:
804       config->support = PACKET_ENABLE;
805       break;
806     case AUTO_BOOLEAN_FALSE:
807       config->support = PACKET_DISABLE;
808       break;
809     case AUTO_BOOLEAN_AUTO:
810       config->support = PACKET_SUPPORT_UNKNOWN;
811       break;
812     }
813 }
814
815 static void
816 show_packet_config_cmd (struct packet_config *config)
817 {
818   char *support = "internal-error";
819   switch (config->support)
820     {
821     case PACKET_ENABLE:
822       support = "enabled";
823       break;
824     case PACKET_DISABLE:
825       support = "disabled";
826       break;
827     case PACKET_SUPPORT_UNKNOWN:
828       support = "unknown";
829       break;
830     }
831   switch (config->detect)
832     {
833     case AUTO_BOOLEAN_AUTO:
834       printf_filtered (_("Support for the `%s' packet is auto-detected, currently %s.\n"),
835                        config->name, support);
836       break;
837     case AUTO_BOOLEAN_TRUE:
838     case AUTO_BOOLEAN_FALSE:
839       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
840                        config->name, support);
841       break;
842     }
843 }
844
845 static void
846 add_packet_config_cmd (struct packet_config *config, const char *name,
847                        const char *title, int legacy)
848 {
849   char *set_doc;
850   char *show_doc;
851   char *cmd_name;
852
853   config->name = name;
854   config->title = title;
855   config->detect = AUTO_BOOLEAN_AUTO;
856   config->support = PACKET_SUPPORT_UNKNOWN;
857   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
858                         name, title);
859   show_doc = xstrprintf ("Show current use of remote protocol `%s' (%s) packet",
860                          name, title);
861   /* set/show TITLE-packet {auto,on,off} */
862   cmd_name = xstrprintf ("%s-packet", title);
863   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
864                                 &config->detect, set_doc, show_doc, NULL, /* help_doc */
865                                 set_remote_protocol_packet_cmd,
866                                 show_remote_protocol_packet_cmd,
867                                 &remote_set_cmdlist, &remote_show_cmdlist);
868   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
869   if (legacy)
870     {
871       char *legacy_name;
872       legacy_name = xstrprintf ("%s-packet", name);
873       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
874                      &remote_set_cmdlist);
875       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
876                      &remote_show_cmdlist);
877     }
878 }
879
880 static enum packet_result
881 packet_check_result (const char *buf)
882 {
883   if (buf[0] != '\0')
884     {
885       /* The stub recognized the packet request.  Check that the
886          operation succeeded.  */
887       if (buf[0] == 'E'
888           && isxdigit (buf[1]) && isxdigit (buf[2])
889           && buf[3] == '\0')
890         /* "Enn"  - definitly an error.  */
891         return PACKET_ERROR;
892
893       /* Always treat "E." as an error.  This will be used for
894          more verbose error messages, such as E.memtypes.  */
895       if (buf[0] == 'E' && buf[1] == '.')
896         return PACKET_ERROR;
897
898       /* The packet may or may not be OK.  Just assume it is.  */
899       return PACKET_OK;
900     }
901   else
902     /* The stub does not support the packet.  */
903     return PACKET_UNKNOWN;
904 }
905
906 static enum packet_result
907 packet_ok (const char *buf, struct packet_config *config)
908 {
909   enum packet_result result;
910
911   result = packet_check_result (buf);
912   switch (result)
913     {
914     case PACKET_OK:
915     case PACKET_ERROR:
916       /* The stub recognized the packet request.  */
917       switch (config->support)
918         {
919         case PACKET_SUPPORT_UNKNOWN:
920           if (remote_debug)
921             fprintf_unfiltered (gdb_stdlog,
922                                     "Packet %s (%s) is supported\n",
923                                     config->name, config->title);
924           config->support = PACKET_ENABLE;
925           break;
926         case PACKET_DISABLE:
927           internal_error (__FILE__, __LINE__,
928                           _("packet_ok: attempt to use a disabled packet"));
929           break;
930         case PACKET_ENABLE:
931           break;
932         }
933       break;
934     case PACKET_UNKNOWN:
935       /* The stub does not support the packet.  */
936       switch (config->support)
937         {
938         case PACKET_ENABLE:
939           if (config->detect == AUTO_BOOLEAN_AUTO)
940             /* If the stub previously indicated that the packet was
941                supported then there is a protocol error..  */
942             error (_("Protocol error: %s (%s) conflicting enabled responses."),
943                    config->name, config->title);
944           else
945             /* The user set it wrong.  */
946             error (_("Enabled packet %s (%s) not recognized by stub"),
947                    config->name, config->title);
948           break;
949         case PACKET_SUPPORT_UNKNOWN:
950           if (remote_debug)
951             fprintf_unfiltered (gdb_stdlog,
952                                 "Packet %s (%s) is NOT supported\n",
953                                 config->name, config->title);
954           config->support = PACKET_DISABLE;
955           break;
956         case PACKET_DISABLE:
957           break;
958         }
959       break;
960     }
961
962   return result;
963 }
964
965 enum {
966   PACKET_vCont = 0,
967   PACKET_X,
968   PACKET_qSymbol,
969   PACKET_P,
970   PACKET_p,
971   PACKET_Z0,
972   PACKET_Z1,
973   PACKET_Z2,
974   PACKET_Z3,
975   PACKET_Z4,
976   PACKET_vFile_open,
977   PACKET_vFile_pread,
978   PACKET_vFile_pwrite,
979   PACKET_vFile_close,
980   PACKET_vFile_unlink,
981   PACKET_qXfer_auxv,
982   PACKET_qXfer_features,
983   PACKET_qXfer_libraries,
984   PACKET_qXfer_memory_map,
985   PACKET_qXfer_spu_read,
986   PACKET_qXfer_spu_write,
987   PACKET_qXfer_osdata,
988   PACKET_qGetTLSAddr,
989   PACKET_qSupported,
990   PACKET_QPassSignals,
991   PACKET_qSearch_memory,
992   PACKET_vAttach,
993   PACKET_vRun,
994   PACKET_QStartNoAckMode,
995   PACKET_vKill,
996   PACKET_qXfer_siginfo_read,
997   PACKET_qXfer_siginfo_write,
998   PACKET_qAttached,
999   PACKET_ConditionalTracepoints,
1000   PACKET_MAX
1001 };
1002
1003 static struct packet_config remote_protocol_packets[PACKET_MAX];
1004
1005 static void
1006 set_remote_protocol_packet_cmd (char *args, int from_tty,
1007                                 struct cmd_list_element *c)
1008 {
1009   struct packet_config *packet;
1010
1011   for (packet = remote_protocol_packets;
1012        packet < &remote_protocol_packets[PACKET_MAX];
1013        packet++)
1014     {
1015       if (&packet->detect == c->var)
1016         {
1017           update_packet_config (packet);
1018           return;
1019         }
1020     }
1021   internal_error (__FILE__, __LINE__, "Could not find config for %s",
1022                   c->name);
1023 }
1024
1025 static void
1026 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1027                                  struct cmd_list_element *c,
1028                                  const char *value)
1029 {
1030   struct packet_config *packet;
1031
1032   for (packet = remote_protocol_packets;
1033        packet < &remote_protocol_packets[PACKET_MAX];
1034        packet++)
1035     {
1036       if (&packet->detect == c->var)
1037         {
1038           show_packet_config_cmd (packet);
1039           return;
1040         }
1041     }
1042   internal_error (__FILE__, __LINE__, "Could not find config for %s",
1043                   c->name);
1044 }
1045
1046 /* Should we try one of the 'Z' requests?  */
1047
1048 enum Z_packet_type
1049 {
1050   Z_PACKET_SOFTWARE_BP,
1051   Z_PACKET_HARDWARE_BP,
1052   Z_PACKET_WRITE_WP,
1053   Z_PACKET_READ_WP,
1054   Z_PACKET_ACCESS_WP,
1055   NR_Z_PACKET_TYPES
1056 };
1057
1058 /* For compatibility with older distributions.  Provide a ``set remote
1059    Z-packet ...'' command that updates all the Z packet types.  */
1060
1061 static enum auto_boolean remote_Z_packet_detect;
1062
1063 static void
1064 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1065                                   struct cmd_list_element *c)
1066 {
1067   int i;
1068   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1069     {
1070       remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1071       update_packet_config (&remote_protocol_packets[PACKET_Z0 + i]);
1072     }
1073 }
1074
1075 static void
1076 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1077                                    struct cmd_list_element *c,
1078                                    const char *value)
1079 {
1080   int i;
1081   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1082     {
1083       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1084     }
1085 }
1086
1087 /* Should we try the 'ThreadInfo' query packet?
1088
1089    This variable (NOT available to the user: auto-detect only!)
1090    determines whether GDB will use the new, simpler "ThreadInfo"
1091    query or the older, more complex syntax for thread queries.
1092    This is an auto-detect variable (set to true at each connect,
1093    and set to false when the target fails to recognize it).  */
1094
1095 static int use_threadinfo_query;
1096 static int use_threadextra_query;
1097
1098 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1099 static struct async_signal_handler *sigint_remote_twice_token;
1100 static struct async_signal_handler *sigint_remote_token;
1101
1102 \f
1103 /* Asynchronous signal handle registered as event loop source for
1104    when we have pending events ready to be passed to the core.  */
1105
1106 static struct async_event_handler *remote_async_inferior_event_token;
1107
1108 /* Asynchronous signal handle registered as event loop source for when
1109    the remote sent us a %Stop notification.  The registered callback
1110    will do a vStopped sequence to pull the rest of the events out of
1111    the remote side into our event queue.  */
1112
1113 static struct async_event_handler *remote_async_get_pending_events_token;
1114 \f
1115
1116 static ptid_t magic_null_ptid;
1117 static ptid_t not_sent_ptid;
1118 static ptid_t any_thread_ptid;
1119
1120 /* These are the threads which we last sent to the remote system.  The
1121    TID member will be -1 for all or -2 for not sent yet.  */
1122
1123 static ptid_t general_thread;
1124 static ptid_t continue_thread;
1125
1126 /* Find out if the stub attached to PID (and hence GDB should offer to
1127    detach instead of killing it when bailing out).  */
1128
1129 static int
1130 remote_query_attached (int pid)
1131 {
1132   struct remote_state *rs = get_remote_state ();
1133
1134   if (remote_protocol_packets[PACKET_qAttached].support == PACKET_DISABLE)
1135     return 0;
1136
1137   if (remote_multi_process_p (rs))
1138     sprintf (rs->buf, "qAttached:%x", pid);
1139   else
1140     sprintf (rs->buf, "qAttached");
1141
1142   putpkt (rs->buf);
1143   getpkt (&rs->buf, &rs->buf_size, 0);
1144
1145   switch (packet_ok (rs->buf,
1146                      &remote_protocol_packets[PACKET_qAttached]))
1147     {
1148     case PACKET_OK:
1149       if (strcmp (rs->buf, "1") == 0)
1150         return 1;
1151       break;
1152     case PACKET_ERROR:
1153       warning (_("Remote failure reply: %s"), rs->buf);
1154       break;
1155     case PACKET_UNKNOWN:
1156       break;
1157     }
1158
1159   return 0;
1160 }
1161
1162 /* Add PID to GDB's inferior table.  Since we can be connected to a
1163    remote system before before knowing about any inferior, mark the
1164    target with execution when we find the first inferior.  If ATTACHED
1165    is 1, then we had just attached to this inferior.  If it is 0, then
1166    we just created this inferior.  If it is -1, then try querying the
1167    remote stub to find out if it had attached to the inferior or
1168    not.  */
1169
1170 static struct inferior *
1171 remote_add_inferior (int pid, int attached)
1172 {
1173   struct remote_state *rs = get_remote_state ();
1174   struct inferior *inf;
1175
1176   /* Check whether this process we're learning about is to be
1177      considered attached, or if is to be considered to have been
1178      spawned by the stub.  */
1179   if (attached == -1)
1180     attached = remote_query_attached (pid);
1181
1182   inf = add_inferior (pid);
1183
1184   inf->attach_flag = attached;
1185
1186   return inf;
1187 }
1188
1189 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1190    according to RUNNING.  */
1191
1192 static void
1193 remote_add_thread (ptid_t ptid, int running)
1194 {
1195   add_thread (ptid);
1196
1197   set_executing (ptid, running);
1198   set_running (ptid, running);
1199 }
1200
1201 /* Come here when we learn about a thread id from the remote target.
1202    It may be the first time we hear about such thread, so take the
1203    opportunity to add it to GDB's thread list.  In case this is the
1204    first time we're noticing its corresponding inferior, add it to
1205    GDB's inferior list as well.  */
1206
1207 static void
1208 remote_notice_new_inferior (ptid_t currthread, int running)
1209 {
1210   struct remote_state *rs = get_remote_state ();
1211
1212   /* If this is a new thread, add it to GDB's thread list.
1213      If we leave it up to WFI to do this, bad things will happen.  */
1214
1215   if (in_thread_list (currthread) && is_exited (currthread))
1216     {
1217       /* We're seeing an event on a thread id we knew had exited.
1218          This has to be a new thread reusing the old id.  Add it.  */
1219       remote_add_thread (currthread, running);
1220       return;
1221     }
1222
1223   if (!in_thread_list (currthread))
1224     {
1225       struct inferior *inf = NULL;
1226       int pid = ptid_get_pid (currthread);
1227
1228       if (ptid_is_pid (inferior_ptid)
1229           && pid == ptid_get_pid (inferior_ptid))
1230         {
1231           /* inferior_ptid has no thread member yet.  This can happen
1232              with the vAttach -> remote_wait,"TAAthread:" path if the
1233              stub doesn't support qC.  This is the first stop reported
1234              after an attach, so this is the main thread.  Update the
1235              ptid in the thread list.  */
1236           if (in_thread_list (pid_to_ptid (pid)))
1237             thread_change_ptid (inferior_ptid, currthread);
1238           else
1239             {
1240               remote_add_thread (currthread, running);
1241               inferior_ptid = currthread;
1242             }
1243           return;
1244         }
1245
1246       if (ptid_equal (magic_null_ptid, inferior_ptid))
1247         {
1248           /* inferior_ptid is not set yet.  This can happen with the
1249              vRun -> remote_wait,"TAAthread:" path if the stub
1250              doesn't support qC.  This is the first stop reported
1251              after an attach, so this is the main thread.  Update the
1252              ptid in the thread list.  */
1253           thread_change_ptid (inferior_ptid, currthread);
1254           return;
1255         }
1256
1257       /* When connecting to a target remote, or to a target
1258          extended-remote which already was debugging an inferior, we
1259          may not know about it yet.  Add it before adding its child
1260          thread, so notifications are emitted in a sensible order.  */
1261       if (!in_inferior_list (ptid_get_pid (currthread)))
1262         inf = remote_add_inferior (ptid_get_pid (currthread), -1);
1263
1264       /* This is really a new thread.  Add it.  */
1265       remote_add_thread (currthread, running);
1266
1267       /* If we found a new inferior, let the common code do whatever
1268          it needs to with it (e.g., read shared libraries, insert
1269          breakpoints).  */
1270       if (inf != NULL)
1271         notice_new_inferior (currthread, running, 0);
1272     }
1273 }
1274
1275 /* Call this function as a result of
1276    1) A halt indication (T packet) containing a thread id
1277    2) A direct query of currthread
1278    3) Successful execution of set thread
1279  */
1280
1281 static void
1282 record_currthread (ptid_t currthread)
1283 {
1284   general_thread = currthread;
1285
1286   if (ptid_equal (currthread, minus_one_ptid))
1287     /* We're just invalidating the local thread mirror.  */
1288     return;
1289
1290   remote_notice_new_inferior (currthread, 0);
1291 }
1292
1293 static char *last_pass_packet;
1294
1295 /* If 'QPassSignals' is supported, tell the remote stub what signals
1296    it can simply pass through to the inferior without reporting.  */
1297
1298 static void
1299 remote_pass_signals (void)
1300 {
1301   if (remote_protocol_packets[PACKET_QPassSignals].support != PACKET_DISABLE)
1302     {
1303       char *pass_packet, *p;
1304       int numsigs = (int) TARGET_SIGNAL_LAST;
1305       int count = 0, i;
1306
1307       gdb_assert (numsigs < 256);
1308       for (i = 0; i < numsigs; i++)
1309         {
1310           if (signal_stop_state (i) == 0
1311               && signal_print_state (i) == 0
1312               && signal_pass_state (i) == 1)
1313             count++;
1314         }
1315       pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1316       strcpy (pass_packet, "QPassSignals:");
1317       p = pass_packet + strlen (pass_packet);
1318       for (i = 0; i < numsigs; i++)
1319         {
1320           if (signal_stop_state (i) == 0
1321               && signal_print_state (i) == 0
1322               && signal_pass_state (i) == 1)
1323             {
1324               if (i >= 16)
1325                 *p++ = tohex (i >> 4);
1326               *p++ = tohex (i & 15);
1327               if (count)
1328                 *p++ = ';';
1329               else
1330                 break;
1331               count--;
1332             }
1333         }
1334       *p = 0;
1335       if (!last_pass_packet || strcmp (last_pass_packet, pass_packet))
1336         {
1337           struct remote_state *rs = get_remote_state ();
1338           char *buf = rs->buf;
1339
1340           putpkt (pass_packet);
1341           getpkt (&rs->buf, &rs->buf_size, 0);
1342           packet_ok (buf, &remote_protocol_packets[PACKET_QPassSignals]);
1343           if (last_pass_packet)
1344             xfree (last_pass_packet);
1345           last_pass_packet = pass_packet;
1346         }
1347       else
1348         xfree (pass_packet);
1349     }
1350 }
1351
1352 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
1353    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1354    thread.  If GEN is set, set the general thread, if not, then set
1355    the step/continue thread.  */
1356 static void
1357 set_thread (struct ptid ptid, int gen)
1358 {
1359   struct remote_state *rs = get_remote_state ();
1360   ptid_t state = gen ? general_thread : continue_thread;
1361   char *buf = rs->buf;
1362   char *endbuf = rs->buf + get_remote_packet_size ();
1363
1364   if (ptid_equal (state, ptid))
1365     return;
1366
1367   *buf++ = 'H';
1368   *buf++ = gen ? 'g' : 'c';
1369   if (ptid_equal (ptid, magic_null_ptid))
1370     xsnprintf (buf, endbuf - buf, "0");
1371   else if (ptid_equal (ptid, any_thread_ptid))
1372     xsnprintf (buf, endbuf - buf, "0");
1373   else if (ptid_equal (ptid, minus_one_ptid))
1374     xsnprintf (buf, endbuf - buf, "-1");
1375   else
1376     write_ptid (buf, endbuf, ptid);
1377   putpkt (rs->buf);
1378   getpkt (&rs->buf, &rs->buf_size, 0);
1379   if (gen)
1380     general_thread = ptid;
1381   else
1382     continue_thread = ptid;
1383 }
1384
1385 static void
1386 set_general_thread (struct ptid ptid)
1387 {
1388   set_thread (ptid, 1);
1389 }
1390
1391 static void
1392 set_continue_thread (struct ptid ptid)
1393 {
1394   set_thread (ptid, 0);
1395 }
1396
1397 /* Change the remote current process.  Which thread within the process
1398    ends up selected isn't important, as long as it is the same process
1399    as what INFERIOR_PTID points to.
1400
1401    This comes from that fact that there is no explicit notion of
1402    "selected process" in the protocol.  The selected process for
1403    general operations is the process the selected general thread
1404    belongs to.  */
1405
1406 static void
1407 set_general_process (void)
1408 {
1409   struct remote_state *rs = get_remote_state ();
1410
1411   /* If the remote can't handle multiple processes, don't bother.  */
1412   if (!remote_multi_process_p (rs))
1413     return;
1414
1415   /* We only need to change the remote current thread if it's pointing
1416      at some other process.  */
1417   if (ptid_get_pid (general_thread) != ptid_get_pid (inferior_ptid))
1418     set_general_thread (inferior_ptid);
1419 }
1420
1421 \f
1422 /*  Return nonzero if the thread PTID is still alive on the remote
1423     system.  */
1424
1425 static int
1426 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1427 {
1428   struct remote_state *rs = get_remote_state ();
1429   int tid = ptid_get_tid (ptid);
1430   char *p, *endp;
1431
1432   if (ptid_equal (ptid, magic_null_ptid))
1433     /* The main thread is always alive.  */
1434     return 1;
1435
1436   if (ptid_get_pid (ptid) != 0 && ptid_get_tid (ptid) == 0)
1437     /* The main thread is always alive.  This can happen after a
1438        vAttach, if the remote side doesn't support
1439        multi-threading.  */
1440     return 1;
1441
1442   p = rs->buf;
1443   endp = rs->buf + get_remote_packet_size ();
1444
1445   *p++ = 'T';
1446   write_ptid (p, endp, ptid);
1447
1448   putpkt (rs->buf);
1449   getpkt (&rs->buf, &rs->buf_size, 0);
1450   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1451 }
1452
1453 /* About these extended threadlist and threadinfo packets.  They are
1454    variable length packets but, the fields within them are often fixed
1455    length.  They are redundent enough to send over UDP as is the
1456    remote protocol in general.  There is a matching unit test module
1457    in libstub.  */
1458
1459 #define OPAQUETHREADBYTES 8
1460
1461 /* a 64 bit opaque identifier */
1462 typedef unsigned char threadref[OPAQUETHREADBYTES];
1463
1464 /* WARNING: This threadref data structure comes from the remote O.S.,
1465    libstub protocol encoding, and remote.c. it is not particularly
1466    changable.  */
1467
1468 /* Right now, the internal structure is int. We want it to be bigger.
1469    Plan to fix this.
1470  */
1471
1472 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
1473
1474 /* gdb_ext_thread_info is an internal GDB data structure which is
1475    equivalent to the reply of the remote threadinfo packet.  */
1476
1477 struct gdb_ext_thread_info
1478   {
1479     threadref threadid;         /* External form of thread reference.  */
1480     int active;                 /* Has state interesting to GDB?
1481                                    regs, stack.  */
1482     char display[256];          /* Brief state display, name,
1483                                    blocked/suspended.  */
1484     char shortname[32];         /* To be used to name threads.  */
1485     char more_display[256];     /* Long info, statistics, queue depth,
1486                                    whatever.  */
1487   };
1488
1489 /* The volume of remote transfers can be limited by submitting
1490    a mask containing bits specifying the desired information.
1491    Use a union of these values as the 'selection' parameter to
1492    get_thread_info. FIXME: Make these TAG names more thread specific.
1493  */
1494
1495 #define TAG_THREADID 1
1496 #define TAG_EXISTS 2
1497 #define TAG_DISPLAY 4
1498 #define TAG_THREADNAME 8
1499 #define TAG_MOREDISPLAY 16
1500
1501 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
1502
1503 char *unpack_varlen_hex (char *buff, ULONGEST *result);
1504
1505 static char *unpack_nibble (char *buf, int *val);
1506
1507 static char *pack_nibble (char *buf, int nibble);
1508
1509 static char *pack_hex_byte (char *pkt, int /* unsigned char */ byte);
1510
1511 static char *unpack_byte (char *buf, int *value);
1512
1513 static char *pack_int (char *buf, int value);
1514
1515 static char *unpack_int (char *buf, int *value);
1516
1517 static char *unpack_string (char *src, char *dest, int length);
1518
1519 static char *pack_threadid (char *pkt, threadref *id);
1520
1521 static char *unpack_threadid (char *inbuf, threadref *id);
1522
1523 void int_to_threadref (threadref *id, int value);
1524
1525 static int threadref_to_int (threadref *ref);
1526
1527 static void copy_threadref (threadref *dest, threadref *src);
1528
1529 static int threadmatch (threadref *dest, threadref *src);
1530
1531 static char *pack_threadinfo_request (char *pkt, int mode,
1532                                       threadref *id);
1533
1534 static int remote_unpack_thread_info_response (char *pkt,
1535                                                threadref *expectedref,
1536                                                struct gdb_ext_thread_info
1537                                                *info);
1538
1539
1540 static int remote_get_threadinfo (threadref *threadid,
1541                                   int fieldset, /*TAG mask */
1542                                   struct gdb_ext_thread_info *info);
1543
1544 static char *pack_threadlist_request (char *pkt, int startflag,
1545                                       int threadcount,
1546                                       threadref *nextthread);
1547
1548 static int parse_threadlist_response (char *pkt,
1549                                       int result_limit,
1550                                       threadref *original_echo,
1551                                       threadref *resultlist,
1552                                       int *doneflag);
1553
1554 static int remote_get_threadlist (int startflag,
1555                                   threadref *nextthread,
1556                                   int result_limit,
1557                                   int *done,
1558                                   int *result_count,
1559                                   threadref *threadlist);
1560
1561 typedef int (*rmt_thread_action) (threadref *ref, void *context);
1562
1563 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
1564                                        void *context, int looplimit);
1565
1566 static int remote_newthread_step (threadref *ref, void *context);
1567
1568
1569 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
1570    buffer we're allowed to write to.  Returns
1571    BUF+CHARACTERS_WRITTEN.  */
1572
1573 static char *
1574 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
1575 {
1576   int pid, tid;
1577   struct remote_state *rs = get_remote_state ();
1578
1579   if (remote_multi_process_p (rs))
1580     {
1581       pid = ptid_get_pid (ptid);
1582       if (pid < 0)
1583         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
1584       else
1585         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
1586     }
1587   tid = ptid_get_tid (ptid);
1588   if (tid < 0)
1589     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
1590   else
1591     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
1592
1593   return buf;
1594 }
1595
1596 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
1597    passed the last parsed char.  Returns null_ptid on error.  */
1598
1599 static ptid_t
1600 read_ptid (char *buf, char **obuf)
1601 {
1602   char *p = buf;
1603   char *pp;
1604   ULONGEST pid = 0, tid = 0;
1605   ptid_t ptid;
1606
1607   if (*p == 'p')
1608     {
1609       /* Multi-process ptid.  */
1610       pp = unpack_varlen_hex (p + 1, &pid);
1611       if (*pp != '.')
1612         error (_("invalid remote ptid: %s\n"), p);
1613
1614       p = pp;
1615       pp = unpack_varlen_hex (p + 1, &tid);
1616       if (obuf)
1617         *obuf = pp;
1618       return ptid_build (pid, 0, tid);
1619     }
1620
1621   /* No multi-process.  Just a tid.  */
1622   pp = unpack_varlen_hex (p, &tid);
1623
1624   /* Since the stub is not sending a process id, then default to
1625      what's in inferior_ptid, unless it's null at this point.  If so,
1626      then since there's no way to know the pid of the reported
1627      threads, use the magic number.  */
1628   if (ptid_equal (inferior_ptid, null_ptid))
1629     pid = ptid_get_pid (magic_null_ptid);
1630   else
1631     pid = ptid_get_pid (inferior_ptid);
1632
1633   if (obuf)
1634     *obuf = pp;
1635   return ptid_build (pid, 0, tid);
1636 }
1637
1638 /* Encode 64 bits in 16 chars of hex.  */
1639
1640 static const char hexchars[] = "0123456789abcdef";
1641
1642 static int
1643 ishex (int ch, int *val)
1644 {
1645   if ((ch >= 'a') && (ch <= 'f'))
1646     {
1647       *val = ch - 'a' + 10;
1648       return 1;
1649     }
1650   if ((ch >= 'A') && (ch <= 'F'))
1651     {
1652       *val = ch - 'A' + 10;
1653       return 1;
1654     }
1655   if ((ch >= '0') && (ch <= '9'))
1656     {
1657       *val = ch - '0';
1658       return 1;
1659     }
1660   return 0;
1661 }
1662
1663 static int
1664 stubhex (int ch)
1665 {
1666   if (ch >= 'a' && ch <= 'f')
1667     return ch - 'a' + 10;
1668   if (ch >= '0' && ch <= '9')
1669     return ch - '0';
1670   if (ch >= 'A' && ch <= 'F')
1671     return ch - 'A' + 10;
1672   return -1;
1673 }
1674
1675 static int
1676 stub_unpack_int (char *buff, int fieldlength)
1677 {
1678   int nibble;
1679   int retval = 0;
1680
1681   while (fieldlength)
1682     {
1683       nibble = stubhex (*buff++);
1684       retval |= nibble;
1685       fieldlength--;
1686       if (fieldlength)
1687         retval = retval << 4;
1688     }
1689   return retval;
1690 }
1691
1692 char *
1693 unpack_varlen_hex (char *buff,  /* packet to parse */
1694                    ULONGEST *result)
1695 {
1696   int nibble;
1697   ULONGEST retval = 0;
1698
1699   while (ishex (*buff, &nibble))
1700     {
1701       buff++;
1702       retval = retval << 4;
1703       retval |= nibble & 0x0f;
1704     }
1705   *result = retval;
1706   return buff;
1707 }
1708
1709 static char *
1710 unpack_nibble (char *buf, int *val)
1711 {
1712   *val = fromhex (*buf++);
1713   return buf;
1714 }
1715
1716 static char *
1717 pack_nibble (char *buf, int nibble)
1718 {
1719   *buf++ = hexchars[(nibble & 0x0f)];
1720   return buf;
1721 }
1722
1723 static char *
1724 pack_hex_byte (char *pkt, int byte)
1725 {
1726   *pkt++ = hexchars[(byte >> 4) & 0xf];
1727   *pkt++ = hexchars[(byte & 0xf)];
1728   return pkt;
1729 }
1730
1731 static char *
1732 unpack_byte (char *buf, int *value)
1733 {
1734   *value = stub_unpack_int (buf, 2);
1735   return buf + 2;
1736 }
1737
1738 static char *
1739 pack_int (char *buf, int value)
1740 {
1741   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
1742   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
1743   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
1744   buf = pack_hex_byte (buf, (value & 0xff));
1745   return buf;
1746 }
1747
1748 static char *
1749 unpack_int (char *buf, int *value)
1750 {
1751   *value = stub_unpack_int (buf, 8);
1752   return buf + 8;
1753 }
1754
1755 #if 0                   /* Currently unused, uncomment when needed.  */
1756 static char *pack_string (char *pkt, char *string);
1757
1758 static char *
1759 pack_string (char *pkt, char *string)
1760 {
1761   char ch;
1762   int len;
1763
1764   len = strlen (string);
1765   if (len > 200)
1766     len = 200;          /* Bigger than most GDB packets, junk???  */
1767   pkt = pack_hex_byte (pkt, len);
1768   while (len-- > 0)
1769     {
1770       ch = *string++;
1771       if ((ch == '\0') || (ch == '#'))
1772         ch = '*';               /* Protect encapsulation.  */
1773       *pkt++ = ch;
1774     }
1775   return pkt;
1776 }
1777 #endif /* 0 (unused) */
1778
1779 static char *
1780 unpack_string (char *src, char *dest, int length)
1781 {
1782   while (length--)
1783     *dest++ = *src++;
1784   *dest = '\0';
1785   return src;
1786 }
1787
1788 static char *
1789 pack_threadid (char *pkt, threadref *id)
1790 {
1791   char *limit;
1792   unsigned char *altid;
1793
1794   altid = (unsigned char *) id;
1795   limit = pkt + BUF_THREAD_ID_SIZE;
1796   while (pkt < limit)
1797     pkt = pack_hex_byte (pkt, *altid++);
1798   return pkt;
1799 }
1800
1801
1802 static char *
1803 unpack_threadid (char *inbuf, threadref *id)
1804 {
1805   char *altref;
1806   char *limit = inbuf + BUF_THREAD_ID_SIZE;
1807   int x, y;
1808
1809   altref = (char *) id;
1810
1811   while (inbuf < limit)
1812     {
1813       x = stubhex (*inbuf++);
1814       y = stubhex (*inbuf++);
1815       *altref++ = (x << 4) | y;
1816     }
1817   return inbuf;
1818 }
1819
1820 /* Externally, threadrefs are 64 bits but internally, they are still
1821    ints. This is due to a mismatch of specifications.  We would like
1822    to use 64bit thread references internally.  This is an adapter
1823    function.  */
1824
1825 void
1826 int_to_threadref (threadref *id, int value)
1827 {
1828   unsigned char *scan;
1829
1830   scan = (unsigned char *) id;
1831   {
1832     int i = 4;
1833     while (i--)
1834       *scan++ = 0;
1835   }
1836   *scan++ = (value >> 24) & 0xff;
1837   *scan++ = (value >> 16) & 0xff;
1838   *scan++ = (value >> 8) & 0xff;
1839   *scan++ = (value & 0xff);
1840 }
1841
1842 static int
1843 threadref_to_int (threadref *ref)
1844 {
1845   int i, value = 0;
1846   unsigned char *scan;
1847
1848   scan = *ref;
1849   scan += 4;
1850   i = 4;
1851   while (i-- > 0)
1852     value = (value << 8) | ((*scan++) & 0xff);
1853   return value;
1854 }
1855
1856 static void
1857 copy_threadref (threadref *dest, threadref *src)
1858 {
1859   int i;
1860   unsigned char *csrc, *cdest;
1861
1862   csrc = (unsigned char *) src;
1863   cdest = (unsigned char *) dest;
1864   i = 8;
1865   while (i--)
1866     *cdest++ = *csrc++;
1867 }
1868
1869 static int
1870 threadmatch (threadref *dest, threadref *src)
1871 {
1872   /* Things are broken right now, so just assume we got a match.  */
1873 #if 0
1874   unsigned char *srcp, *destp;
1875   int i, result;
1876   srcp = (char *) src;
1877   destp = (char *) dest;
1878
1879   result = 1;
1880   while (i-- > 0)
1881     result &= (*srcp++ == *destp++) ? 1 : 0;
1882   return result;
1883 #endif
1884   return 1;
1885 }
1886
1887 /*
1888    threadid:1,        # always request threadid
1889    context_exists:2,
1890    display:4,
1891    unique_name:8,
1892    more_display:16
1893  */
1894
1895 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
1896
1897 static char *
1898 pack_threadinfo_request (char *pkt, int mode, threadref *id)
1899 {
1900   *pkt++ = 'q';                         /* Info Query */
1901   *pkt++ = 'P';                         /* process or thread info */
1902   pkt = pack_int (pkt, mode);           /* mode */
1903   pkt = pack_threadid (pkt, id);        /* threadid */
1904   *pkt = '\0';                          /* terminate */
1905   return pkt;
1906 }
1907
1908 /* These values tag the fields in a thread info response packet.  */
1909 /* Tagging the fields allows us to request specific fields and to
1910    add more fields as time goes by.  */
1911
1912 #define TAG_THREADID 1          /* Echo the thread identifier.  */
1913 #define TAG_EXISTS 2            /* Is this process defined enough to
1914                                    fetch registers and its stack?  */
1915 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
1916 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
1917 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
1918                                    the process.  */
1919
1920 static int
1921 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
1922                                     struct gdb_ext_thread_info *info)
1923 {
1924   struct remote_state *rs = get_remote_state ();
1925   int mask, length;
1926   int tag;
1927   threadref ref;
1928   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
1929   int retval = 1;
1930
1931   /* info->threadid = 0; FIXME: implement zero_threadref.  */
1932   info->active = 0;
1933   info->display[0] = '\0';
1934   info->shortname[0] = '\0';
1935   info->more_display[0] = '\0';
1936
1937   /* Assume the characters indicating the packet type have been
1938      stripped.  */
1939   pkt = unpack_int (pkt, &mask);        /* arg mask */
1940   pkt = unpack_threadid (pkt, &ref);
1941
1942   if (mask == 0)
1943     warning (_("Incomplete response to threadinfo request."));
1944   if (!threadmatch (&ref, expectedref))
1945     {                   /* This is an answer to a different request.  */
1946       warning (_("ERROR RMT Thread info mismatch."));
1947       return 0;
1948     }
1949   copy_threadref (&info->threadid, &ref);
1950
1951   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
1952
1953   /* Packets are terminated with nulls.  */
1954   while ((pkt < limit) && mask && *pkt)
1955     {
1956       pkt = unpack_int (pkt, &tag);     /* tag */
1957       pkt = unpack_byte (pkt, &length); /* length */
1958       if (!(tag & mask))                /* Tags out of synch with mask.  */
1959         {
1960           warning (_("ERROR RMT: threadinfo tag mismatch."));
1961           retval = 0;
1962           break;
1963         }
1964       if (tag == TAG_THREADID)
1965         {
1966           if (length != 16)
1967             {
1968               warning (_("ERROR RMT: length of threadid is not 16."));
1969               retval = 0;
1970               break;
1971             }
1972           pkt = unpack_threadid (pkt, &ref);
1973           mask = mask & ~TAG_THREADID;
1974           continue;
1975         }
1976       if (tag == TAG_EXISTS)
1977         {
1978           info->active = stub_unpack_int (pkt, length);
1979           pkt += length;
1980           mask = mask & ~(TAG_EXISTS);
1981           if (length > 8)
1982             {
1983               warning (_("ERROR RMT: 'exists' length too long."));
1984               retval = 0;
1985               break;
1986             }
1987           continue;
1988         }
1989       if (tag == TAG_THREADNAME)
1990         {
1991           pkt = unpack_string (pkt, &info->shortname[0], length);
1992           mask = mask & ~TAG_THREADNAME;
1993           continue;
1994         }
1995       if (tag == TAG_DISPLAY)
1996         {
1997           pkt = unpack_string (pkt, &info->display[0], length);
1998           mask = mask & ~TAG_DISPLAY;
1999           continue;
2000         }
2001       if (tag == TAG_MOREDISPLAY)
2002         {
2003           pkt = unpack_string (pkt, &info->more_display[0], length);
2004           mask = mask & ~TAG_MOREDISPLAY;
2005           continue;
2006         }
2007       warning (_("ERROR RMT: unknown thread info tag."));
2008       break;                    /* Not a tag we know about.  */
2009     }
2010   return retval;
2011 }
2012
2013 static int
2014 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2015                        struct gdb_ext_thread_info *info)
2016 {
2017   struct remote_state *rs = get_remote_state ();
2018   int result;
2019
2020   pack_threadinfo_request (rs->buf, fieldset, threadid);
2021   putpkt (rs->buf);
2022   getpkt (&rs->buf, &rs->buf_size, 0);
2023
2024   if (rs->buf[0] == '\0')
2025     return 0;
2026
2027   result = remote_unpack_thread_info_response (rs->buf + 2,
2028                                                threadid, info);
2029   return result;
2030 }
2031
2032 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2033
2034 static char *
2035 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2036                          threadref *nextthread)
2037 {
2038   *pkt++ = 'q';                 /* info query packet */
2039   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2040   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2041   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2042   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2043   *pkt = '\0';
2044   return pkt;
2045 }
2046
2047 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2048
2049 static int
2050 parse_threadlist_response (char *pkt, int result_limit,
2051                            threadref *original_echo, threadref *resultlist,
2052                            int *doneflag)
2053 {
2054   struct remote_state *rs = get_remote_state ();
2055   char *limit;
2056   int count, resultcount, done;
2057
2058   resultcount = 0;
2059   /* Assume the 'q' and 'M chars have been stripped.  */
2060   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2061   /* done parse past here */
2062   pkt = unpack_byte (pkt, &count);      /* count field */
2063   pkt = unpack_nibble (pkt, &done);
2064   /* The first threadid is the argument threadid.  */
2065   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2066   while ((count-- > 0) && (pkt < limit))
2067     {
2068       pkt = unpack_threadid (pkt, resultlist++);
2069       if (resultcount++ >= result_limit)
2070         break;
2071     }
2072   if (doneflag)
2073     *doneflag = done;
2074   return resultcount;
2075 }
2076
2077 static int
2078 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2079                        int *done, int *result_count, threadref *threadlist)
2080 {
2081   struct remote_state *rs = get_remote_state ();
2082   static threadref echo_nextthread;
2083   int result = 1;
2084
2085   /* Trancate result limit to be smaller than the packet size.  */
2086   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10) >= get_remote_packet_size ())
2087     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2088
2089   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2090   putpkt (rs->buf);
2091   getpkt (&rs->buf, &rs->buf_size, 0);
2092
2093   if (*rs->buf == '\0')
2094     *result_count = 0;
2095   else
2096     *result_count =
2097       parse_threadlist_response (rs->buf + 2, result_limit, &echo_nextthread,
2098                                  threadlist, done);
2099
2100   if (!threadmatch (&echo_nextthread, nextthread))
2101     {
2102       /* FIXME: This is a good reason to drop the packet.  */
2103       /* Possably, there is a duplicate response.  */
2104       /* Possabilities :
2105          retransmit immediatly - race conditions
2106          retransmit after timeout - yes
2107          exit
2108          wait for packet, then exit
2109        */
2110       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2111       return 0;                 /* I choose simply exiting.  */
2112     }
2113   if (*result_count <= 0)
2114     {
2115       if (*done != 1)
2116         {
2117           warning (_("RMT ERROR : failed to get remote thread list."));
2118           result = 0;
2119         }
2120       return result;            /* break; */
2121     }
2122   if (*result_count > result_limit)
2123     {
2124       *result_count = 0;
2125       warning (_("RMT ERROR: threadlist response longer than requested."));
2126       return 0;
2127     }
2128   return result;
2129 }
2130
2131 /* This is the interface between remote and threads, remotes upper
2132    interface.  */
2133
2134 /* remote_find_new_threads retrieves the thread list and for each
2135    thread in the list, looks up the thread in GDB's internal list,
2136    adding the thread if it does not already exist.  This involves
2137    getting partial thread lists from the remote target so, polling the
2138    quit_flag is required.  */
2139
2140
2141 /* About this many threadisds fit in a packet.  */
2142
2143 #define MAXTHREADLISTRESULTS 32
2144
2145 static int
2146 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2147                             int looplimit)
2148 {
2149   int done, i, result_count;
2150   int startflag = 1;
2151   int result = 1;
2152   int loopcount = 0;
2153   static threadref nextthread;
2154   static threadref resultthreadlist[MAXTHREADLISTRESULTS];
2155
2156   done = 0;
2157   while (!done)
2158     {
2159       if (loopcount++ > looplimit)
2160         {
2161           result = 0;
2162           warning (_("Remote fetch threadlist -infinite loop-."));
2163           break;
2164         }
2165       if (!remote_get_threadlist (startflag, &nextthread, MAXTHREADLISTRESULTS,
2166                                   &done, &result_count, resultthreadlist))
2167         {
2168           result = 0;
2169           break;
2170         }
2171       /* Clear for later iterations.  */
2172       startflag = 0;
2173       /* Setup to resume next batch of thread references, set nextthread.  */
2174       if (result_count >= 1)
2175         copy_threadref (&nextthread, &resultthreadlist[result_count - 1]);
2176       i = 0;
2177       while (result_count--)
2178         if (!(result = (*stepfunction) (&resultthreadlist[i++], context)))
2179           break;
2180     }
2181   return result;
2182 }
2183
2184 static int
2185 remote_newthread_step (threadref *ref, void *context)
2186 {
2187   int pid = ptid_get_pid (inferior_ptid);
2188   ptid_t ptid = ptid_build (pid, 0, threadref_to_int (ref));
2189
2190   if (!in_thread_list (ptid))
2191     add_thread (ptid);
2192   return 1;                     /* continue iterator */
2193 }
2194
2195 #define CRAZY_MAX_THREADS 1000
2196
2197 static ptid_t
2198 remote_current_thread (ptid_t oldpid)
2199 {
2200   struct remote_state *rs = get_remote_state ();
2201   char *p = rs->buf;
2202   int tid;
2203   int pid;
2204
2205   putpkt ("qC");
2206   getpkt (&rs->buf, &rs->buf_size, 0);
2207   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2208     return read_ptid (&rs->buf[2], NULL);
2209   else
2210     return oldpid;
2211 }
2212
2213 /* Find new threads for info threads command.
2214  * Original version, using John Metzler's thread protocol.
2215  */
2216
2217 static void
2218 remote_find_new_threads (void)
2219 {
2220   remote_threadlist_iterator (remote_newthread_step, 0,
2221                               CRAZY_MAX_THREADS);
2222 }
2223
2224 /*
2225  * Find all threads for info threads command.
2226  * Uses new thread protocol contributed by Cisco.
2227  * Falls back and attempts to use the older method (above)
2228  * if the target doesn't respond to the new method.
2229  */
2230
2231 static void
2232 remote_threads_info (struct target_ops *ops)
2233 {
2234   struct remote_state *rs = get_remote_state ();
2235   char *bufp;
2236   ptid_t new_thread;
2237
2238   if (remote_desc == 0)         /* paranoia */
2239     error (_("Command can only be used when connected to the remote target."));
2240
2241   if (use_threadinfo_query)
2242     {
2243       putpkt ("qfThreadInfo");
2244       getpkt (&rs->buf, &rs->buf_size, 0);
2245       bufp = rs->buf;
2246       if (bufp[0] != '\0')              /* q packet recognized */
2247         {
2248           while (*bufp++ == 'm')        /* reply contains one or more TID */
2249             {
2250               do
2251                 {
2252                   new_thread = read_ptid (bufp, &bufp);
2253                   if (!ptid_equal (new_thread, null_ptid))
2254                     {
2255                       /* In non-stop mode, we assume new found threads
2256                          are running until proven otherwise with a
2257                          stop reply.  In all-stop, we can only get
2258                          here if all threads are stopped.  */
2259                       int running = non_stop ? 1 : 0;
2260
2261                       remote_notice_new_inferior (new_thread, running);
2262                     }
2263                 }
2264               while (*bufp++ == ',');   /* comma-separated list */
2265               putpkt ("qsThreadInfo");
2266               getpkt (&rs->buf, &rs->buf_size, 0);
2267               bufp = rs->buf;
2268             }
2269           return;       /* done */
2270         }
2271     }
2272
2273   /* Only qfThreadInfo is supported in non-stop mode.  */
2274   if (non_stop)
2275     return;
2276
2277   /* Else fall back to old method based on jmetzler protocol.  */
2278   use_threadinfo_query = 0;
2279   remote_find_new_threads ();
2280   return;
2281 }
2282
2283 /*
2284  * Collect a descriptive string about the given thread.
2285  * The target may say anything it wants to about the thread
2286  * (typically info about its blocked / runnable state, name, etc.).
2287  * This string will appear in the info threads display.
2288  *
2289  * Optional: targets are not required to implement this function.
2290  */
2291
2292 static char *
2293 remote_threads_extra_info (struct thread_info *tp)
2294 {
2295   struct remote_state *rs = get_remote_state ();
2296   int result;
2297   int set;
2298   threadref id;
2299   struct gdb_ext_thread_info threadinfo;
2300   static char display_buf[100]; /* arbitrary...  */
2301   int n = 0;                    /* position in display_buf */
2302
2303   if (remote_desc == 0)         /* paranoia */
2304     internal_error (__FILE__, __LINE__,
2305                     _("remote_threads_extra_info"));
2306
2307   if (ptid_equal (tp->ptid, magic_null_ptid)
2308       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_tid (tp->ptid) == 0))
2309     /* This is the main thread which was added by GDB.  The remote
2310        server doesn't know about it.  */
2311     return NULL;
2312
2313   if (use_threadextra_query)
2314     {
2315       char *b = rs->buf;
2316       char *endb = rs->buf + get_remote_packet_size ();
2317
2318       xsnprintf (b, endb - b, "qThreadExtraInfo,");
2319       b += strlen (b);
2320       write_ptid (b, endb, tp->ptid);
2321
2322       putpkt (rs->buf);
2323       getpkt (&rs->buf, &rs->buf_size, 0);
2324       if (rs->buf[0] != 0)
2325         {
2326           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
2327           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
2328           display_buf [result] = '\0';
2329           return display_buf;
2330         }
2331     }
2332
2333   /* If the above query fails, fall back to the old method.  */
2334   use_threadextra_query = 0;
2335   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
2336     | TAG_MOREDISPLAY | TAG_DISPLAY;
2337   int_to_threadref (&id, ptid_get_tid (tp->ptid));
2338   if (remote_get_threadinfo (&id, set, &threadinfo))
2339     if (threadinfo.active)
2340       {
2341         if (*threadinfo.shortname)
2342           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
2343                           " Name: %s,", threadinfo.shortname);
2344         if (*threadinfo.display)
2345           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2346                           " State: %s,", threadinfo.display);
2347         if (*threadinfo.more_display)
2348           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
2349                           " Priority: %s", threadinfo.more_display);
2350
2351         if (n > 0)
2352           {
2353             /* For purely cosmetic reasons, clear up trailing commas.  */
2354             if (',' == display_buf[n-1])
2355               display_buf[n-1] = ' ';
2356             return display_buf;
2357           }
2358       }
2359   return NULL;
2360 }
2361 \f
2362
2363 /* Restart the remote side; this is an extended protocol operation.  */
2364
2365 static void
2366 extended_remote_restart (void)
2367 {
2368   struct remote_state *rs = get_remote_state ();
2369
2370   /* Send the restart command; for reasons I don't understand the
2371      remote side really expects a number after the "R".  */
2372   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
2373   putpkt (rs->buf);
2374
2375   remote_fileio_reset ();
2376 }
2377 \f
2378 /* Clean up connection to a remote debugger.  */
2379
2380 static void
2381 remote_close (int quitting)
2382 {
2383   if (remote_desc == NULL)
2384     return; /* already closed */
2385
2386   /* Make sure we leave stdin registered in the event loop, and we
2387      don't leave the async SIGINT signal handler installed.  */
2388   remote_terminal_ours ();
2389
2390   serial_close (remote_desc);
2391   remote_desc = NULL;
2392
2393   /* We don't have a connection to the remote stub anymore.  Get rid
2394      of all the inferiors and their threads we were controlling.  */
2395   discard_all_inferiors ();
2396
2397   /* We're no longer interested in any of these events.  */
2398   discard_pending_stop_replies (-1);
2399
2400   if (remote_async_inferior_event_token)
2401     delete_async_event_handler (&remote_async_inferior_event_token);
2402   if (remote_async_get_pending_events_token)
2403     delete_async_event_handler (&remote_async_get_pending_events_token);
2404 }
2405
2406 /* Query the remote side for the text, data and bss offsets.  */
2407
2408 static void
2409 get_offsets (void)
2410 {
2411   struct remote_state *rs = get_remote_state ();
2412   char *buf;
2413   char *ptr;
2414   int lose, num_segments = 0, do_sections, do_segments;
2415   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
2416   struct section_offsets *offs;
2417   struct symfile_segment_data *data;
2418
2419   if (symfile_objfile == NULL)
2420     return;
2421
2422   putpkt ("qOffsets");
2423   getpkt (&rs->buf, &rs->buf_size, 0);
2424   buf = rs->buf;
2425
2426   if (buf[0] == '\000')
2427     return;                     /* Return silently.  Stub doesn't support
2428                                    this command.  */
2429   if (buf[0] == 'E')
2430     {
2431       warning (_("Remote failure reply: %s"), buf);
2432       return;
2433     }
2434
2435   /* Pick up each field in turn.  This used to be done with scanf, but
2436      scanf will make trouble if CORE_ADDR size doesn't match
2437      conversion directives correctly.  The following code will work
2438      with any size of CORE_ADDR.  */
2439   text_addr = data_addr = bss_addr = 0;
2440   ptr = buf;
2441   lose = 0;
2442
2443   if (strncmp (ptr, "Text=", 5) == 0)
2444     {
2445       ptr += 5;
2446       /* Don't use strtol, could lose on big values.  */
2447       while (*ptr && *ptr != ';')
2448         text_addr = (text_addr << 4) + fromhex (*ptr++);
2449
2450       if (strncmp (ptr, ";Data=", 6) == 0)
2451         {
2452           ptr += 6;
2453           while (*ptr && *ptr != ';')
2454             data_addr = (data_addr << 4) + fromhex (*ptr++);
2455         }
2456       else
2457         lose = 1;
2458
2459       if (!lose && strncmp (ptr, ";Bss=", 5) == 0)
2460         {
2461           ptr += 5;
2462           while (*ptr && *ptr != ';')
2463             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
2464
2465           if (bss_addr != data_addr)
2466             warning (_("Target reported unsupported offsets: %s"), buf);
2467         }
2468       else
2469         lose = 1;
2470     }
2471   else if (strncmp (ptr, "TextSeg=", 8) == 0)
2472     {
2473       ptr += 8;
2474       /* Don't use strtol, could lose on big values.  */
2475       while (*ptr && *ptr != ';')
2476         text_addr = (text_addr << 4) + fromhex (*ptr++);
2477       num_segments = 1;
2478
2479       if (strncmp (ptr, ";DataSeg=", 9) == 0)
2480         {
2481           ptr += 9;
2482           while (*ptr && *ptr != ';')
2483             data_addr = (data_addr << 4) + fromhex (*ptr++);
2484           num_segments++;
2485         }
2486     }
2487   else
2488     lose = 1;
2489
2490   if (lose)
2491     error (_("Malformed response to offset query, %s"), buf);
2492   else if (*ptr != '\0')
2493     warning (_("Target reported unsupported offsets: %s"), buf);
2494
2495   offs = ((struct section_offsets *)
2496           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
2497   memcpy (offs, symfile_objfile->section_offsets,
2498           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
2499
2500   data = get_symfile_segment_data (symfile_objfile->obfd);
2501   do_segments = (data != NULL);
2502   do_sections = num_segments == 0;
2503
2504   if (num_segments > 0)
2505     {
2506       segments[0] = text_addr;
2507       segments[1] = data_addr;
2508     }
2509   /* If we have two segments, we can still try to relocate everything
2510      by assuming that the .text and .data offsets apply to the whole
2511      text and data segments.  Convert the offsets given in the packet
2512      to base addresses for symfile_map_offsets_to_segments.  */
2513   else if (data && data->num_segments == 2)
2514     {
2515       segments[0] = data->segment_bases[0] + text_addr;
2516       segments[1] = data->segment_bases[1] + data_addr;
2517       num_segments = 2;
2518     }
2519   /* If the object file has only one segment, assume that it is text
2520      rather than data; main programs with no writable data are rare,
2521      but programs with no code are useless.  Of course the code might
2522      have ended up in the data segment... to detect that we would need
2523      the permissions here.  */
2524   else if (data && data->num_segments == 1)
2525     {
2526       segments[0] = data->segment_bases[0] + text_addr;
2527       num_segments = 1;
2528     }
2529   /* There's no way to relocate by segment.  */
2530   else
2531     do_segments = 0;
2532
2533   if (do_segments)
2534     {
2535       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
2536                                                  offs, num_segments, segments);
2537
2538       if (ret == 0 && !do_sections)
2539         error (_("Can not handle qOffsets TextSeg response with this symbol file"));
2540
2541       if (ret > 0)
2542         do_sections = 0;
2543     }
2544
2545   if (data)
2546     free_symfile_segment_data (data);
2547
2548   if (do_sections)
2549     {
2550       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
2551
2552       /* This is a temporary kludge to force data and bss to use the same offsets
2553          because that's what nlmconv does now.  The real solution requires changes
2554          to the stub and remote.c that I don't have time to do right now.  */
2555
2556       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
2557       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
2558     }
2559
2560   objfile_relocate (symfile_objfile, offs);
2561 }
2562
2563 /* Callback for iterate_over_threads.  Set the STOP_REQUESTED flags in
2564    threads we know are stopped already.  This is used during the
2565    initial remote connection in non-stop mode --- threads that are
2566    reported as already being stopped are left stopped.  */
2567
2568 static int
2569 set_stop_requested_callback (struct thread_info *thread, void *data)
2570 {
2571   /* If we have a stop reply for this thread, it must be stopped.  */
2572   if (peek_stop_reply (thread->ptid))
2573     set_stop_requested (thread->ptid, 1);
2574
2575   return 0;
2576 }
2577
2578 /* Stub for catch_exception.  */
2579
2580 struct start_remote_args
2581 {
2582   int from_tty;
2583
2584   /* The current target.  */
2585   struct target_ops *target;
2586
2587   /* Non-zero if this is an extended-remote target.  */
2588   int extended_p;
2589 };
2590
2591 static void
2592 remote_start_remote (struct ui_out *uiout, void *opaque)
2593 {
2594   struct start_remote_args *args = opaque;
2595   struct remote_state *rs = get_remote_state ();
2596   struct packet_config *noack_config;
2597   char *wait_status = NULL;
2598
2599   immediate_quit++;             /* Allow user to interrupt it.  */
2600
2601   /* Ack any packet which the remote side has already sent.  */
2602   serial_write (remote_desc, "+", 1);
2603
2604   /* The first packet we send to the target is the optional "supported
2605      packets" request.  If the target can answer this, it will tell us
2606      which later probes to skip.  */
2607   remote_query_supported ();
2608
2609   /* Next, we possibly activate noack mode.
2610
2611      If the QStartNoAckMode packet configuration is set to AUTO,
2612      enable noack mode if the stub reported a wish for it with
2613      qSupported.
2614
2615      If set to TRUE, then enable noack mode even if the stub didn't
2616      report it in qSupported.  If the stub doesn't reply OK, the
2617      session ends with an error.
2618
2619      If FALSE, then don't activate noack mode, regardless of what the
2620      stub claimed should be the default with qSupported.  */
2621
2622   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
2623
2624   if (noack_config->detect == AUTO_BOOLEAN_TRUE
2625       || (noack_config->detect == AUTO_BOOLEAN_AUTO
2626           && noack_config->support == PACKET_ENABLE))
2627     {
2628       putpkt ("QStartNoAckMode");
2629       getpkt (&rs->buf, &rs->buf_size, 0);
2630       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
2631         rs->noack_mode = 1;
2632     }
2633
2634   if (args->extended_p)
2635     {
2636       /* Tell the remote that we are using the extended protocol.  */
2637       putpkt ("!");
2638       getpkt (&rs->buf, &rs->buf_size, 0);
2639     }
2640
2641   /* Next, if the target can specify a description, read it.  We do
2642      this before anything involving memory or registers.  */
2643   target_find_description ();
2644
2645   /* On OSs where the list of libraries is global to all
2646      processes, we fetch them early.  */
2647   if (gdbarch_has_global_solist (target_gdbarch))
2648     solib_add (NULL, args->from_tty, args->target, auto_solib_add);
2649
2650   if (non_stop)
2651     {
2652       if (!rs->non_stop_aware)
2653         error (_("Non-stop mode requested, but remote does not support non-stop"));
2654
2655       putpkt ("QNonStop:1");
2656       getpkt (&rs->buf, &rs->buf_size, 0);
2657
2658       if (strcmp (rs->buf, "OK") != 0)
2659         error ("Remote refused setting non-stop mode with: %s", rs->buf);
2660
2661       /* Find about threads and processes the stub is already
2662          controlling.  We default to adding them in the running state.
2663          The '?' query below will then tell us about which threads are
2664          stopped.  */
2665       remote_threads_info (args->target);
2666     }
2667   else if (rs->non_stop_aware)
2668     {
2669       /* Don't assume that the stub can operate in all-stop mode.
2670          Request it explicitely.  */
2671       putpkt ("QNonStop:0");
2672       getpkt (&rs->buf, &rs->buf_size, 0);
2673
2674       if (strcmp (rs->buf, "OK") != 0)
2675         error ("Remote refused setting all-stop mode with: %s", rs->buf);
2676     }
2677
2678   /* Check whether the target is running now.  */
2679   putpkt ("?");
2680   getpkt (&rs->buf, &rs->buf_size, 0);
2681
2682   if (!non_stop)
2683     {
2684       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
2685         {
2686           if (!args->extended_p)
2687             error (_("The target is not running (try extended-remote?)"));
2688
2689           /* We're connected, but not running.  Drop out before we
2690              call start_remote.  */
2691           return;
2692         }
2693       else
2694         {
2695           /* Save the reply for later.  */
2696           wait_status = alloca (strlen (rs->buf) + 1);
2697           strcpy (wait_status, rs->buf);
2698         }
2699
2700       /* Let the stub know that we want it to return the thread.  */
2701       set_continue_thread (minus_one_ptid);
2702
2703       /* Without this, some commands which require an active target
2704          (such as kill) won't work.  This variable serves (at least)
2705          double duty as both the pid of the target process (if it has
2706          such), and as a flag indicating that a target is active.
2707          These functions should be split out into seperate variables,
2708          especially since GDB will someday have a notion of debugging
2709          several processes.  */
2710       inferior_ptid = magic_null_ptid;
2711
2712       /* Now, if we have thread information, update inferior_ptid.  */
2713       inferior_ptid = remote_current_thread (inferior_ptid);
2714
2715       remote_add_inferior (ptid_get_pid (inferior_ptid), -1);
2716
2717       /* Always add the main thread.  */
2718       add_thread_silent (inferior_ptid);
2719
2720       get_offsets ();           /* Get text, data & bss offsets.  */
2721
2722       /* If we could not find a description using qXfer, and we know
2723          how to do it some other way, try again.  This is not
2724          supported for non-stop; it could be, but it is tricky if
2725          there are no stopped threads when we connect.  */
2726       if (remote_read_description_p (args->target)
2727           && gdbarch_target_desc (target_gdbarch) == NULL)
2728         {
2729           target_clear_description ();
2730           target_find_description ();
2731         }
2732
2733       /* Use the previously fetched status.  */
2734       gdb_assert (wait_status != NULL);
2735       strcpy (rs->buf, wait_status);
2736       rs->cached_wait_status = 1;
2737
2738       immediate_quit--;
2739       start_remote (args->from_tty); /* Initialize gdb process mechanisms.  */
2740     }
2741   else
2742     {
2743       /* Clear WFI global state.  Do this before finding about new
2744          threads and inferiors, and setting the current inferior.
2745          Otherwise we would clear the proceed status of the current
2746          inferior when we want its stop_soon state to be preserved
2747          (see notice_new_inferior).  */
2748       init_wait_for_inferior ();
2749
2750       /* In non-stop, we will either get an "OK", meaning that there
2751          are no stopped threads at this time; or, a regular stop
2752          reply.  In the latter case, there may be more than one thread
2753          stopped --- we pull them all out using the vStopped
2754          mechanism.  */
2755       if (strcmp (rs->buf, "OK") != 0)
2756         {
2757           struct stop_reply *stop_reply;
2758           struct cleanup *old_chain;
2759
2760           stop_reply = stop_reply_xmalloc ();
2761           old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
2762
2763           remote_parse_stop_reply (rs->buf, stop_reply);
2764           discard_cleanups (old_chain);
2765
2766           /* get_pending_stop_replies acks this one, and gets the rest
2767              out.  */
2768           pending_stop_reply = stop_reply;
2769           remote_get_pending_stop_replies ();
2770
2771           /* Make sure that threads that were stopped remain
2772              stopped.  */
2773           iterate_over_threads (set_stop_requested_callback, NULL);
2774         }
2775
2776       if (target_can_async_p ())
2777         target_async (inferior_event_handler, 0);
2778
2779       if (thread_count () == 0)
2780         {
2781           if (!args->extended_p)
2782             error (_("The target is not running (try extended-remote?)"));
2783
2784           /* We're connected, but not running.  Drop out before we
2785              call start_remote.  */
2786           return;
2787         }
2788
2789       /* Let the stub know that we want it to return the thread.  */
2790
2791       /* Force the stub to choose a thread.  */
2792       set_general_thread (null_ptid);
2793
2794       /* Query it.  */
2795       inferior_ptid = remote_current_thread (minus_one_ptid);
2796       if (ptid_equal (inferior_ptid, minus_one_ptid))
2797         error (_("remote didn't report the current thread in non-stop mode"));
2798
2799       get_offsets ();           /* Get text, data & bss offsets.  */
2800
2801       /* In non-stop mode, any cached wait status will be stored in
2802          the stop reply queue.  */
2803       gdb_assert (wait_status == NULL);
2804     }
2805
2806   /* If we connected to a live target, do some additional setup.  */
2807   if (target_has_execution)
2808     {
2809       if (exec_bfd)     /* No use without an exec file.  */
2810         remote_check_symbols (symfile_objfile);
2811     }
2812
2813   /* If breakpoints are global, insert them now.  */
2814   if (gdbarch_has_global_breakpoints (target_gdbarch)
2815       && breakpoints_always_inserted_mode ())
2816     insert_breakpoints ();
2817 }
2818
2819 /* Open a connection to a remote debugger.
2820    NAME is the filename used for communication.  */
2821
2822 static void
2823 remote_open (char *name, int from_tty)
2824 {
2825   remote_open_1 (name, from_tty, &remote_ops, 0);
2826 }
2827
2828 /* Open a connection to a remote debugger using the extended
2829    remote gdb protocol.  NAME is the filename used for communication.  */
2830
2831 static void
2832 extended_remote_open (char *name, int from_tty)
2833 {
2834   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
2835 }
2836
2837 /* Generic code for opening a connection to a remote target.  */
2838
2839 static void
2840 init_all_packet_configs (void)
2841 {
2842   int i;
2843   for (i = 0; i < PACKET_MAX; i++)
2844     update_packet_config (&remote_protocol_packets[i]);
2845 }
2846
2847 /* Symbol look-up.  */
2848
2849 static void
2850 remote_check_symbols (struct objfile *objfile)
2851 {
2852   struct remote_state *rs = get_remote_state ();
2853   char *msg, *reply, *tmp;
2854   struct minimal_symbol *sym;
2855   int end;
2856
2857   if (remote_protocol_packets[PACKET_qSymbol].support == PACKET_DISABLE)
2858     return;
2859
2860   /* Make sure the remote is pointing at the right process.  */
2861   set_general_process ();
2862
2863   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
2864      because we need both at the same time.  */
2865   msg = alloca (get_remote_packet_size ());
2866
2867   /* Invite target to request symbol lookups.  */
2868
2869   putpkt ("qSymbol::");
2870   getpkt (&rs->buf, &rs->buf_size, 0);
2871   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
2872   reply = rs->buf;
2873
2874   while (strncmp (reply, "qSymbol:", 8) == 0)
2875     {
2876       tmp = &reply[8];
2877       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
2878       msg[end] = '\0';
2879       sym = lookup_minimal_symbol (msg, NULL, NULL);
2880       if (sym == NULL)
2881         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
2882       else
2883         {
2884           int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
2885           CORE_ADDR sym_addr = SYMBOL_VALUE_ADDRESS (sym);
2886
2887           /* If this is a function address, return the start of code
2888              instead of any data function descriptor.  */
2889           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch,
2890                                                          sym_addr,
2891                                                          &current_target);
2892
2893           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
2894                      phex_nz (sym_addr, addr_size), &reply[8]);
2895         }
2896   
2897       putpkt (msg);
2898       getpkt (&rs->buf, &rs->buf_size, 0);
2899       reply = rs->buf;
2900     }
2901 }
2902
2903 static struct serial *
2904 remote_serial_open (char *name)
2905 {
2906   static int udp_warning = 0;
2907
2908   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
2909      of in ser-tcp.c, because it is the remote protocol assuming that the
2910      serial connection is reliable and not the serial connection promising
2911      to be.  */
2912   if (!udp_warning && strncmp (name, "udp:", 4) == 0)
2913     {
2914       warning (_("\
2915 The remote protocol may be unreliable over UDP.\n\
2916 Some events may be lost, rendering further debugging impossible."));
2917       udp_warning = 1;
2918     }
2919
2920   return serial_open (name);
2921 }
2922
2923 /* This type describes each known response to the qSupported
2924    packet.  */
2925 struct protocol_feature
2926 {
2927   /* The name of this protocol feature.  */
2928   const char *name;
2929
2930   /* The default for this protocol feature.  */
2931   enum packet_support default_support;
2932
2933   /* The function to call when this feature is reported, or after
2934      qSupported processing if the feature is not supported.
2935      The first argument points to this structure.  The second
2936      argument indicates whether the packet requested support be
2937      enabled, disabled, or probed (or the default, if this function
2938      is being called at the end of processing and this feature was
2939      not reported).  The third argument may be NULL; if not NULL, it
2940      is a NUL-terminated string taken from the packet following
2941      this feature's name and an equals sign.  */
2942   void (*func) (const struct protocol_feature *, enum packet_support,
2943                 const char *);
2944
2945   /* The corresponding packet for this feature.  Only used if
2946      FUNC is remote_supported_packet.  */
2947   int packet;
2948 };
2949
2950 static void
2951 remote_supported_packet (const struct protocol_feature *feature,
2952                          enum packet_support support,
2953                          const char *argument)
2954 {
2955   if (argument)
2956     {
2957       warning (_("Remote qSupported response supplied an unexpected value for"
2958                  " \"%s\"."), feature->name);
2959       return;
2960     }
2961
2962   if (remote_protocol_packets[feature->packet].support
2963       == PACKET_SUPPORT_UNKNOWN)
2964     remote_protocol_packets[feature->packet].support = support;
2965 }
2966
2967 static void
2968 remote_packet_size (const struct protocol_feature *feature,
2969                     enum packet_support support, const char *value)
2970 {
2971   struct remote_state *rs = get_remote_state ();
2972
2973   int packet_size;
2974   char *value_end;
2975
2976   if (support != PACKET_ENABLE)
2977     return;
2978
2979   if (value == NULL || *value == '\0')
2980     {
2981       warning (_("Remote target reported \"%s\" without a size."),
2982                feature->name);
2983       return;
2984     }
2985
2986   errno = 0;
2987   packet_size = strtol (value, &value_end, 16);
2988   if (errno != 0 || *value_end != '\0' || packet_size < 0)
2989     {
2990       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
2991                feature->name, value);
2992       return;
2993     }
2994
2995   if (packet_size > MAX_REMOTE_PACKET_SIZE)
2996     {
2997       warning (_("limiting remote suggested packet size (%d bytes) to %d"),
2998                packet_size, MAX_REMOTE_PACKET_SIZE);
2999       packet_size = MAX_REMOTE_PACKET_SIZE;
3000     }
3001
3002   /* Record the new maximum packet size.  */
3003   rs->explicit_packet_size = packet_size;
3004 }
3005
3006 static void
3007 remote_multi_process_feature (const struct protocol_feature *feature,
3008                               enum packet_support support, const char *value)
3009 {
3010   struct remote_state *rs = get_remote_state ();
3011   rs->multi_process_aware = (support == PACKET_ENABLE);
3012 }
3013
3014 static void
3015 remote_non_stop_feature (const struct protocol_feature *feature,
3016                               enum packet_support support, const char *value)
3017 {
3018   struct remote_state *rs = get_remote_state ();
3019   rs->non_stop_aware = (support == PACKET_ENABLE);
3020 }
3021
3022 static void
3023 remote_cond_tracepoint_feature (const struct protocol_feature *feature,
3024                                        enum packet_support support,
3025                                        const char *value)
3026 {
3027   struct remote_state *rs = get_remote_state ();
3028   rs->cond_tracepoints = (support == PACKET_ENABLE);
3029 }
3030
3031 static struct protocol_feature remote_protocol_features[] = {
3032   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
3033   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
3034     PACKET_qXfer_auxv },
3035   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
3036     PACKET_qXfer_features },
3037   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
3038     PACKET_qXfer_libraries },
3039   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
3040     PACKET_qXfer_memory_map },
3041   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
3042     PACKET_qXfer_spu_read },
3043   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
3044     PACKET_qXfer_spu_write },
3045   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
3046     PACKET_qXfer_osdata },
3047   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
3048     PACKET_QPassSignals },
3049   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
3050     PACKET_QStartNoAckMode },
3051   { "multiprocess", PACKET_DISABLE, remote_multi_process_feature, -1 },
3052   { "QNonStop", PACKET_DISABLE, remote_non_stop_feature, -1 },
3053   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
3054     PACKET_qXfer_siginfo_read },
3055   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
3056     PACKET_qXfer_siginfo_write },
3057   { "ConditionalTracepoints", PACKET_DISABLE, remote_cond_tracepoint_feature,
3058     PACKET_ConditionalTracepoints },
3059 };
3060
3061 static void
3062 remote_query_supported (void)
3063 {
3064   struct remote_state *rs = get_remote_state ();
3065   char *next;
3066   int i;
3067   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
3068
3069   /* The packet support flags are handled differently for this packet
3070      than for most others.  We treat an error, a disabled packet, and
3071      an empty response identically: any features which must be reported
3072      to be used will be automatically disabled.  An empty buffer
3073      accomplishes this, since that is also the representation for a list
3074      containing no features.  */
3075
3076   rs->buf[0] = 0;
3077   if (remote_protocol_packets[PACKET_qSupported].support != PACKET_DISABLE)
3078     {
3079       if (rs->extended)
3080         putpkt ("qSupported:multiprocess+");
3081       else
3082         putpkt ("qSupported");
3083
3084       getpkt (&rs->buf, &rs->buf_size, 0);
3085
3086       /* If an error occured, warn, but do not return - just reset the
3087          buffer to empty and go on to disable features.  */
3088       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
3089           == PACKET_ERROR)
3090         {
3091           warning (_("Remote failure reply: %s"), rs->buf);
3092           rs->buf[0] = 0;
3093         }
3094     }
3095
3096   memset (seen, 0, sizeof (seen));
3097
3098   next = rs->buf;
3099   while (*next)
3100     {
3101       enum packet_support is_supported;
3102       char *p, *end, *name_end, *value;
3103
3104       /* First separate out this item from the rest of the packet.  If
3105          there's another item after this, we overwrite the separator
3106          (terminated strings are much easier to work with).  */
3107       p = next;
3108       end = strchr (p, ';');
3109       if (end == NULL)
3110         {
3111           end = p + strlen (p);
3112           next = end;
3113         }
3114       else
3115         {
3116           *end = '\0';
3117           next = end + 1;
3118
3119           if (end == p)
3120             {
3121               warning (_("empty item in \"qSupported\" response"));
3122               continue;
3123             }
3124         }
3125
3126       name_end = strchr (p, '=');
3127       if (name_end)
3128         {
3129           /* This is a name=value entry.  */
3130           is_supported = PACKET_ENABLE;
3131           value = name_end + 1;
3132           *name_end = '\0';
3133         }
3134       else
3135         {
3136           value = NULL;
3137           switch (end[-1])
3138             {
3139             case '+':
3140               is_supported = PACKET_ENABLE;
3141               break;
3142
3143             case '-':
3144               is_supported = PACKET_DISABLE;
3145               break;
3146
3147             case '?':
3148               is_supported = PACKET_SUPPORT_UNKNOWN;
3149               break;
3150
3151             default:
3152               warning (_("unrecognized item \"%s\" in \"qSupported\" response"), p);
3153               continue;
3154             }
3155           end[-1] = '\0';
3156         }
3157
3158       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3159         if (strcmp (remote_protocol_features[i].name, p) == 0)
3160           {
3161             const struct protocol_feature *feature;
3162
3163             seen[i] = 1;
3164             feature = &remote_protocol_features[i];
3165             feature->func (feature, is_supported, value);
3166             break;
3167           }
3168     }
3169
3170   /* If we increased the packet size, make sure to increase the global
3171      buffer size also.  We delay this until after parsing the entire
3172      qSupported packet, because this is the same buffer we were
3173      parsing.  */
3174   if (rs->buf_size < rs->explicit_packet_size)
3175     {
3176       rs->buf_size = rs->explicit_packet_size;
3177       rs->buf = xrealloc (rs->buf, rs->buf_size);
3178     }
3179
3180   /* Handle the defaults for unmentioned features.  */
3181   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
3182     if (!seen[i])
3183       {
3184         const struct protocol_feature *feature;
3185
3186         feature = &remote_protocol_features[i];
3187         feature->func (feature, feature->default_support, NULL);
3188       }
3189 }
3190
3191
3192 static void
3193 remote_open_1 (char *name, int from_tty, struct target_ops *target, int extended_p)
3194 {
3195   struct remote_state *rs = get_remote_state ();
3196
3197   if (name == 0)
3198     error (_("To open a remote debug connection, you need to specify what\n"
3199            "serial device is attached to the remote system\n"
3200            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
3201
3202   /* See FIXME above.  */
3203   if (!target_async_permitted)
3204     wait_forever_enabled_p = 1;
3205
3206   /* If we're connected to a running target, target_preopen will kill it.
3207      But if we're connected to a target system with no running process,
3208      then we will still be connected when it returns.  Ask this question
3209      first, before target_preopen has a chance to kill anything.  */
3210   if (remote_desc != NULL && !have_inferiors ())
3211     {
3212       if (!from_tty
3213           || query (_("Already connected to a remote target.  Disconnect? ")))
3214         pop_target ();
3215       else
3216         error (_("Still connected."));
3217     }
3218
3219   target_preopen (from_tty);
3220
3221   unpush_target (target);
3222
3223   /* This time without a query.  If we were connected to an
3224      extended-remote target and target_preopen killed the running
3225      process, we may still be connected.  If we are starting "target
3226      remote" now, the extended-remote target will not have been
3227      removed by unpush_target.  */
3228   if (remote_desc != NULL && !have_inferiors ())
3229     pop_target ();
3230
3231   /* Make sure we send the passed signals list the next time we resume.  */
3232   xfree (last_pass_packet);
3233   last_pass_packet = NULL;
3234
3235   remote_fileio_reset ();
3236   reopen_exec_file ();
3237   reread_symbols ();
3238
3239   remote_desc = remote_serial_open (name);
3240   if (!remote_desc)
3241     perror_with_name (name);
3242
3243   if (baud_rate != -1)
3244     {
3245       if (serial_setbaudrate (remote_desc, baud_rate))
3246         {
3247           /* The requested speed could not be set.  Error out to
3248              top level after closing remote_desc.  Take care to
3249              set remote_desc to NULL to avoid closing remote_desc
3250              more than once.  */
3251           serial_close (remote_desc);
3252           remote_desc = NULL;
3253           perror_with_name (name);
3254         }
3255     }
3256
3257   serial_raw (remote_desc);
3258
3259   /* If there is something sitting in the buffer we might take it as a
3260      response to a command, which would be bad.  */
3261   serial_flush_input (remote_desc);
3262
3263   if (from_tty)
3264     {
3265       puts_filtered ("Remote debugging using ");
3266       puts_filtered (name);
3267       puts_filtered ("\n");
3268     }
3269   push_target (target);         /* Switch to using remote target now.  */
3270
3271   /* Register extra event sources in the event loop.  */
3272   remote_async_inferior_event_token
3273     = create_async_event_handler (remote_async_inferior_event_handler,
3274                                   NULL);
3275   remote_async_get_pending_events_token
3276     = create_async_event_handler (remote_async_get_pending_events_handler,
3277                                   NULL);
3278
3279   /* Reset the target state; these things will be queried either by
3280      remote_query_supported or as they are needed.  */
3281   init_all_packet_configs ();
3282   rs->cached_wait_status = 0;
3283   rs->explicit_packet_size = 0;
3284   rs->noack_mode = 0;
3285   rs->multi_process_aware = 0;
3286   rs->extended = extended_p;
3287   rs->non_stop_aware = 0;
3288   rs->waiting_for_stop_reply = 0;
3289
3290   general_thread = not_sent_ptid;
3291   continue_thread = not_sent_ptid;
3292
3293   /* Probe for ability to use "ThreadInfo" query, as required.  */
3294   use_threadinfo_query = 1;
3295   use_threadextra_query = 1;
3296
3297   if (target_async_permitted)
3298     {
3299       /* With this target we start out by owning the terminal.  */
3300       remote_async_terminal_ours_p = 1;
3301
3302       /* FIXME: cagney/1999-09-23: During the initial connection it is
3303          assumed that the target is already ready and able to respond to
3304          requests. Unfortunately remote_start_remote() eventually calls
3305          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
3306          around this. Eventually a mechanism that allows
3307          wait_for_inferior() to expect/get timeouts will be
3308          implemented.  */
3309       wait_forever_enabled_p = 0;
3310     }
3311
3312   /* First delete any symbols previously loaded from shared libraries.  */
3313   no_shared_libraries (NULL, 0);
3314
3315   /* Start afresh.  */
3316   init_thread_list ();
3317
3318   /* Start the remote connection.  If error() or QUIT, discard this
3319      target (we'd otherwise be in an inconsistent state) and then
3320      propogate the error on up the exception chain.  This ensures that
3321      the caller doesn't stumble along blindly assuming that the
3322      function succeeded.  The CLI doesn't have this problem but other
3323      UI's, such as MI do.
3324
3325      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
3326      this function should return an error indication letting the
3327      caller restore the previous state.  Unfortunately the command
3328      ``target remote'' is directly wired to this function making that
3329      impossible.  On a positive note, the CLI side of this problem has
3330      been fixed - the function set_cmd_context() makes it possible for
3331      all the ``target ....'' commands to share a common callback
3332      function.  See cli-dump.c.  */
3333   {
3334     struct gdb_exception ex;
3335     struct start_remote_args args;
3336
3337     args.from_tty = from_tty;
3338     args.target = target;
3339     args.extended_p = extended_p;
3340
3341     ex = catch_exception (uiout, remote_start_remote, &args, RETURN_MASK_ALL);
3342     if (ex.reason < 0)
3343       {
3344         /* Pop the partially set up target - unless something else did
3345            already before throwing the exception.  */
3346         if (remote_desc != NULL)
3347           pop_target ();
3348         if (target_async_permitted)
3349           wait_forever_enabled_p = 1;
3350         throw_exception (ex);
3351       }
3352   }
3353
3354   if (target_async_permitted)
3355     wait_forever_enabled_p = 1;
3356 }
3357
3358 /* This takes a program previously attached to and detaches it.  After
3359    this is done, GDB can be used to debug some other program.  We
3360    better not have left any breakpoints in the target program or it'll
3361    die when it hits one.  */
3362
3363 static void
3364 remote_detach_1 (char *args, int from_tty, int extended)
3365 {
3366   int pid = ptid_get_pid (inferior_ptid);
3367   struct remote_state *rs = get_remote_state ();
3368
3369   if (args)
3370     error (_("Argument given to \"detach\" when remotely debugging."));
3371
3372   if (!target_has_execution)
3373     error (_("No process to detach from."));
3374
3375   /* Tell the remote target to detach.  */
3376   if (remote_multi_process_p (rs))
3377     sprintf (rs->buf, "D;%x", pid);
3378   else
3379     strcpy (rs->buf, "D");
3380
3381   putpkt (rs->buf);
3382   getpkt (&rs->buf, &rs->buf_size, 0);
3383
3384   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
3385     ;
3386   else if (rs->buf[0] == '\0')
3387     error (_("Remote doesn't know how to detach"));
3388   else
3389     error (_("Can't detach process."));
3390
3391   if (from_tty)
3392     {
3393       if (remote_multi_process_p (rs))
3394         printf_filtered (_("Detached from remote %s.\n"),
3395                          target_pid_to_str (pid_to_ptid (pid)));
3396       else
3397         {
3398           if (extended)
3399             puts_filtered (_("Detached from remote process.\n"));
3400           else
3401             puts_filtered (_("Ending remote debugging.\n"));
3402         }
3403     }
3404
3405   discard_pending_stop_replies (pid);
3406   target_mourn_inferior ();
3407 }
3408
3409 static void
3410 remote_detach (struct target_ops *ops, char *args, int from_tty)
3411 {
3412   remote_detach_1 (args, from_tty, 0);
3413 }
3414
3415 static void
3416 extended_remote_detach (struct target_ops *ops, char *args, int from_tty)
3417 {
3418   remote_detach_1 (args, from_tty, 1);
3419 }
3420
3421 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
3422
3423 static void
3424 remote_disconnect (struct target_ops *target, char *args, int from_tty)
3425 {
3426   if (args)
3427     error (_("Argument given to \"disconnect\" when remotely debugging."));
3428
3429   /* Make sure we unpush even the extended remote targets; mourn
3430      won't do it.  So call remote_mourn_1 directly instead of
3431      target_mourn_inferior.  */
3432   remote_mourn_1 (target);
3433
3434   if (from_tty)
3435     puts_filtered ("Ending remote debugging.\n");
3436 }
3437
3438 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
3439    be chatty about it.  */
3440
3441 static void
3442 extended_remote_attach_1 (struct target_ops *target, char *args, int from_tty)
3443 {
3444   struct remote_state *rs = get_remote_state ();
3445   int pid;
3446   char *dummy;
3447   char *wait_status = NULL;
3448
3449   if (!args)
3450     error_no_arg (_("process-id to attach"));
3451
3452   dummy = args;
3453   pid = strtol (args, &dummy, 0);
3454   /* Some targets don't set errno on errors, grrr!  */
3455   if (pid == 0 && args == dummy)
3456     error (_("Illegal process-id: %s."), args);
3457
3458   if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3459     error (_("This target does not support attaching to a process"));
3460
3461   sprintf (rs->buf, "vAttach;%x", pid);
3462   putpkt (rs->buf);
3463   getpkt (&rs->buf, &rs->buf_size, 0);
3464
3465   if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vAttach]) == PACKET_OK)
3466     {
3467       if (from_tty)
3468         printf_unfiltered (_("Attached to %s\n"),
3469                            target_pid_to_str (pid_to_ptid (pid)));
3470
3471       if (!non_stop)
3472         {
3473           /* Save the reply for later.  */
3474           wait_status = alloca (strlen (rs->buf) + 1);
3475           strcpy (wait_status, rs->buf);
3476         }
3477       else if (strcmp (rs->buf, "OK") != 0)
3478         error (_("Attaching to %s failed with: %s"),
3479                target_pid_to_str (pid_to_ptid (pid)),
3480                rs->buf);
3481     }
3482   else if (remote_protocol_packets[PACKET_vAttach].support == PACKET_DISABLE)
3483     error (_("This target does not support attaching to a process"));
3484   else
3485     error (_("Attaching to %s failed"),
3486            target_pid_to_str (pid_to_ptid (pid)));
3487
3488   remote_add_inferior (pid, 1);
3489
3490   inferior_ptid = pid_to_ptid (pid);
3491
3492   if (non_stop)
3493     {
3494       struct thread_info *thread;
3495
3496       /* Get list of threads.  */
3497       remote_threads_info (target);
3498
3499       thread = first_thread_of_process (pid);
3500       if (thread)
3501         inferior_ptid = thread->ptid;
3502       else
3503         inferior_ptid = pid_to_ptid (pid);
3504
3505       /* Invalidate our notion of the remote current thread.  */
3506       record_currthread (minus_one_ptid);
3507     }
3508   else
3509     {
3510       /* Now, if we have thread information, update inferior_ptid.  */
3511       inferior_ptid = remote_current_thread (inferior_ptid);
3512
3513       /* Add the main thread to the thread list.  */
3514       add_thread_silent (inferior_ptid);
3515     }
3516
3517   /* Next, if the target can specify a description, read it.  We do
3518      this before anything involving memory or registers.  */
3519   target_find_description ();
3520
3521   if (!non_stop)
3522     {
3523       /* Use the previously fetched status.  */
3524       gdb_assert (wait_status != NULL);
3525
3526       if (target_can_async_p ())
3527         {
3528           struct stop_reply *stop_reply;
3529           struct cleanup *old_chain;
3530
3531           stop_reply = stop_reply_xmalloc ();
3532           old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
3533           remote_parse_stop_reply (wait_status, stop_reply);
3534           discard_cleanups (old_chain);
3535           push_stop_reply (stop_reply);
3536
3537           target_async (inferior_event_handler, 0);
3538         }
3539       else
3540         {
3541           gdb_assert (wait_status != NULL);
3542           strcpy (rs->buf, wait_status);
3543           rs->cached_wait_status = 1;
3544         }
3545     }
3546   else
3547     gdb_assert (wait_status == NULL);
3548 }
3549
3550 static void
3551 extended_remote_attach (struct target_ops *ops, char *args, int from_tty)
3552 {
3553   extended_remote_attach_1 (ops, args, from_tty);
3554 }
3555
3556 /* Convert hex digit A to a number.  */
3557
3558 static int
3559 fromhex (int a)
3560 {
3561   if (a >= '0' && a <= '9')
3562     return a - '0';
3563   else if (a >= 'a' && a <= 'f')
3564     return a - 'a' + 10;
3565   else if (a >= 'A' && a <= 'F')
3566     return a - 'A' + 10;
3567   else
3568     error (_("Reply contains invalid hex digit %d"), a);
3569 }
3570
3571 static int
3572 hex2bin (const char *hex, gdb_byte *bin, int count)
3573 {
3574   int i;
3575
3576   for (i = 0; i < count; i++)
3577     {
3578       if (hex[0] == 0 || hex[1] == 0)
3579         {
3580           /* Hex string is short, or of uneven length.
3581              Return the count that has been converted so far.  */
3582           return i;
3583         }
3584       *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
3585       hex += 2;
3586     }
3587   return i;
3588 }
3589
3590 /* Convert number NIB to a hex digit.  */
3591
3592 static int
3593 tohex (int nib)
3594 {
3595   if (nib < 10)
3596     return '0' + nib;
3597   else
3598     return 'a' + nib - 10;
3599 }
3600
3601 static int
3602 bin2hex (const gdb_byte *bin, char *hex, int count)
3603 {
3604   int i;
3605   /* May use a length, or a nul-terminated string as input.  */
3606   if (count == 0)
3607     count = strlen ((char *) bin);
3608
3609   for (i = 0; i < count; i++)
3610     {
3611       *hex++ = tohex ((*bin >> 4) & 0xf);
3612       *hex++ = tohex (*bin++ & 0xf);
3613     }
3614   *hex = 0;
3615   return i;
3616 }
3617 \f
3618 /* Check for the availability of vCont.  This function should also check
3619    the response.  */
3620
3621 static void
3622 remote_vcont_probe (struct remote_state *rs)
3623 {
3624   char *buf;
3625
3626   strcpy (rs->buf, "vCont?");
3627   putpkt (rs->buf);
3628   getpkt (&rs->buf, &rs->buf_size, 0);
3629   buf = rs->buf;
3630
3631   /* Make sure that the features we assume are supported.  */
3632   if (strncmp (buf, "vCont", 5) == 0)
3633     {
3634       char *p = &buf[5];
3635       int support_s, support_S, support_c, support_C;
3636
3637       support_s = 0;
3638       support_S = 0;
3639       support_c = 0;
3640       support_C = 0;
3641       rs->support_vCont_t = 0;
3642       while (p && *p == ';')
3643         {
3644           p++;
3645           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
3646             support_s = 1;
3647           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
3648             support_S = 1;
3649           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
3650             support_c = 1;
3651           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
3652             support_C = 1;
3653           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
3654             rs->support_vCont_t = 1;
3655
3656           p = strchr (p, ';');
3657         }
3658
3659       /* If s, S, c, and C are not all supported, we can't use vCont.  Clearing
3660          BUF will make packet_ok disable the packet.  */
3661       if (!support_s || !support_S || !support_c || !support_C)
3662         buf[0] = 0;
3663     }
3664
3665   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
3666 }
3667
3668 /* Helper function for building "vCont" resumptions.  Write a
3669    resumption to P.  ENDP points to one-passed-the-end of the buffer
3670    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
3671    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
3672    resumed thread should be single-stepped and/or signalled.  If PTID
3673    equals minus_one_ptid, then all threads are resumed; if PTID
3674    represents a process, then all threads of the process are resumed;
3675    the thread to be stepped and/or signalled is given in the global
3676    INFERIOR_PTID.  */
3677
3678 static char *
3679 append_resumption (char *p, char *endp,
3680                    ptid_t ptid, int step, enum target_signal siggnal)
3681 {
3682   struct remote_state *rs = get_remote_state ();
3683
3684   if (step && siggnal != TARGET_SIGNAL_0)
3685     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
3686   else if (step)
3687     p += xsnprintf (p, endp - p, ";s");
3688   else if (siggnal != TARGET_SIGNAL_0)
3689     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
3690   else
3691     p += xsnprintf (p, endp - p, ";c");
3692
3693   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
3694     {
3695       ptid_t nptid;
3696
3697       /* All (-1) threads of process.  */
3698       nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
3699
3700       p += xsnprintf (p, endp - p, ":");
3701       p = write_ptid (p, endp, nptid);
3702     }
3703   else if (!ptid_equal (ptid, minus_one_ptid))
3704     {
3705       p += xsnprintf (p, endp - p, ":");
3706       p = write_ptid (p, endp, ptid);
3707     }
3708
3709   return p;
3710 }
3711
3712 /* Resume the remote inferior by using a "vCont" packet.  The thread
3713    to be resumed is PTID; STEP and SIGGNAL indicate whether the
3714    resumed thread should be single-stepped and/or signalled.  If PTID
3715    equals minus_one_ptid, then all threads are resumed; the thread to
3716    be stepped and/or signalled is given in the global INFERIOR_PTID.
3717    This function returns non-zero iff it resumes the inferior.
3718
3719    This function issues a strict subset of all possible vCont commands at the
3720    moment.  */
3721
3722 static int
3723 remote_vcont_resume (ptid_t ptid, int step, enum target_signal siggnal)
3724 {
3725   struct remote_state *rs = get_remote_state ();
3726   char *p;
3727   char *endp;
3728
3729   if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3730     remote_vcont_probe (rs);
3731
3732   if (remote_protocol_packets[PACKET_vCont].support == PACKET_DISABLE)
3733     return 0;
3734
3735   p = rs->buf;
3736   endp = rs->buf + get_remote_packet_size ();
3737
3738   /* If we could generate a wider range of packets, we'd have to worry
3739      about overflowing BUF.  Should there be a generic
3740      "multi-part-packet" packet?  */
3741
3742   p += xsnprintf (p, endp - p, "vCont");
3743
3744   if (ptid_equal (ptid, magic_null_ptid))
3745     {
3746       /* MAGIC_NULL_PTID means that we don't have any active threads,
3747          so we don't have any TID numbers the inferior will
3748          understand.  Make sure to only send forms that do not specify
3749          a TID.  */
3750       p = append_resumption (p, endp, minus_one_ptid, step, siggnal);
3751     }
3752   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
3753     {
3754       /* Resume all threads (of all processes, or of a single
3755          process), with preference for INFERIOR_PTID.  This assumes
3756          inferior_ptid belongs to the set of all threads we are about
3757          to resume.  */
3758       if (step || siggnal != TARGET_SIGNAL_0)
3759         {
3760           /* Step inferior_ptid, with or without signal.  */
3761           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
3762         }
3763
3764       /* And continue others without a signal.  */
3765       p = append_resumption (p, endp, ptid, /*step=*/ 0, TARGET_SIGNAL_0);
3766     }
3767   else
3768     {
3769       /* Scheduler locking; resume only PTID.  */
3770       p = append_resumption (p, endp, ptid, step, siggnal);
3771     }
3772
3773   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
3774   putpkt (rs->buf);
3775
3776   if (non_stop)
3777     {
3778       /* In non-stop, the stub replies to vCont with "OK".  The stop
3779          reply will be reported asynchronously by means of a `%Stop'
3780          notification.  */
3781       getpkt (&rs->buf, &rs->buf_size, 0);
3782       if (strcmp (rs->buf, "OK") != 0)
3783         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
3784     }
3785
3786   return 1;
3787 }
3788
3789 /* Tell the remote machine to resume.  */
3790
3791 static enum target_signal last_sent_signal = TARGET_SIGNAL_0;
3792
3793 static int last_sent_step;
3794
3795 static void
3796 remote_resume (struct target_ops *ops,
3797                ptid_t ptid, int step, enum target_signal siggnal)
3798 {
3799   struct remote_state *rs = get_remote_state ();
3800   char *buf;
3801
3802   last_sent_signal = siggnal;
3803   last_sent_step = step;
3804
3805   /* Update the inferior on signals to silently pass, if they've changed.  */
3806   remote_pass_signals ();
3807
3808   /* The vCont packet doesn't need to specify threads via Hc.  */
3809   if (remote_vcont_resume (ptid, step, siggnal))
3810     goto done;
3811
3812   /* All other supported resume packets do use Hc, so set the continue
3813      thread.  */
3814   if (ptid_equal (ptid, minus_one_ptid))
3815     set_continue_thread (any_thread_ptid);
3816   else
3817     set_continue_thread (ptid);
3818
3819   buf = rs->buf;
3820   if (execution_direction == EXEC_REVERSE)
3821     {
3822       /* We don't pass signals to the target in reverse exec mode.  */
3823       if (info_verbose && siggnal != TARGET_SIGNAL_0)
3824         warning (" - Can't pass signal %d to target in reverse: ignored.\n",
3825                  siggnal);
3826       strcpy (buf, step ? "bs" : "bc");
3827     }
3828   else if (siggnal != TARGET_SIGNAL_0)
3829     {
3830       buf[0] = step ? 'S' : 'C';
3831       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
3832       buf[2] = tohex (((int) siggnal) & 0xf);
3833       buf[3] = '\0';
3834     }
3835   else
3836     strcpy (buf, step ? "s" : "c");
3837
3838   putpkt (buf);
3839
3840  done:
3841   /* We are about to start executing the inferior, let's register it
3842      with the event loop. NOTE: this is the one place where all the
3843      execution commands end up. We could alternatively do this in each
3844      of the execution commands in infcmd.c.  */
3845   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
3846      into infcmd.c in order to allow inferior function calls to work
3847      NOT asynchronously.  */
3848   if (target_can_async_p ())
3849     target_async (inferior_event_handler, 0);
3850
3851   /* We've just told the target to resume.  The remote server will
3852      wait for the inferior to stop, and then send a stop reply.  In
3853      the mean time, we can't start another command/query ourselves
3854      because the stub wouldn't be ready to process it.  This applies
3855      only to the base all-stop protocol, however.  In non-stop (which
3856      only supports vCont), the stub replies with an "OK", and is
3857      immediate able to process further serial input.  */
3858   if (!non_stop)
3859     rs->waiting_for_stop_reply = 1;
3860 }
3861 \f
3862
3863 /* Set up the signal handler for SIGINT, while the target is
3864    executing, ovewriting the 'regular' SIGINT signal handler.  */
3865 static void
3866 initialize_sigint_signal_handler (void)
3867 {
3868   signal (SIGINT, handle_remote_sigint);
3869 }
3870
3871 /* Signal handler for SIGINT, while the target is executing.  */
3872 static void
3873 handle_remote_sigint (int sig)
3874 {
3875   signal (sig, handle_remote_sigint_twice);
3876   mark_async_signal_handler_wrapper (sigint_remote_token);
3877 }
3878
3879 /* Signal handler for SIGINT, installed after SIGINT has already been
3880    sent once.  It will take effect the second time that the user sends
3881    a ^C.  */
3882 static void
3883 handle_remote_sigint_twice (int sig)
3884 {
3885   signal (sig, handle_remote_sigint);
3886   mark_async_signal_handler_wrapper (sigint_remote_twice_token);
3887 }
3888
3889 /* Perform the real interruption of the target execution, in response
3890    to a ^C.  */
3891 static void
3892 async_remote_interrupt (gdb_client_data arg)
3893 {
3894   if (remote_debug)
3895     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
3896
3897   target_stop (inferior_ptid);
3898 }
3899
3900 /* Perform interrupt, if the first attempt did not succeed. Just give
3901    up on the target alltogether.  */
3902 void
3903 async_remote_interrupt_twice (gdb_client_data arg)
3904 {
3905   if (remote_debug)
3906     fprintf_unfiltered (gdb_stdlog, "remote_interrupt_twice called\n");
3907
3908   interrupt_query ();
3909 }
3910
3911 /* Reinstall the usual SIGINT handlers, after the target has
3912    stopped.  */
3913 static void
3914 cleanup_sigint_signal_handler (void *dummy)
3915 {
3916   signal (SIGINT, handle_sigint);
3917 }
3918
3919 /* Send ^C to target to halt it.  Target will respond, and send us a
3920    packet.  */
3921 static void (*ofunc) (int);
3922
3923 /* The command line interface's stop routine. This function is installed
3924    as a signal handler for SIGINT. The first time a user requests a
3925    stop, we call remote_stop to send a break or ^C. If there is no
3926    response from the target (it didn't stop when the user requested it),
3927    we ask the user if he'd like to detach from the target.  */
3928 static void
3929 remote_interrupt (int signo)
3930 {
3931   /* If this doesn't work, try more severe steps.  */
3932   signal (signo, remote_interrupt_twice);
3933
3934   gdb_call_async_signal_handler (sigint_remote_token, 1);
3935 }
3936
3937 /* The user typed ^C twice.  */
3938
3939 static void
3940 remote_interrupt_twice (int signo)
3941 {
3942   signal (signo, ofunc);
3943   gdb_call_async_signal_handler (sigint_remote_twice_token, 1);
3944   signal (signo, remote_interrupt);
3945 }
3946
3947 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
3948    thread, all threads of a remote process, or all threads of all
3949    processes.  */
3950
3951 static void
3952 remote_stop_ns (ptid_t ptid)
3953 {
3954   struct remote_state *rs = get_remote_state ();
3955   char *p = rs->buf;
3956   char *endp = rs->buf + get_remote_packet_size ();
3957   struct stop_reply *reply, *next;
3958
3959   if (remote_protocol_packets[PACKET_vCont].support == PACKET_SUPPORT_UNKNOWN)
3960     remote_vcont_probe (rs);
3961
3962   if (!rs->support_vCont_t)
3963     error (_("Remote server does not support stopping threads"));
3964
3965   if (ptid_equal (ptid, minus_one_ptid)
3966       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
3967     p += xsnprintf (p, endp - p, "vCont;t");
3968   else
3969     {
3970       ptid_t nptid;
3971
3972       p += xsnprintf (p, endp - p, "vCont;t:");
3973
3974       if (ptid_is_pid (ptid))
3975           /* All (-1) threads of process.  */
3976         nptid = ptid_build (ptid_get_pid (ptid), 0, -1);
3977       else
3978         {
3979           /* Small optimization: if we already have a stop reply for
3980              this thread, no use in telling the stub we want this
3981              stopped.  */
3982           if (peek_stop_reply (ptid))
3983             return;
3984
3985           nptid = ptid;
3986         }
3987
3988       p = write_ptid (p, endp, nptid);
3989     }
3990
3991   /* In non-stop, we get an immediate OK reply.  The stop reply will
3992      come in asynchronously by notification.  */
3993   putpkt (rs->buf);
3994   getpkt (&rs->buf, &rs->buf_size, 0);
3995   if (strcmp (rs->buf, "OK") != 0)
3996     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
3997 }
3998
3999 /* All-stop version of target_stop.  Sends a break or a ^C to stop the
4000    remote target.  It is undefined which thread of which process
4001    reports the stop.  */
4002
4003 static void
4004 remote_stop_as (ptid_t ptid)
4005 {
4006   struct remote_state *rs = get_remote_state ();
4007
4008   /* If the inferior is stopped already, but the core didn't know
4009      about it yet, just ignore the request.  The cached wait status
4010      will be collected in remote_wait.  */
4011   if (rs->cached_wait_status)
4012     return;
4013
4014   /* Send a break or a ^C, depending on user preference.  */
4015
4016   if (remote_break)
4017     serial_send_break (remote_desc);
4018   else
4019     serial_write (remote_desc, "\003", 1);
4020 }
4021
4022 /* This is the generic stop called via the target vector. When a target
4023    interrupt is requested, either by the command line or the GUI, we
4024    will eventually end up here.  */
4025
4026 static void
4027 remote_stop (ptid_t ptid)
4028 {
4029   if (remote_debug)
4030     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
4031
4032   if (non_stop)
4033     remote_stop_ns (ptid);
4034   else
4035     remote_stop_as (ptid);
4036 }
4037
4038 /* Ask the user what to do when an interrupt is received.  */
4039
4040 static void
4041 interrupt_query (void)
4042 {
4043   target_terminal_ours ();
4044
4045   if (target_can_async_p ())
4046     {
4047       signal (SIGINT, handle_sigint);
4048       deprecated_throw_reason (RETURN_QUIT);
4049     }
4050   else
4051     {
4052       if (query (_("Interrupted while waiting for the program.\n\
4053 Give up (and stop debugging it)? ")))
4054         {
4055           pop_target ();
4056           deprecated_throw_reason (RETURN_QUIT);
4057         }
4058     }
4059
4060   target_terminal_inferior ();
4061 }
4062
4063 /* Enable/disable target terminal ownership.  Most targets can use
4064    terminal groups to control terminal ownership.  Remote targets are
4065    different in that explicit transfer of ownership to/from GDB/target
4066    is required.  */
4067
4068 static void
4069 remote_terminal_inferior (void)
4070 {
4071   if (!target_async_permitted)
4072     /* Nothing to do.  */
4073     return;
4074
4075   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
4076      idempotent.  The event-loop GDB talking to an asynchronous target
4077      with a synchronous command calls this function from both
4078      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
4079      transfer the terminal to the target when it shouldn't this guard
4080      can go away.  */
4081   if (!remote_async_terminal_ours_p)
4082     return;
4083   delete_file_handler (input_fd);
4084   remote_async_terminal_ours_p = 0;
4085   initialize_sigint_signal_handler ();
4086   /* NOTE: At this point we could also register our selves as the
4087      recipient of all input.  Any characters typed could then be
4088      passed on down to the target.  */
4089 }
4090
4091 static void
4092 remote_terminal_ours (void)
4093 {
4094   if (!target_async_permitted)
4095     /* Nothing to do.  */
4096     return;
4097
4098   /* See FIXME in remote_terminal_inferior.  */
4099   if (remote_async_terminal_ours_p)
4100     return;
4101   cleanup_sigint_signal_handler (NULL);
4102   add_file_handler (input_fd, stdin_event_handler, 0);
4103   remote_async_terminal_ours_p = 1;
4104 }
4105
4106 void
4107 remote_console_output (char *msg)
4108 {
4109   char *p;
4110
4111   for (p = msg; p[0] && p[1]; p += 2)
4112     {
4113       char tb[2];
4114       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
4115       tb[0] = c;
4116       tb[1] = 0;
4117       fputs_unfiltered (tb, gdb_stdtarg);
4118     }
4119     gdb_flush (gdb_stdtarg);
4120   }
4121
4122 typedef struct cached_reg
4123 {
4124   int num;
4125   gdb_byte data[MAX_REGISTER_SIZE];
4126 } cached_reg_t;
4127
4128 DEF_VEC_O(cached_reg_t);
4129
4130 struct stop_reply
4131 {
4132   struct stop_reply *next;
4133
4134   ptid_t ptid;
4135
4136   struct target_waitstatus ws;
4137
4138   VEC(cached_reg_t) *regcache;
4139
4140   int stopped_by_watchpoint_p;
4141   CORE_ADDR watch_data_address;
4142
4143   int solibs_changed;
4144   int replay_event;
4145 };
4146
4147 /* The list of already fetched and acknowledged stop events.  */
4148 static struct stop_reply *stop_reply_queue;
4149
4150 static struct stop_reply *
4151 stop_reply_xmalloc (void)
4152 {
4153   struct stop_reply *r = XMALLOC (struct stop_reply);
4154   r->next = NULL;
4155   return r;
4156 }
4157
4158 static void
4159 stop_reply_xfree (struct stop_reply *r)
4160 {
4161   if (r != NULL)
4162     {
4163       VEC_free (cached_reg_t, r->regcache);
4164       xfree (r);
4165     }
4166 }
4167
4168 /* Discard all pending stop replies of inferior PID.  If PID is -1,
4169    discard everything.  */
4170
4171 static void
4172 discard_pending_stop_replies (int pid)
4173 {
4174   struct stop_reply *prev = NULL, *reply, *next;
4175
4176   /* Discard the in-flight notification.  */
4177   if (pending_stop_reply != NULL
4178       && (pid == -1
4179           || ptid_get_pid (pending_stop_reply->ptid) == pid))
4180     {
4181       stop_reply_xfree (pending_stop_reply);
4182       pending_stop_reply = NULL;
4183     }
4184
4185   /* Discard the stop replies we have already pulled with
4186      vStopped.  */
4187   for (reply = stop_reply_queue; reply; reply = next)
4188     {
4189       next = reply->next;
4190       if (pid == -1
4191           || ptid_get_pid (reply->ptid) == pid)
4192         {
4193           if (reply == stop_reply_queue)
4194             stop_reply_queue = reply->next;
4195           else
4196             prev->next = reply->next;
4197
4198           stop_reply_xfree (reply);
4199         }
4200       else
4201         prev = reply;
4202     }
4203 }
4204
4205 /* Cleanup wrapper.  */
4206
4207 static void
4208 do_stop_reply_xfree (void *arg)
4209 {
4210   struct stop_reply *r = arg;
4211   stop_reply_xfree (r);
4212 }
4213
4214 /* Look for a queued stop reply belonging to PTID.  If one is found,
4215    remove it from the queue, and return it.  Returns NULL if none is
4216    found.  If there are still queued events left to process, tell the
4217    event loop to get back to target_wait soon.  */
4218
4219 static struct stop_reply *
4220 queued_stop_reply (ptid_t ptid)
4221 {
4222   struct stop_reply *it, *prev;
4223   struct stop_reply head;
4224
4225   head.next = stop_reply_queue;
4226   prev = &head;
4227
4228   it = head.next;
4229
4230   if (!ptid_equal (ptid, minus_one_ptid))
4231     for (; it; prev = it, it = it->next)
4232       if (ptid_equal (ptid, it->ptid))
4233         break;
4234
4235   if (it)
4236     {
4237       prev->next = it->next;
4238       it->next = NULL;
4239     }
4240
4241   stop_reply_queue = head.next;
4242
4243   if (stop_reply_queue)
4244     /* There's still at least an event left.  */
4245     mark_async_event_handler (remote_async_inferior_event_token);
4246
4247   return it;
4248 }
4249
4250 /* Push a fully parsed stop reply in the stop reply queue.  Since we
4251    know that we now have at least one queued event left to pass to the
4252    core side, tell the event loop to get back to target_wait soon.  */
4253
4254 static void
4255 push_stop_reply (struct stop_reply *new_event)
4256 {
4257   struct stop_reply *event;
4258
4259   if (stop_reply_queue)
4260     {
4261       for (event = stop_reply_queue;
4262            event && event->next;
4263            event = event->next)
4264         ;
4265
4266       event->next = new_event;
4267     }
4268   else
4269     stop_reply_queue = new_event;
4270
4271   mark_async_event_handler (remote_async_inferior_event_token);
4272 }
4273
4274 /* Returns true if we have a stop reply for PTID.  */
4275
4276 static int
4277 peek_stop_reply (ptid_t ptid)
4278 {
4279   struct stop_reply *it;
4280
4281   for (it = stop_reply_queue; it; it = it->next)
4282     if (ptid_equal (ptid, it->ptid))
4283       {
4284         if (it->ws.kind == TARGET_WAITKIND_STOPPED)
4285           return 1;
4286       }
4287
4288   return 0;
4289 }
4290
4291 /* Parse the stop reply in BUF.  Either the function succeeds, and the
4292    result is stored in EVENT, or throws an error.  */
4293
4294 static void
4295 remote_parse_stop_reply (char *buf, struct stop_reply *event)
4296 {
4297   struct remote_arch_state *rsa = get_remote_arch_state ();
4298   ULONGEST addr;
4299   char *p;
4300
4301   event->ptid = null_ptid;
4302   event->ws.kind = TARGET_WAITKIND_IGNORE;
4303   event->ws.value.integer = 0;
4304   event->solibs_changed = 0;
4305   event->replay_event = 0;
4306   event->stopped_by_watchpoint_p = 0;
4307   event->regcache = NULL;
4308
4309   switch (buf[0])
4310     {
4311     case 'T':           /* Status with PC, SP, FP, ...  */
4312       {
4313         gdb_byte regs[MAX_REGISTER_SIZE];
4314
4315         /* Expedited reply, containing Signal, {regno, reg} repeat.  */
4316         /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
4317            ss = signal number
4318            n... = register number
4319            r... = register contents
4320         */
4321
4322         p = &buf[3];    /* after Txx */
4323         while (*p)
4324           {
4325             char *p1;
4326             char *p_temp;
4327             int fieldsize;
4328             LONGEST pnum = 0;
4329
4330             /* If the packet contains a register number, save it in
4331                pnum and set p1 to point to the character following it.
4332                Otherwise p1 points to p.  */
4333
4334             /* If this packet is an awatch packet, don't parse the 'a'
4335                as a register number.  */
4336
4337             if (strncmp (p, "awatch", strlen("awatch")) != 0)
4338               {
4339                 /* Read the ``P'' register number.  */
4340                 pnum = strtol (p, &p_temp, 16);
4341                 p1 = p_temp;
4342               }
4343             else
4344               p1 = p;
4345
4346             if (p1 == p)        /* No register number present here.  */
4347               {
4348                 p1 = strchr (p, ':');
4349                 if (p1 == NULL)
4350                   error (_("Malformed packet(a) (missing colon): %s\n\
4351 Packet: '%s'\n"),
4352                          p, buf);
4353                 if (strncmp (p, "thread", p1 - p) == 0)
4354                   event->ptid = read_ptid (++p1, &p);
4355                 else if ((strncmp (p, "watch", p1 - p) == 0)
4356                          || (strncmp (p, "rwatch", p1 - p) == 0)
4357                          || (strncmp (p, "awatch", p1 - p) == 0))
4358                   {
4359                     event->stopped_by_watchpoint_p = 1;
4360                     p = unpack_varlen_hex (++p1, &addr);
4361                     event->watch_data_address = (CORE_ADDR) addr;
4362                   }
4363                 else if (strncmp (p, "library", p1 - p) == 0)
4364                   {
4365                     p1++;
4366                     p_temp = p1;
4367                     while (*p_temp && *p_temp != ';')
4368                       p_temp++;
4369
4370                     event->solibs_changed = 1;
4371                     p = p_temp;
4372                   }
4373                 else if (strncmp (p, "replaylog", p1 - p) == 0)
4374                   {
4375                     /* NO_HISTORY event.
4376                        p1 will indicate "begin" or "end", but
4377                        it makes no difference for now, so ignore it.  */
4378                     event->replay_event = 1;
4379                     p_temp = strchr (p1 + 1, ';');
4380                     if (p_temp)
4381                       p = p_temp;
4382                   }
4383                 else
4384                   {
4385                     /* Silently skip unknown optional info.  */
4386                     p_temp = strchr (p1 + 1, ';');
4387                     if (p_temp)
4388                       p = p_temp;
4389                   }
4390               }
4391             else
4392               {
4393                 struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
4394                 cached_reg_t cached_reg;
4395
4396                 p = p1;
4397
4398                 if (*p != ':')
4399                   error (_("Malformed packet(b) (missing colon): %s\n\
4400 Packet: '%s'\n"),
4401                          p, buf);
4402                 ++p;
4403
4404                 if (reg == NULL)
4405                   error (_("Remote sent bad register number %s: %s\n\
4406 Packet: '%s'\n"),
4407                          phex_nz (pnum, 0), p, buf);
4408
4409                 cached_reg.num = reg->regnum;
4410
4411                 fieldsize = hex2bin (p, cached_reg.data,
4412                                      register_size (target_gdbarch,
4413                                                     reg->regnum));
4414                 p += 2 * fieldsize;
4415                 if (fieldsize < register_size (target_gdbarch,
4416                                                reg->regnum))
4417                   warning (_("Remote reply is too short: %s"), buf);
4418
4419                 VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
4420               }
4421
4422             if (*p != ';')
4423               error (_("Remote register badly formatted: %s\nhere: %s"),
4424                      buf, p);
4425             ++p;
4426           }
4427       }
4428       /* fall through */
4429     case 'S':           /* Old style status, just signal only.  */
4430       if (event->solibs_changed)
4431         event->ws.kind = TARGET_WAITKIND_LOADED;
4432       else if (event->replay_event)
4433         event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
4434       else
4435         {
4436           event->ws.kind = TARGET_WAITKIND_STOPPED;
4437           event->ws.value.sig = (enum target_signal)
4438             (((fromhex (buf[1])) << 4) + (fromhex (buf[2])));
4439         }
4440       break;
4441     case 'W':           /* Target exited.  */
4442     case 'X':
4443       {
4444         char *p;
4445         int pid;
4446         ULONGEST value;
4447
4448         /* GDB used to accept only 2 hex chars here.  Stubs should
4449            only send more if they detect GDB supports multi-process
4450            support.  */
4451         p = unpack_varlen_hex (&buf[1], &value);
4452
4453         if (buf[0] == 'W')
4454           {
4455             /* The remote process exited.  */
4456             event->ws.kind = TARGET_WAITKIND_EXITED;
4457             event->ws.value.integer = value;
4458           }
4459         else
4460           {
4461             /* The remote process exited with a signal.  */
4462             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
4463             event->ws.value.sig = (enum target_signal) value;
4464           }
4465
4466         /* If no process is specified, assume inferior_ptid.  */
4467         pid = ptid_get_pid (inferior_ptid);
4468         if (*p == '\0')
4469           ;
4470         else if (*p == ';')
4471           {
4472             p++;
4473
4474             if (p == '\0')
4475               ;
4476             else if (strncmp (p,
4477                               "process:", sizeof ("process:") - 1) == 0)
4478               {
4479                 ULONGEST upid;
4480                 p += sizeof ("process:") - 1;
4481                 unpack_varlen_hex (p, &upid);
4482                 pid = upid;
4483               }
4484             else
4485               error (_("unknown stop reply packet: %s"), buf);
4486           }
4487         else
4488           error (_("unknown stop reply packet: %s"), buf);
4489         event->ptid = pid_to_ptid (pid);
4490       }
4491       break;
4492     }
4493
4494   if (non_stop && ptid_equal (event->ptid, null_ptid))
4495     error (_("No process or thread specified in stop reply: %s"), buf);
4496 }
4497
4498 /* When the stub wants to tell GDB about a new stop reply, it sends a
4499    stop notification (%Stop).  Those can come it at any time, hence,
4500    we have to make sure that any pending putpkt/getpkt sequence we're
4501    making is finished, before querying the stub for more events with
4502    vStopped.  E.g., if we started a vStopped sequence immediatelly
4503    upon receiving the %Stop notification, something like this could
4504    happen:
4505
4506     1.1) --> Hg 1
4507     1.2) <-- OK
4508     1.3) --> g
4509     1.4) <-- %Stop
4510     1.5) --> vStopped
4511     1.6) <-- (registers reply to step #1.3)
4512
4513    Obviously, the reply in step #1.6 would be unexpected to a vStopped
4514    query.
4515
4516    To solve this, whenever we parse a %Stop notification sucessfully,
4517    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
4518    doing whatever we were doing:
4519
4520     2.1) --> Hg 1
4521     2.2) <-- OK
4522     2.3) --> g
4523     2.4) <-- %Stop
4524       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
4525     2.5) <-- (registers reply to step #2.3)
4526
4527    Eventualy after step #2.5, we return to the event loop, which
4528    notices there's an event on the
4529    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
4530    associated callback --- the function below.  At this point, we're
4531    always safe to start a vStopped sequence. :
4532
4533     2.6) --> vStopped
4534     2.7) <-- T05 thread:2
4535     2.8) --> vStopped
4536     2.9) --> OK
4537 */
4538
4539 static void
4540 remote_get_pending_stop_replies (void)
4541 {
4542   struct remote_state *rs = get_remote_state ();
4543   int ret;
4544
4545   if (pending_stop_reply)
4546     {
4547       /* acknowledge */
4548       putpkt ("vStopped");
4549
4550       /* Now we can rely on it.  */
4551       push_stop_reply (pending_stop_reply);
4552       pending_stop_reply = NULL;
4553
4554       while (1)
4555         {
4556           getpkt (&rs->buf, &rs->buf_size, 0);
4557           if (strcmp (rs->buf, "OK") == 0)
4558             break;
4559           else
4560             {
4561               struct cleanup *old_chain;
4562               struct stop_reply *stop_reply = stop_reply_xmalloc ();
4563
4564               old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4565               remote_parse_stop_reply (rs->buf, stop_reply);
4566
4567               /* acknowledge */
4568               putpkt ("vStopped");
4569
4570               if (stop_reply->ws.kind != TARGET_WAITKIND_IGNORE)
4571                 {
4572                   /* Now we can rely on it.  */
4573                   discard_cleanups (old_chain);
4574                   push_stop_reply (stop_reply);
4575                 }
4576               else
4577                 /* We got an unknown stop reply.  */
4578                 do_cleanups (old_chain);
4579             }
4580         }
4581     }
4582 }
4583
4584
4585 /* Called when it is decided that STOP_REPLY holds the info of the
4586    event that is to be returned to the core.  This function always
4587    destroys STOP_REPLY.  */
4588
4589 static ptid_t
4590 process_stop_reply (struct stop_reply *stop_reply,
4591                     struct target_waitstatus *status)
4592 {
4593   ptid_t ptid;
4594
4595   *status = stop_reply->ws;
4596   ptid = stop_reply->ptid;
4597
4598   /* If no thread/process was reported by the stub, assume the current
4599      inferior.  */
4600   if (ptid_equal (ptid, null_ptid))
4601     ptid = inferior_ptid;
4602
4603   if (status->kind != TARGET_WAITKIND_EXITED
4604       && status->kind != TARGET_WAITKIND_SIGNALLED)
4605     {
4606       /* Expedited registers.  */
4607       if (stop_reply->regcache)
4608         {
4609           struct regcache *regcache
4610             = get_thread_arch_regcache (ptid, target_gdbarch);
4611           cached_reg_t *reg;
4612           int ix;
4613
4614           for (ix = 0;
4615                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
4616                ix++)
4617             regcache_raw_supply (regcache, reg->num, reg->data);
4618           VEC_free (cached_reg_t, stop_reply->regcache);
4619         }
4620
4621       remote_stopped_by_watchpoint_p = stop_reply->stopped_by_watchpoint_p;
4622       remote_watch_data_address = stop_reply->watch_data_address;
4623
4624       remote_notice_new_inferior (ptid, 0);
4625     }
4626
4627   stop_reply_xfree (stop_reply);
4628   return ptid;
4629 }
4630
4631 /* The non-stop mode version of target_wait.  */
4632
4633 static ptid_t
4634 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
4635 {
4636   struct remote_state *rs = get_remote_state ();
4637   struct remote_arch_state *rsa = get_remote_arch_state ();
4638   ptid_t event_ptid = null_ptid;
4639   struct stop_reply *stop_reply;
4640   int ret;
4641
4642   /* If in non-stop mode, get out of getpkt even if a
4643      notification is received.  */
4644
4645   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4646                               0 /* forever */);
4647   while (1)
4648     {
4649       if (ret != -1)
4650         switch (rs->buf[0])
4651           {
4652           case 'E':             /* Error of some sort.  */
4653             /* We're out of sync with the target now.  Did it continue
4654                or not?  We can't tell which thread it was in non-stop,
4655                so just ignore this.  */
4656             warning (_("Remote failure reply: %s"), rs->buf);
4657             break;
4658           case 'O':             /* Console output.  */
4659             remote_console_output (rs->buf + 1);
4660             break;
4661           default:
4662             warning (_("Invalid remote reply: %s"), rs->buf);
4663             break;
4664           }
4665
4666       /* Acknowledge a pending stop reply that may have arrived in the
4667          mean time.  */
4668       if (pending_stop_reply != NULL)
4669         remote_get_pending_stop_replies ();
4670
4671       /* If indeed we noticed a stop reply, we're done.  */
4672       stop_reply = queued_stop_reply (ptid);
4673       if (stop_reply != NULL)
4674         return process_stop_reply (stop_reply, status);
4675
4676       /* Still no event.  If we're just polling for an event, then
4677          return to the event loop.  */
4678       if (options & TARGET_WNOHANG)
4679         {
4680           status->kind = TARGET_WAITKIND_IGNORE;
4681           return minus_one_ptid;
4682         }
4683
4684       /* Otherwise do a blocking wait.  */
4685       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
4686                                   1 /* forever */);
4687     }
4688 }
4689
4690 /* Wait until the remote machine stops, then return, storing status in
4691    STATUS just as `wait' would.  */
4692
4693 static ptid_t
4694 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
4695 {
4696   struct remote_state *rs = get_remote_state ();
4697   struct remote_arch_state *rsa = get_remote_arch_state ();
4698   ptid_t event_ptid = null_ptid;
4699   ULONGEST addr;
4700   int solibs_changed = 0;
4701   char *buf, *p;
4702   struct stop_reply *stop_reply;
4703
4704  again:
4705
4706   status->kind = TARGET_WAITKIND_IGNORE;
4707   status->value.integer = 0;
4708
4709   stop_reply = queued_stop_reply (ptid);
4710   if (stop_reply != NULL)
4711     return process_stop_reply (stop_reply, status);
4712
4713   if (rs->cached_wait_status)
4714     /* Use the cached wait status, but only once.  */
4715     rs->cached_wait_status = 0;
4716   else
4717     {
4718       int ret;
4719
4720       if (!target_is_async_p ())
4721         {
4722           ofunc = signal (SIGINT, remote_interrupt);
4723           /* If the user hit C-c before this packet, or between packets,
4724              pretend that it was hit right here.  */
4725           if (quit_flag)
4726             {
4727               quit_flag = 0;
4728               remote_interrupt (SIGINT);
4729             }
4730         }
4731
4732       /* FIXME: cagney/1999-09-27: If we're in async mode we should
4733          _never_ wait for ever -> test on target_is_async_p().
4734          However, before we do that we need to ensure that the caller
4735          knows how to take the target into/out of async mode.  */
4736       ret = getpkt_sane (&rs->buf, &rs->buf_size, wait_forever_enabled_p);
4737       if (!target_is_async_p ())
4738         signal (SIGINT, ofunc);
4739     }
4740
4741   buf = rs->buf;
4742
4743   remote_stopped_by_watchpoint_p = 0;
4744
4745   /* We got something.  */
4746   rs->waiting_for_stop_reply = 0;
4747
4748   switch (buf[0])
4749     {
4750     case 'E':           /* Error of some sort.  */
4751       /* We're out of sync with the target now.  Did it continue or
4752          not?  Not is more likely, so report a stop.  */
4753       warning (_("Remote failure reply: %s"), buf);
4754       status->kind = TARGET_WAITKIND_STOPPED;
4755       status->value.sig = TARGET_SIGNAL_0;
4756       break;
4757     case 'F':           /* File-I/O request.  */
4758       remote_fileio_request (buf);
4759       break;
4760     case 'T': case 'S': case 'X': case 'W':
4761       {
4762         struct stop_reply *stop_reply;
4763         struct cleanup *old_chain;
4764
4765         stop_reply = stop_reply_xmalloc ();
4766         old_chain = make_cleanup (do_stop_reply_xfree, stop_reply);
4767         remote_parse_stop_reply (buf, stop_reply);
4768         discard_cleanups (old_chain);
4769         event_ptid = process_stop_reply (stop_reply, status);
4770         break;
4771       }
4772     case 'O':           /* Console output.  */
4773       remote_console_output (buf + 1);
4774
4775       /* The target didn't really stop; keep waiting.  */
4776       rs->waiting_for_stop_reply = 1;
4777
4778       break;
4779     case '\0':
4780       if (last_sent_signal != TARGET_SIGNAL_0)
4781         {
4782           /* Zero length reply means that we tried 'S' or 'C' and the
4783              remote system doesn't support it.  */
4784           target_terminal_ours_for_output ();
4785           printf_filtered
4786             ("Can't send signals to this remote system.  %s not sent.\n",
4787              target_signal_to_name (last_sent_signal));
4788           last_sent_signal = TARGET_SIGNAL_0;
4789           target_terminal_inferior ();
4790
4791           strcpy ((char *) buf, last_sent_step ? "s" : "c");
4792           putpkt ((char *) buf);
4793
4794           /* We just told the target to resume, so a stop reply is in
4795              order.  */
4796           rs->waiting_for_stop_reply = 1;
4797           break;
4798         }
4799       /* else fallthrough */
4800     default:
4801       warning (_("Invalid remote reply: %s"), buf);
4802       /* Keep waiting.  */
4803       rs->waiting_for_stop_reply = 1;
4804       break;
4805     }
4806
4807   if (status->kind == TARGET_WAITKIND_IGNORE)
4808     {
4809       /* Nothing interesting happened.  If we're doing a non-blocking
4810          poll, we're done.  Otherwise, go back to waiting.  */
4811       if (options & TARGET_WNOHANG)
4812         return minus_one_ptid;
4813       else
4814         goto again;
4815     }
4816   else if (status->kind != TARGET_WAITKIND_EXITED
4817            && status->kind != TARGET_WAITKIND_SIGNALLED)
4818     {
4819       if (!ptid_equal (event_ptid, null_ptid))
4820         record_currthread (event_ptid);
4821       else
4822         event_ptid = inferior_ptid;
4823     }
4824   else
4825     /* A process exit.  Invalidate our notion of current thread.  */
4826     record_currthread (minus_one_ptid);
4827
4828   return event_ptid;
4829 }
4830
4831 /* Wait until the remote machine stops, then return, storing status in
4832    STATUS just as `wait' would.  */
4833
4834 static ptid_t
4835 remote_wait (struct target_ops *ops,
4836              ptid_t ptid, struct target_waitstatus *status, int options)
4837 {
4838   ptid_t event_ptid;
4839
4840   if (non_stop)
4841     event_ptid = remote_wait_ns (ptid, status, options);
4842   else
4843     event_ptid = remote_wait_as (ptid, status, options);
4844
4845   if (target_can_async_p ())
4846     {
4847       /* If there are are events left in the queue tell the event loop
4848          to return here.  */
4849       if (stop_reply_queue)
4850         mark_async_event_handler (remote_async_inferior_event_token);
4851     }
4852
4853   return event_ptid;
4854 }
4855
4856 /* Fetch a single register using a 'p' packet.  */
4857
4858 static int
4859 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
4860 {
4861   struct remote_state *rs = get_remote_state ();
4862   char *buf, *p;
4863   char regp[MAX_REGISTER_SIZE];
4864   int i;
4865
4866   if (remote_protocol_packets[PACKET_p].support == PACKET_DISABLE)
4867     return 0;
4868
4869   if (reg->pnum == -1)
4870     return 0;
4871
4872   p = rs->buf;
4873   *p++ = 'p';
4874   p += hexnumstr (p, reg->pnum);
4875   *p++ = '\0';
4876   remote_send (&rs->buf, &rs->buf_size);
4877
4878   buf = rs->buf;
4879
4880   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
4881     {
4882     case PACKET_OK:
4883       break;
4884     case PACKET_UNKNOWN:
4885       return 0;
4886     case PACKET_ERROR:
4887       error (_("Could not fetch register \"%s\""),
4888              gdbarch_register_name (get_regcache_arch (regcache), reg->regnum));
4889     }
4890
4891   /* If this register is unfetchable, tell the regcache.  */
4892   if (buf[0] == 'x')
4893     {
4894       regcache_raw_supply (regcache, reg->regnum, NULL);
4895       return 1;
4896     }
4897
4898   /* Otherwise, parse and supply the value.  */
4899   p = buf;
4900   i = 0;
4901   while (p[0] != 0)
4902     {
4903       if (p[1] == 0)
4904         error (_("fetch_register_using_p: early buf termination"));
4905
4906       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
4907       p += 2;
4908     }
4909   regcache_raw_supply (regcache, reg->regnum, regp);
4910   return 1;
4911 }
4912
4913 /* Fetch the registers included in the target's 'g' packet.  */
4914
4915 static int
4916 send_g_packet (void)
4917 {
4918   struct remote_state *rs = get_remote_state ();
4919   int i, buf_len;
4920   char *p;
4921   char *regs;
4922
4923   sprintf (rs->buf, "g");
4924   remote_send (&rs->buf, &rs->buf_size);
4925
4926   /* We can get out of synch in various cases.  If the first character
4927      in the buffer is not a hex character, assume that has happened
4928      and try to fetch another packet to read.  */
4929   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
4930          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
4931          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
4932          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
4933     {
4934       if (remote_debug)
4935         fprintf_unfiltered (gdb_stdlog,
4936                             "Bad register packet; fetching a new packet\n");
4937       getpkt (&rs->buf, &rs->buf_size, 0);
4938     }
4939
4940   buf_len = strlen (rs->buf);
4941
4942   /* Sanity check the received packet.  */
4943   if (buf_len % 2 != 0)
4944     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
4945
4946   return buf_len / 2;
4947 }
4948
4949 static void
4950 process_g_packet (struct regcache *regcache)
4951 {
4952   struct gdbarch *gdbarch = get_regcache_arch (regcache);
4953   struct remote_state *rs = get_remote_state ();
4954   struct remote_arch_state *rsa = get_remote_arch_state ();
4955   int i, buf_len;
4956   char *p;
4957   char *regs;
4958
4959   buf_len = strlen (rs->buf);
4960
4961   /* Further sanity checks, with knowledge of the architecture.  */
4962   if (buf_len > 2 * rsa->sizeof_g_packet)
4963     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
4964
4965   /* Save the size of the packet sent to us by the target.  It is used
4966      as a heuristic when determining the max size of packets that the
4967      target can safely receive.  */
4968   if (rsa->actual_register_packet_size == 0)
4969     rsa->actual_register_packet_size = buf_len;
4970
4971   /* If this is smaller than we guessed the 'g' packet would be,
4972      update our records.  A 'g' reply that doesn't include a register's
4973      value implies either that the register is not available, or that
4974      the 'p' packet must be used.  */
4975   if (buf_len < 2 * rsa->sizeof_g_packet)
4976     {
4977       rsa->sizeof_g_packet = buf_len / 2;
4978
4979       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
4980         {
4981           if (rsa->regs[i].pnum == -1)
4982             continue;
4983
4984           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
4985             rsa->regs[i].in_g_packet = 0;
4986           else
4987             rsa->regs[i].in_g_packet = 1;
4988         }
4989     }
4990
4991   regs = alloca (rsa->sizeof_g_packet);
4992
4993   /* Unimplemented registers read as all bits zero.  */
4994   memset (regs, 0, rsa->sizeof_g_packet);
4995
4996   /* Reply describes registers byte by byte, each byte encoded as two
4997      hex characters.  Suck them all up, then supply them to the
4998      register cacheing/storage mechanism.  */
4999
5000   p = rs->buf;
5001   for (i = 0; i < rsa->sizeof_g_packet; i++)
5002     {
5003       if (p[0] == 0 || p[1] == 0)
5004         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
5005         internal_error (__FILE__, __LINE__,
5006                         "unexpected end of 'g' packet reply");
5007
5008       if (p[0] == 'x' && p[1] == 'x')
5009         regs[i] = 0;            /* 'x' */
5010       else
5011         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
5012       p += 2;
5013     }
5014
5015   {
5016     int i;
5017     for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
5018       {
5019         struct packet_reg *r = &rsa->regs[i];
5020         if (r->in_g_packet)
5021           {
5022             if (r->offset * 2 >= strlen (rs->buf))
5023               /* This shouldn't happen - we adjusted in_g_packet above.  */
5024               internal_error (__FILE__, __LINE__,
5025                               "unexpected end of 'g' packet reply");
5026             else if (rs->buf[r->offset * 2] == 'x')
5027               {
5028                 gdb_assert (r->offset * 2 < strlen (rs->buf));
5029                 /* The register isn't available, mark it as such (at
5030                    the same time setting the value to zero).  */
5031                 regcache_raw_supply (regcache, r->regnum, NULL);
5032               }
5033             else
5034               regcache_raw_supply (regcache, r->regnum,
5035                                    regs + r->offset);
5036           }
5037       }
5038   }
5039 }
5040
5041 static void
5042 fetch_registers_using_g (struct regcache *regcache)
5043 {
5044   send_g_packet ();
5045   process_g_packet (regcache);
5046 }
5047
5048 static void
5049 remote_fetch_registers (struct target_ops *ops,
5050                         struct regcache *regcache, int regnum)
5051 {
5052   struct remote_state *rs = get_remote_state ();
5053   struct remote_arch_state *rsa = get_remote_arch_state ();
5054   int i;
5055
5056   set_general_thread (inferior_ptid);
5057
5058   if (regnum >= 0)
5059     {
5060       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5061       gdb_assert (reg != NULL);
5062
5063       /* If this register might be in the 'g' packet, try that first -
5064          we are likely to read more than one register.  If this is the
5065          first 'g' packet, we might be overly optimistic about its
5066          contents, so fall back to 'p'.  */
5067       if (reg->in_g_packet)
5068         {
5069           fetch_registers_using_g (regcache);
5070           if (reg->in_g_packet)
5071             return;
5072         }
5073
5074       if (fetch_register_using_p (regcache, reg))
5075         return;
5076
5077       /* This register is not available.  */
5078       regcache_raw_supply (regcache, reg->regnum, NULL);
5079
5080       return;
5081     }
5082
5083   fetch_registers_using_g (regcache);
5084
5085   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5086     if (!rsa->regs[i].in_g_packet)
5087       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
5088         {
5089           /* This register is not available.  */
5090           regcache_raw_supply (regcache, i, NULL);
5091         }
5092 }
5093
5094 /* Prepare to store registers.  Since we may send them all (using a
5095    'G' request), we have to read out the ones we don't want to change
5096    first.  */
5097
5098 static void
5099 remote_prepare_to_store (struct regcache *regcache)
5100 {
5101   struct remote_arch_state *rsa = get_remote_arch_state ();
5102   int i;
5103   gdb_byte buf[MAX_REGISTER_SIZE];
5104
5105   /* Make sure the entire registers array is valid.  */
5106   switch (remote_protocol_packets[PACKET_P].support)
5107     {
5108     case PACKET_DISABLE:
5109     case PACKET_SUPPORT_UNKNOWN:
5110       /* Make sure all the necessary registers are cached.  */
5111       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5112         if (rsa->regs[i].in_g_packet)
5113           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
5114       break;
5115     case PACKET_ENABLE:
5116       break;
5117     }
5118 }
5119
5120 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
5121    packet was not recognized.  */
5122
5123 static int
5124 store_register_using_P (const struct regcache *regcache, struct packet_reg *reg)
5125 {
5126   struct gdbarch *gdbarch = get_regcache_arch (regcache);
5127   struct remote_state *rs = get_remote_state ();
5128   struct remote_arch_state *rsa = get_remote_arch_state ();
5129   /* Try storing a single register.  */
5130   char *buf = rs->buf;
5131   gdb_byte regp[MAX_REGISTER_SIZE];
5132   char *p;
5133
5134   if (remote_protocol_packets[PACKET_P].support == PACKET_DISABLE)
5135     return 0;
5136
5137   if (reg->pnum == -1)
5138     return 0;
5139
5140   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
5141   p = buf + strlen (buf);
5142   regcache_raw_collect (regcache, reg->regnum, regp);
5143   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
5144   remote_send (&rs->buf, &rs->buf_size);
5145
5146   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
5147     {
5148     case PACKET_OK:
5149       return 1;
5150     case PACKET_ERROR:
5151       error (_("Could not write register \"%s\""),
5152              gdbarch_register_name (gdbarch, reg->regnum));
5153     case PACKET_UNKNOWN:
5154       return 0;
5155     default:
5156       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
5157     }
5158 }
5159
5160 /* Store register REGNUM, or all registers if REGNUM == -1, from the
5161    contents of the register cache buffer.  FIXME: ignores errors.  */
5162
5163 static void
5164 store_registers_using_G (const struct regcache *regcache)
5165 {
5166   struct remote_state *rs = get_remote_state ();
5167   struct remote_arch_state *rsa = get_remote_arch_state ();
5168   gdb_byte *regs;
5169   char *p;
5170
5171   /* Extract all the registers in the regcache copying them into a
5172      local buffer.  */
5173   {
5174     int i;
5175     regs = alloca (rsa->sizeof_g_packet);
5176     memset (regs, 0, rsa->sizeof_g_packet);
5177     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5178       {
5179         struct packet_reg *r = &rsa->regs[i];
5180         if (r->in_g_packet)
5181           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
5182       }
5183   }
5184
5185   /* Command describes registers byte by byte,
5186      each byte encoded as two hex characters.  */
5187   p = rs->buf;
5188   *p++ = 'G';
5189   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
5190      updated.  */
5191   bin2hex (regs, p, rsa->sizeof_g_packet);
5192   remote_send (&rs->buf, &rs->buf_size);
5193 }
5194
5195 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
5196    of the register cache buffer.  FIXME: ignores errors.  */
5197
5198 static void
5199 remote_store_registers (struct target_ops *ops,
5200                         struct regcache *regcache, int regnum)
5201 {
5202   struct remote_state *rs = get_remote_state ();
5203   struct remote_arch_state *rsa = get_remote_arch_state ();
5204   int i;
5205
5206   set_general_thread (inferior_ptid);
5207
5208   if (regnum >= 0)
5209     {
5210       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
5211       gdb_assert (reg != NULL);
5212
5213       /* Always prefer to store registers using the 'P' packet if
5214          possible; we often change only a small number of registers.
5215          Sometimes we change a larger number; we'd need help from a
5216          higher layer to know to use 'G'.  */
5217       if (store_register_using_P (regcache, reg))
5218         return;
5219
5220       /* For now, don't complain if we have no way to write the
5221          register.  GDB loses track of unavailable registers too
5222          easily.  Some day, this may be an error.  We don't have
5223          any way to read the register, either... */
5224       if (!reg->in_g_packet)
5225         return;
5226
5227       store_registers_using_G (regcache);
5228       return;
5229     }
5230
5231   store_registers_using_G (regcache);
5232
5233   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
5234     if (!rsa->regs[i].in_g_packet)
5235       if (!store_register_using_P (regcache, &rsa->regs[i]))
5236         /* See above for why we do not issue an error here.  */
5237         continue;
5238 }
5239 \f
5240
5241 /* Return the number of hex digits in num.  */
5242
5243 static int
5244 hexnumlen (ULONGEST num)
5245 {
5246   int i;
5247
5248   for (i = 0; num != 0; i++)
5249     num >>= 4;
5250
5251   return max (i, 1);
5252 }
5253
5254 /* Set BUF to the minimum number of hex digits representing NUM.  */
5255
5256 static int
5257 hexnumstr (char *buf, ULONGEST num)
5258 {
5259   int len = hexnumlen (num);
5260   return hexnumnstr (buf, num, len);
5261 }
5262
5263
5264 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
5265
5266 static int
5267 hexnumnstr (char *buf, ULONGEST num, int width)
5268 {
5269   int i;
5270
5271   buf[width] = '\0';
5272
5273   for (i = width - 1; i >= 0; i--)
5274     {
5275       buf[i] = "0123456789abcdef"[(num & 0xf)];
5276       num >>= 4;
5277     }
5278
5279   return width;
5280 }
5281
5282 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
5283
5284 static CORE_ADDR
5285 remote_address_masked (CORE_ADDR addr)
5286 {
5287   int address_size = remote_address_size;
5288   /* If "remoteaddresssize" was not set, default to target address size.  */
5289   if (!address_size)
5290     address_size = gdbarch_addr_bit (target_gdbarch);
5291
5292   if (address_size > 0
5293       && address_size < (sizeof (ULONGEST) * 8))
5294     {
5295       /* Only create a mask when that mask can safely be constructed
5296          in a ULONGEST variable.  */
5297       ULONGEST mask = 1;
5298       mask = (mask << address_size) - 1;
5299       addr &= mask;
5300     }
5301   return addr;
5302 }
5303
5304 /* Convert BUFFER, binary data at least LEN bytes long, into escaped
5305    binary data in OUT_BUF.  Set *OUT_LEN to the length of the data
5306    encoded in OUT_BUF, and return the number of bytes in OUT_BUF
5307    (which may be more than *OUT_LEN due to escape characters).  The
5308    total number of bytes in the output buffer will be at most
5309    OUT_MAXLEN.  */
5310
5311 static int
5312 remote_escape_output (const gdb_byte *buffer, int len,
5313                       gdb_byte *out_buf, int *out_len,
5314                       int out_maxlen)
5315 {
5316   int input_index, output_index;
5317
5318   output_index = 0;
5319   for (input_index = 0; input_index < len; input_index++)
5320     {
5321       gdb_byte b = buffer[input_index];
5322
5323       if (b == '$' || b == '#' || b == '}')
5324         {
5325           /* These must be escaped.  */
5326           if (output_index + 2 > out_maxlen)
5327             break;
5328           out_buf[output_index++] = '}';
5329           out_buf[output_index++] = b ^ 0x20;
5330         }
5331       else
5332         {
5333           if (output_index + 1 > out_maxlen)
5334             break;
5335           out_buf[output_index++] = b;
5336         }
5337     }
5338
5339   *out_len = input_index;
5340   return output_index;
5341 }
5342
5343 /* Convert BUFFER, escaped data LEN bytes long, into binary data
5344    in OUT_BUF.  Return the number of bytes written to OUT_BUF.
5345    Raise an error if the total number of bytes exceeds OUT_MAXLEN.
5346
5347    This function reverses remote_escape_output.  It allows more
5348    escaped characters than that function does, in particular because
5349    '*' must be escaped to avoid the run-length encoding processing
5350    in reading packets.  */
5351
5352 static int
5353 remote_unescape_input (const gdb_byte *buffer, int len,
5354                        gdb_byte *out_buf, int out_maxlen)
5355 {
5356   int input_index, output_index;
5357   int escaped;
5358
5359   output_index = 0;
5360   escaped = 0;
5361   for (input_index = 0; input_index < len; input_index++)
5362     {
5363       gdb_byte b = buffer[input_index];
5364
5365       if (output_index + 1 > out_maxlen)
5366         {
5367           warning (_("Received too much data from remote target;"
5368                      " ignoring overflow."));
5369           return output_index;
5370         }
5371
5372       if (escaped)
5373         {
5374           out_buf[output_index++] = b ^ 0x20;
5375           escaped = 0;
5376         }
5377       else if (b == '}')
5378         escaped = 1;
5379       else
5380         out_buf[output_index++] = b;
5381     }
5382
5383   if (escaped)
5384     error (_("Unmatched escape character in target response."));
5385
5386   return output_index;
5387 }
5388
5389 /* Determine whether the remote target supports binary downloading.
5390    This is accomplished by sending a no-op memory write of zero length
5391    to the target at the specified address. It does not suffice to send
5392    the whole packet, since many stubs strip the eighth bit and
5393    subsequently compute a wrong checksum, which causes real havoc with
5394    remote_write_bytes.
5395
5396    NOTE: This can still lose if the serial line is not eight-bit
5397    clean. In cases like this, the user should clear "remote
5398    X-packet".  */
5399
5400 static void
5401 check_binary_download (CORE_ADDR addr)
5402 {
5403   struct remote_state *rs = get_remote_state ();
5404
5405   switch (remote_protocol_packets[PACKET_X].support)
5406     {
5407     case PACKET_DISABLE:
5408       break;
5409     case PACKET_ENABLE:
5410       break;
5411     case PACKET_SUPPORT_UNKNOWN:
5412       {
5413         char *p;
5414
5415         p = rs->buf;
5416         *p++ = 'X';
5417         p += hexnumstr (p, (ULONGEST) addr);
5418         *p++ = ',';
5419         p += hexnumstr (p, (ULONGEST) 0);
5420         *p++ = ':';
5421         *p = '\0';
5422
5423         putpkt_binary (rs->buf, (int) (p - rs->buf));
5424         getpkt (&rs->buf, &rs->buf_size, 0);
5425
5426         if (rs->buf[0] == '\0')
5427           {
5428             if (remote_debug)
5429               fprintf_unfiltered (gdb_stdlog,
5430                                   "binary downloading NOT suppported by target\n");
5431             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
5432           }
5433         else
5434           {
5435             if (remote_debug)
5436               fprintf_unfiltered (gdb_stdlog,
5437                                   "binary downloading suppported by target\n");
5438             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
5439           }
5440         break;
5441       }
5442     }
5443 }
5444
5445 /* Write memory data directly to the remote machine.
5446    This does not inform the data cache; the data cache uses this.
5447    HEADER is the starting part of the packet.
5448    MEMADDR is the address in the remote memory space.
5449    MYADDR is the address of the buffer in our space.
5450    LEN is the number of bytes.
5451    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
5452    should send data as binary ('X'), or hex-encoded ('M').
5453
5454    The function creates packet of the form
5455        <HEADER><ADDRESS>,<LENGTH>:<DATA>
5456
5457    where encoding of <DATA> is termined by PACKET_FORMAT.
5458
5459    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
5460    are omitted.
5461
5462    Returns the number of bytes transferred, or 0 (setting errno) for
5463    error.  Only transfer a single packet.  */
5464
5465 static int
5466 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
5467                         const gdb_byte *myaddr, int len,
5468                         char packet_format, int use_length)
5469 {
5470   struct remote_state *rs = get_remote_state ();
5471   char *p;
5472   char *plen = NULL;
5473   int plenlen = 0;
5474   int todo;
5475   int nr_bytes;
5476   int payload_size;
5477   int payload_length;
5478   int header_length;
5479
5480   if (packet_format != 'X' && packet_format != 'M')
5481     internal_error (__FILE__, __LINE__,
5482                     "remote_write_bytes_aux: bad packet format");
5483
5484   if (len <= 0)
5485     return 0;
5486
5487   payload_size = get_memory_write_packet_size ();
5488
5489   /* The packet buffer will be large enough for the payload;
5490      get_memory_packet_size ensures this.  */
5491   rs->buf[0] = '\0';
5492
5493   /* Compute the size of the actual payload by subtracting out the
5494      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".
5495      */
5496   payload_size -= strlen ("$,:#NN");
5497   if (!use_length)
5498     /* The comma won't be used. */
5499     payload_size += 1;
5500   header_length = strlen (header);
5501   payload_size -= header_length;
5502   payload_size -= hexnumlen (memaddr);
5503
5504   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
5505
5506   strcat (rs->buf, header);
5507   p = rs->buf + strlen (header);
5508
5509   /* Compute a best guess of the number of bytes actually transfered.  */
5510   if (packet_format == 'X')
5511     {
5512       /* Best guess at number of bytes that will fit.  */
5513       todo = min (len, payload_size);
5514       if (use_length)
5515         payload_size -= hexnumlen (todo);
5516       todo = min (todo, payload_size);
5517     }
5518   else
5519     {
5520       /* Num bytes that will fit.  */
5521       todo = min (len, payload_size / 2);
5522       if (use_length)
5523         payload_size -= hexnumlen (todo);
5524       todo = min (todo, payload_size / 2);
5525     }
5526
5527   if (todo <= 0)
5528     internal_error (__FILE__, __LINE__,
5529                     _("minumum packet size too small to write data"));
5530
5531   /* If we already need another packet, then try to align the end
5532      of this packet to a useful boundary.  */
5533   if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
5534     todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
5535
5536   /* Append "<memaddr>".  */
5537   memaddr = remote_address_masked (memaddr);
5538   p += hexnumstr (p, (ULONGEST) memaddr);
5539
5540   if (use_length)
5541     {
5542       /* Append ",".  */
5543       *p++ = ',';
5544
5545       /* Append <len>.  Retain the location/size of <len>.  It may need to
5546          be adjusted once the packet body has been created.  */
5547       plen = p;
5548       plenlen = hexnumstr (p, (ULONGEST) todo);
5549       p += plenlen;
5550     }
5551
5552   /* Append ":".  */
5553   *p++ = ':';
5554   *p = '\0';
5555
5556   /* Append the packet body.  */
5557   if (packet_format == 'X')
5558     {
5559       /* Binary mode.  Send target system values byte by byte, in
5560          increasing byte addresses.  Only escape certain critical
5561          characters.  */
5562       payload_length = remote_escape_output (myaddr, todo, p, &nr_bytes,
5563                                              payload_size);
5564
5565       /* If not all TODO bytes fit, then we'll need another packet.  Make
5566          a second try to keep the end of the packet aligned.  Don't do
5567          this if the packet is tiny.  */
5568       if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
5569         {
5570           int new_nr_bytes;
5571
5572           new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
5573                           - memaddr);
5574           if (new_nr_bytes != nr_bytes)
5575             payload_length = remote_escape_output (myaddr, new_nr_bytes,
5576                                                    p, &nr_bytes,
5577                                                    payload_size);
5578         }
5579
5580       p += payload_length;
5581       if (use_length && nr_bytes < todo)
5582         {
5583           /* Escape chars have filled up the buffer prematurely,
5584              and we have actually sent fewer bytes than planned.
5585              Fix-up the length field of the packet.  Use the same
5586              number of characters as before.  */
5587           plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
5588           *plen = ':';  /* overwrite \0 from hexnumnstr() */
5589         }
5590     }
5591   else
5592     {
5593       /* Normal mode: Send target system values byte by byte, in
5594          increasing byte addresses.  Each byte is encoded as a two hex
5595          value.  */
5596       nr_bytes = bin2hex (myaddr, p, todo);
5597       p += 2 * nr_bytes;
5598     }
5599
5600   putpkt_binary (rs->buf, (int) (p - rs->buf));
5601   getpkt (&rs->buf, &rs->buf_size, 0);
5602
5603   if (rs->buf[0] == 'E')
5604     {
5605       /* There is no correspondance between what the remote protocol
5606          uses for errors and errno codes.  We would like a cleaner way
5607          of representing errors (big enough to include errno codes,
5608          bfd_error codes, and others).  But for now just return EIO.  */
5609       errno = EIO;
5610       return 0;
5611     }
5612
5613   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
5614      fewer bytes than we'd planned.  */
5615   return nr_bytes;
5616 }
5617
5618 /* Write memory data directly to the remote machine.
5619    This does not inform the data cache; the data cache uses this.
5620    MEMADDR is the address in the remote memory space.
5621    MYADDR is the address of the buffer in our space.
5622    LEN is the number of bytes.
5623
5624    Returns number of bytes transferred, or 0 (setting errno) for
5625    error.  Only transfer a single packet.  */
5626
5627 int
5628 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, int len)
5629 {
5630   char *packet_format = 0;
5631
5632   /* Check whether the target supports binary download.  */
5633   check_binary_download (memaddr);
5634
5635   switch (remote_protocol_packets[PACKET_X].support)
5636     {
5637     case PACKET_ENABLE:
5638       packet_format = "X";
5639       break;
5640     case PACKET_DISABLE:
5641       packet_format = "M";
5642       break;
5643     case PACKET_SUPPORT_UNKNOWN:
5644       internal_error (__FILE__, __LINE__,
5645                       _("remote_write_bytes: bad internal state"));
5646     default:
5647       internal_error (__FILE__, __LINE__, _("bad switch"));
5648     }
5649
5650   return remote_write_bytes_aux (packet_format,
5651                                  memaddr, myaddr, len, packet_format[0], 1);
5652 }
5653
5654 /* Read memory data directly from the remote machine.
5655    This does not use the data cache; the data cache uses this.
5656    MEMADDR is the address in the remote memory space.
5657    MYADDR is the address of the buffer in our space.
5658    LEN is the number of bytes.
5659
5660    Returns number of bytes transferred, or 0 for error.  */
5661
5662 /* NOTE: cagney/1999-10-18: This function (and its siblings in other
5663    remote targets) shouldn't attempt to read the entire buffer.
5664    Instead it should read a single packet worth of data and then
5665    return the byte size of that packet to the caller.  The caller (its
5666    caller and its callers caller ;-) already contains code for
5667    handling partial reads.  */
5668
5669 int
5670 remote_read_bytes (CORE_ADDR memaddr, gdb_byte *myaddr, int len)
5671 {
5672   struct remote_state *rs = get_remote_state ();
5673   int max_buf_size;             /* Max size of packet output buffer.  */
5674   int origlen;
5675
5676   if (len <= 0)
5677     return 0;
5678
5679   max_buf_size = get_memory_read_packet_size ();
5680   /* The packet buffer will be large enough for the payload;
5681      get_memory_packet_size ensures this.  */
5682
5683   origlen = len;
5684   while (len > 0)
5685     {
5686       char *p;
5687       int todo;
5688       int i;
5689
5690       todo = min (len, max_buf_size / 2);       /* num bytes that will fit */
5691
5692       /* construct "m"<memaddr>","<len>" */
5693       /* sprintf (rs->buf, "m%lx,%x", (unsigned long) memaddr, todo); */
5694       memaddr = remote_address_masked (memaddr);
5695       p = rs->buf;
5696       *p++ = 'm';
5697       p += hexnumstr (p, (ULONGEST) memaddr);
5698       *p++ = ',';
5699       p += hexnumstr (p, (ULONGEST) todo);
5700       *p = '\0';
5701
5702       putpkt (rs->buf);
5703       getpkt (&rs->buf, &rs->buf_size, 0);
5704
5705       if (rs->buf[0] == 'E'
5706           && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
5707           && rs->buf[3] == '\0')
5708         {
5709           /* There is no correspondance between what the remote
5710              protocol uses for errors and errno codes.  We would like
5711              a cleaner way of representing errors (big enough to
5712              include errno codes, bfd_error codes, and others).  But
5713              for now just return EIO.  */
5714           errno = EIO;
5715           return 0;
5716         }
5717
5718       /* Reply describes memory byte by byte,
5719          each byte encoded as two hex characters.  */
5720
5721       p = rs->buf;
5722       if ((i = hex2bin (p, myaddr, todo)) < todo)
5723         {
5724           /* Reply is short.  This means that we were able to read
5725              only part of what we wanted to.  */
5726           return i + (origlen - len);
5727         }
5728       myaddr += todo;
5729       memaddr += todo;
5730       len -= todo;
5731     }
5732   return origlen;
5733 }
5734 \f
5735
5736 /* Remote notification handler.  */
5737
5738 static void
5739 handle_notification (char *buf, size_t length)
5740 {
5741   if (strncmp (buf, "Stop:", 5) == 0)
5742     {
5743       if (pending_stop_reply)
5744         /* We've already parsed the in-flight stop-reply, but the stub
5745            for some reason thought we didn't, possibly due to timeout
5746            on its side.  Just ignore it.  */
5747         ;
5748       else
5749         {
5750           struct cleanup *old_chain;
5751           struct stop_reply *reply = stop_reply_xmalloc ();
5752           old_chain = make_cleanup (do_stop_reply_xfree, reply);
5753
5754           remote_parse_stop_reply (buf + 5, reply);
5755
5756           discard_cleanups (old_chain);
5757
5758           /* Be careful to only set it after parsing, since an error
5759              may be thrown then.  */
5760           pending_stop_reply = reply;
5761
5762           /* Notify the event loop there's a stop reply to acknowledge
5763              and that there may be more events to fetch.  */
5764           mark_async_event_handler (remote_async_get_pending_events_token);
5765         }
5766     }
5767   else
5768     /* We ignore notifications we don't recognize, for compatibility
5769        with newer stubs.  */
5770     ;
5771 }
5772
5773 \f
5774 /* Read or write LEN bytes from inferior memory at MEMADDR,
5775    transferring to or from debugger address BUFFER.  Write to inferior
5776    if SHOULD_WRITE is nonzero.  Returns length of data written or
5777    read; 0 for error.  TARGET is unused.  */
5778
5779 static int
5780 remote_xfer_memory (CORE_ADDR mem_addr, gdb_byte *buffer, int mem_len,
5781                     int should_write, struct mem_attrib *attrib,
5782                     struct target_ops *target)
5783 {
5784   int res;
5785
5786   set_general_thread (inferior_ptid);
5787
5788   if (should_write)
5789     res = remote_write_bytes (mem_addr, buffer, mem_len);
5790   else
5791     res = remote_read_bytes (mem_addr, buffer, mem_len);
5792
5793   return res;
5794 }
5795
5796 /* Sends a packet with content determined by the printf format string
5797    FORMAT and the remaining arguments, then gets the reply.  Returns
5798    whether the packet was a success, a failure, or unknown.  */
5799
5800 static enum packet_result
5801 remote_send_printf (const char *format, ...)
5802 {
5803   struct remote_state *rs = get_remote_state ();
5804   int max_size = get_remote_packet_size ();
5805
5806   va_list ap;
5807   va_start (ap, format);
5808
5809   rs->buf[0] = '\0';
5810   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
5811     internal_error (__FILE__, __LINE__, "Too long remote packet.");
5812
5813   if (putpkt (rs->buf) < 0)
5814     error (_("Communication problem with target."));
5815
5816   rs->buf[0] = '\0';
5817   getpkt (&rs->buf, &rs->buf_size, 0);
5818
5819   return packet_check_result (rs->buf);
5820 }
5821
5822 static void
5823 restore_remote_timeout (void *p)
5824 {
5825   int value = *(int *)p;
5826   remote_timeout = value;
5827 }
5828
5829 /* Flash writing can take quite some time.  We'll set
5830    effectively infinite timeout for flash operations.
5831    In future, we'll need to decide on a better approach.  */
5832 static const int remote_flash_timeout = 1000;
5833
5834 static void
5835 remote_flash_erase (struct target_ops *ops,
5836                     ULONGEST address, LONGEST length)
5837 {
5838   int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
5839   int saved_remote_timeout = remote_timeout;
5840   enum packet_result ret;
5841
5842   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5843                                           &saved_remote_timeout);
5844   remote_timeout = remote_flash_timeout;
5845
5846   ret = remote_send_printf ("vFlashErase:%s,%s",
5847                             phex (address, addr_size),
5848                             phex (length, 4));
5849   switch (ret)
5850     {
5851     case PACKET_UNKNOWN:
5852       error (_("Remote target does not support flash erase"));
5853     case PACKET_ERROR:
5854       error (_("Error erasing flash with vFlashErase packet"));
5855     default:
5856       break;
5857     }
5858
5859   do_cleanups (back_to);
5860 }
5861
5862 static LONGEST
5863 remote_flash_write (struct target_ops *ops,
5864                     ULONGEST address, LONGEST length,
5865                     const gdb_byte *data)
5866 {
5867   int saved_remote_timeout = remote_timeout;
5868   int ret;
5869   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5870                                           &saved_remote_timeout);
5871
5872   remote_timeout = remote_flash_timeout;
5873   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length, 'X', 0);
5874   do_cleanups (back_to);
5875
5876   return ret;
5877 }
5878
5879 static void
5880 remote_flash_done (struct target_ops *ops)
5881 {
5882   int saved_remote_timeout = remote_timeout;
5883   int ret;
5884   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
5885                                           &saved_remote_timeout);
5886
5887   remote_timeout = remote_flash_timeout;
5888   ret = remote_send_printf ("vFlashDone");
5889   do_cleanups (back_to);
5890
5891   switch (ret)
5892     {
5893     case PACKET_UNKNOWN:
5894       error (_("Remote target does not support vFlashDone"));
5895     case PACKET_ERROR:
5896       error (_("Error finishing flash operation"));
5897     default:
5898       break;
5899     }
5900 }
5901
5902 static void
5903 remote_files_info (struct target_ops *ignore)
5904 {
5905   puts_filtered ("Debugging a target over a serial line.\n");
5906 }
5907 \f
5908 /* Stuff for dealing with the packets which are part of this protocol.
5909    See comment at top of file for details.  */
5910
5911 /* Read a single character from the remote end.  */
5912
5913 static int
5914 readchar (int timeout)
5915 {
5916   int ch;
5917
5918   ch = serial_readchar (remote_desc, timeout);
5919
5920   if (ch >= 0)
5921     return ch;
5922
5923   switch ((enum serial_rc) ch)
5924     {
5925     case SERIAL_EOF:
5926       pop_target ();
5927       error (_("Remote connection closed"));
5928       /* no return */
5929     case SERIAL_ERROR:
5930       perror_with_name (_("Remote communication error"));
5931       /* no return */
5932     case SERIAL_TIMEOUT:
5933       break;
5934     }
5935   return ch;
5936 }
5937
5938 /* Send the command in *BUF to the remote machine, and read the reply
5939    into *BUF.  Report an error if we get an error reply.  Resize
5940    *BUF using xrealloc if necessary to hold the result, and update
5941    *SIZEOF_BUF.  */
5942
5943 static void
5944 remote_send (char **buf,
5945              long *sizeof_buf)
5946 {
5947   putpkt (*buf);
5948   getpkt (buf, sizeof_buf, 0);
5949
5950   if ((*buf)[0] == 'E')
5951     error (_("Remote failure reply: %s"), *buf);
5952 }
5953
5954 /* Return a pointer to an xmalloc'ed string representing an escaped
5955    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
5956    etc.  The caller is responsible for releasing the returned
5957    memory.  */
5958
5959 static char *
5960 escape_buffer (const char *buf, int n)
5961 {
5962   struct cleanup *old_chain;
5963   struct ui_file *stb;
5964   char *str;
5965   long length;
5966
5967   stb = mem_fileopen ();
5968   old_chain = make_cleanup_ui_file_delete (stb);
5969
5970   fputstrn_unfiltered (buf, n, 0, stb);
5971   str = ui_file_xstrdup (stb, &length);
5972   do_cleanups (old_chain);
5973   return str;
5974 }
5975
5976 /* Display a null-terminated packet on stdout, for debugging, using C
5977    string notation.  */
5978
5979 static void
5980 print_packet (char *buf)
5981 {
5982   puts_filtered ("\"");
5983   fputstr_filtered (buf, '"', gdb_stdout);
5984   puts_filtered ("\"");
5985 }
5986
5987 int
5988 putpkt (char *buf)
5989 {
5990   return putpkt_binary (buf, strlen (buf));
5991 }
5992
5993 /* Send a packet to the remote machine, with error checking.  The data
5994    of the packet is in BUF.  The string in BUF can be at most
5995    get_remote_packet_size () - 5 to account for the $, # and checksum,
5996    and for a possible /0 if we are debugging (remote_debug) and want
5997    to print the sent packet as a string.  */
5998
5999 static int
6000 putpkt_binary (char *buf, int cnt)
6001 {
6002   struct remote_state *rs = get_remote_state ();
6003   int i;
6004   unsigned char csum = 0;
6005   char *buf2 = alloca (cnt + 6);
6006
6007   int ch;
6008   int tcount = 0;
6009   char *p;
6010
6011   /* Catch cases like trying to read memory or listing threads while
6012      we're waiting for a stop reply.  The remote server wouldn't be
6013      ready to handle this request, so we'd hang and timeout.  We don't
6014      have to worry about this in synchronous mode, because in that
6015      case it's not possible to issue a command while the target is
6016      running.  This is not a problem in non-stop mode, because in that
6017      case, the stub is always ready to process serial input.  */
6018   if (!non_stop && target_can_async_p () && rs->waiting_for_stop_reply)
6019     error (_("Cannot execute this command while the target is running."));
6020
6021   /* We're sending out a new packet.  Make sure we don't look at a
6022      stale cached response.  */
6023   rs->cached_wait_status = 0;
6024
6025   /* Copy the packet into buffer BUF2, encapsulating it
6026      and giving it a checksum.  */
6027
6028   p = buf2;
6029   *p++ = '$';
6030
6031   for (i = 0; i < cnt; i++)
6032     {
6033       csum += buf[i];
6034       *p++ = buf[i];
6035     }
6036   *p++ = '#';
6037   *p++ = tohex ((csum >> 4) & 0xf);
6038   *p++ = tohex (csum & 0xf);
6039
6040   /* Send it over and over until we get a positive ack.  */
6041
6042   while (1)
6043     {
6044       int started_error_output = 0;
6045
6046       if (remote_debug)
6047         {
6048           struct cleanup *old_chain;
6049           char *str;
6050
6051           *p = '\0';
6052           str = escape_buffer (buf2, p - buf2);
6053           old_chain = make_cleanup (xfree, str);
6054           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
6055           gdb_flush (gdb_stdlog);
6056           do_cleanups (old_chain);
6057         }
6058       if (serial_write (remote_desc, buf2, p - buf2))
6059         perror_with_name (_("putpkt: write failed"));
6060
6061       /* If this is a no acks version of the remote protocol, send the
6062          packet and move on.  */
6063       if (rs->noack_mode)
6064         break;
6065
6066       /* Read until either a timeout occurs (-2) or '+' is read.
6067          Handle any notification that arrives in the mean time.  */
6068       while (1)
6069         {
6070           ch = readchar (remote_timeout);
6071
6072           if (remote_debug)
6073             {
6074               switch (ch)
6075                 {
6076                 case '+':
6077                 case '-':
6078                 case SERIAL_TIMEOUT:
6079                 case '$':
6080                 case '%':
6081                   if (started_error_output)
6082                     {
6083                       putchar_unfiltered ('\n');
6084                       started_error_output = 0;
6085                     }
6086                 }
6087             }
6088
6089           switch (ch)
6090             {
6091             case '+':
6092               if (remote_debug)
6093                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
6094               return 1;
6095             case '-':
6096               if (remote_debug)
6097                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
6098             case SERIAL_TIMEOUT:
6099               tcount++;
6100               if (tcount > 3)
6101                 return 0;
6102               break;            /* Retransmit buffer.  */
6103             case '$':
6104               {
6105                 if (remote_debug)
6106                   fprintf_unfiltered (gdb_stdlog,
6107                                       "Packet instead of Ack, ignoring it\n");
6108                 /* It's probably an old response sent because an ACK
6109                    was lost.  Gobble up the packet and ack it so it
6110                    doesn't get retransmitted when we resend this
6111                    packet.  */
6112                 skip_frame ();
6113                 serial_write (remote_desc, "+", 1);
6114                 continue;       /* Now, go look for +.  */
6115               }
6116
6117             case '%':
6118               {
6119                 int val;
6120
6121                 /* If we got a notification, handle it, and go back to looking
6122                    for an ack.  */
6123                 /* We've found the start of a notification.  Now
6124                    collect the data.  */
6125                 val = read_frame (&rs->buf, &rs->buf_size);
6126                 if (val >= 0)
6127                   {
6128                     if (remote_debug)
6129                       {
6130                         struct cleanup *old_chain;
6131                         char *str;
6132
6133                         str = escape_buffer (rs->buf, val);
6134                         old_chain = make_cleanup (xfree, str);
6135                         fprintf_unfiltered (gdb_stdlog,
6136                                             "  Notification received: %s\n",
6137                                             str);
6138                         do_cleanups (old_chain);
6139                       }
6140                     handle_notification (rs->buf, val);
6141                     /* We're in sync now, rewait for the ack.  */
6142                     tcount = 0;
6143                   }
6144                 else
6145                   {
6146                     if (remote_debug)
6147                       {
6148                         if (!started_error_output)
6149                           {
6150                             started_error_output = 1;
6151                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6152                           }
6153                         fputc_unfiltered (ch & 0177, gdb_stdlog);
6154                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
6155                       }
6156                   }
6157                 continue;
6158               }
6159               /* fall-through */
6160             default:
6161               if (remote_debug)
6162                 {
6163                   if (!started_error_output)
6164                     {
6165                       started_error_output = 1;
6166                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
6167                     }
6168                   fputc_unfiltered (ch & 0177, gdb_stdlog);
6169                 }
6170               continue;
6171             }
6172           break;                /* Here to retransmit.  */
6173         }
6174
6175 #if 0
6176       /* This is wrong.  If doing a long backtrace, the user should be
6177          able to get out next time we call QUIT, without anything as
6178          violent as interrupt_query.  If we want to provide a way out of
6179          here without getting to the next QUIT, it should be based on
6180          hitting ^C twice as in remote_wait.  */
6181       if (quit_flag)
6182         {
6183           quit_flag = 0;
6184           interrupt_query ();
6185         }
6186 #endif
6187     }
6188   return 0;
6189 }
6190
6191 /* Come here after finding the start of a frame when we expected an
6192    ack.  Do our best to discard the rest of this packet.  */
6193
6194 static void
6195 skip_frame (void)
6196 {
6197   int c;
6198
6199   while (1)
6200     {
6201       c = readchar (remote_timeout);
6202       switch (c)
6203         {
6204         case SERIAL_TIMEOUT:
6205           /* Nothing we can do.  */
6206           return;
6207         case '#':
6208           /* Discard the two bytes of checksum and stop.  */
6209           c = readchar (remote_timeout);
6210           if (c >= 0)
6211             c = readchar (remote_timeout);
6212
6213           return;
6214         case '*':               /* Run length encoding.  */
6215           /* Discard the repeat count.  */
6216           c = readchar (remote_timeout);
6217           if (c < 0)
6218             return;
6219           break;
6220         default:
6221           /* A regular character.  */
6222           break;
6223         }
6224     }
6225 }
6226
6227 /* Come here after finding the start of the frame.  Collect the rest
6228    into *BUF, verifying the checksum, length, and handling run-length
6229    compression.  NUL terminate the buffer.  If there is not enough room,
6230    expand *BUF using xrealloc.
6231
6232    Returns -1 on error, number of characters in buffer (ignoring the
6233    trailing NULL) on success. (could be extended to return one of the
6234    SERIAL status indications).  */
6235
6236 static long
6237 read_frame (char **buf_p,
6238             long *sizeof_buf)
6239 {
6240   unsigned char csum;
6241   long bc;
6242   int c;
6243   char *buf = *buf_p;
6244   struct remote_state *rs = get_remote_state ();
6245
6246   csum = 0;
6247   bc = 0;
6248
6249   while (1)
6250     {
6251       c = readchar (remote_timeout);
6252       switch (c)
6253         {
6254         case SERIAL_TIMEOUT:
6255           if (remote_debug)
6256             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
6257           return -1;
6258         case '$':
6259           if (remote_debug)
6260             fputs_filtered ("Saw new packet start in middle of old one\n",
6261                             gdb_stdlog);
6262           return -1;            /* Start a new packet, count retries.  */
6263         case '#':
6264           {
6265             unsigned char pktcsum;
6266             int check_0 = 0;
6267             int check_1 = 0;
6268
6269             buf[bc] = '\0';
6270
6271             check_0 = readchar (remote_timeout);
6272             if (check_0 >= 0)
6273               check_1 = readchar (remote_timeout);
6274
6275             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
6276               {
6277                 if (remote_debug)
6278                   fputs_filtered ("Timeout in checksum, retrying\n",
6279                                   gdb_stdlog);
6280                 return -1;
6281               }
6282             else if (check_0 < 0 || check_1 < 0)
6283               {
6284                 if (remote_debug)
6285                   fputs_filtered ("Communication error in checksum\n",
6286                                   gdb_stdlog);
6287                 return -1;
6288               }
6289
6290             /* Don't recompute the checksum; with no ack packets we
6291                don't have any way to indicate a packet retransmission
6292                is necessary.  */
6293             if (rs->noack_mode)
6294               return bc;
6295
6296             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
6297             if (csum == pktcsum)
6298               return bc;
6299
6300             if (remote_debug)
6301               {
6302                 struct cleanup *old_chain;
6303                 char *str;
6304
6305                 str = escape_buffer (buf, bc);
6306                 old_chain = make_cleanup (xfree, str);
6307                 fprintf_unfiltered (gdb_stdlog,
6308                                     "\
6309 Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
6310                                     pktcsum, csum, str);
6311                 do_cleanups (old_chain);
6312               }
6313             /* Number of characters in buffer ignoring trailing
6314                NULL.  */
6315             return -1;
6316           }
6317         case '*':               /* Run length encoding.  */
6318           {
6319             int repeat;
6320             csum += c;
6321
6322             c = readchar (remote_timeout);
6323             csum += c;
6324             repeat = c - ' ' + 3;       /* Compute repeat count.  */
6325
6326             /* The character before ``*'' is repeated.  */
6327
6328             if (repeat > 0 && repeat <= 255 && bc > 0)
6329               {
6330                 if (bc + repeat - 1 >= *sizeof_buf - 1)
6331                   {
6332                     /* Make some more room in the buffer.  */
6333                     *sizeof_buf += repeat;
6334                     *buf_p = xrealloc (*buf_p, *sizeof_buf);
6335                     buf = *buf_p;
6336                   }
6337
6338                 memset (&buf[bc], buf[bc - 1], repeat);
6339                 bc += repeat;
6340                 continue;
6341               }
6342
6343             buf[bc] = '\0';
6344             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
6345             return -1;
6346           }
6347         default:
6348           if (bc >= *sizeof_buf - 1)
6349             {
6350               /* Make some more room in the buffer.  */
6351               *sizeof_buf *= 2;
6352               *buf_p = xrealloc (*buf_p, *sizeof_buf);
6353               buf = *buf_p;
6354             }
6355
6356           buf[bc++] = c;
6357           csum += c;
6358           continue;
6359         }
6360     }
6361 }
6362
6363 /* Read a packet from the remote machine, with error checking, and
6364    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
6365    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
6366    rather than timing out; this is used (in synchronous mode) to wait
6367    for a target that is is executing user code to stop.  */
6368 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
6369    don't have to change all the calls to getpkt to deal with the
6370    return value, because at the moment I don't know what the right
6371    thing to do it for those.  */
6372 void
6373 getpkt (char **buf,
6374         long *sizeof_buf,
6375         int forever)
6376 {
6377   int timed_out;
6378
6379   timed_out = getpkt_sane (buf, sizeof_buf, forever);
6380 }
6381
6382
6383 /* Read a packet from the remote machine, with error checking, and
6384    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
6385    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
6386    rather than timing out; this is used (in synchronous mode) to wait
6387    for a target that is is executing user code to stop.  If FOREVER ==
6388    0, this function is allowed to time out gracefully and return an
6389    indication of this to the caller.  Otherwise return the number of
6390    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
6391    enough reason to return to the caller.  */
6392
6393 static int
6394 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
6395                         int expecting_notif)
6396 {
6397   struct remote_state *rs = get_remote_state ();
6398   int c;
6399   int tries;
6400   int timeout;
6401   int val = -1;
6402
6403   /* We're reading a new response.  Make sure we don't look at a
6404      previously cached response.  */
6405   rs->cached_wait_status = 0;
6406
6407   strcpy (*buf, "timeout");
6408
6409   if (forever)
6410     timeout = watchdog > 0 ? watchdog : -1;
6411   else if (expecting_notif)
6412     timeout = 0; /* There should already be a char in the buffer.  If
6413                     not, bail out.  */
6414   else
6415     timeout = remote_timeout;
6416
6417 #define MAX_TRIES 3
6418
6419   /* Process any number of notifications, and then return when
6420      we get a packet.  */
6421   for (;;)
6422     {
6423       /* If we get a timeout or bad checksm, retry up to MAX_TRIES
6424          times.  */
6425       for (tries = 1; tries <= MAX_TRIES; tries++)
6426         {
6427           /* This can loop forever if the remote side sends us
6428              characters continuously, but if it pauses, we'll get
6429              SERIAL_TIMEOUT from readchar because of timeout.  Then
6430              we'll count that as a retry.
6431
6432              Note that even when forever is set, we will only wait
6433              forever prior to the start of a packet.  After that, we
6434              expect characters to arrive at a brisk pace.  They should
6435              show up within remote_timeout intervals.  */
6436           do
6437             c = readchar (timeout);
6438           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
6439
6440           if (c == SERIAL_TIMEOUT)
6441             {
6442               if (expecting_notif)
6443                 return -1; /* Don't complain, it's normal to not get
6444                               anything in this case.  */
6445
6446               if (forever)      /* Watchdog went off?  Kill the target.  */
6447                 {
6448                   QUIT;
6449                   pop_target ();
6450                   error (_("Watchdog timeout has expired.  Target detached."));
6451                 }
6452               if (remote_debug)
6453                 fputs_filtered ("Timed out.\n", gdb_stdlog);
6454             }
6455           else
6456             {
6457               /* We've found the start of a packet or notification.
6458                  Now collect the data.  */
6459               val = read_frame (buf, sizeof_buf);
6460               if (val >= 0)
6461                 break;
6462             }
6463
6464           serial_write (remote_desc, "-", 1);
6465         }
6466
6467       if (tries > MAX_TRIES)
6468         {
6469           /* We have tried hard enough, and just can't receive the
6470              packet/notification.  Give up.  */
6471           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
6472
6473           /* Skip the ack char if we're in no-ack mode.  */
6474           if (!rs->noack_mode)
6475             serial_write (remote_desc, "+", 1);
6476           return -1;
6477         }
6478
6479       /* If we got an ordinary packet, return that to our caller.  */
6480       if (c == '$')
6481         {
6482           if (remote_debug)
6483             {
6484              struct cleanup *old_chain;
6485              char *str;
6486
6487              str = escape_buffer (*buf, val);
6488              old_chain = make_cleanup (xfree, str);
6489              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
6490              do_cleanups (old_chain);
6491             }
6492
6493           /* Skip the ack char if we're in no-ack mode.  */
6494           if (!rs->noack_mode)
6495             serial_write (remote_desc, "+", 1);
6496           return val;
6497         }
6498
6499        /* If we got a notification, handle it, and go back to looking
6500          for a packet.  */
6501       else
6502         {
6503           gdb_assert (c == '%');
6504
6505           if (remote_debug)
6506             {
6507               struct cleanup *old_chain;
6508               char *str;
6509
6510               str = escape_buffer (*buf, val);
6511               old_chain = make_cleanup (xfree, str);
6512               fprintf_unfiltered (gdb_stdlog,
6513                                   "  Notification received: %s\n",
6514                                   str);
6515               do_cleanups (old_chain);
6516             }
6517
6518           handle_notification (*buf, val);
6519
6520           /* Notifications require no acknowledgement.  */
6521
6522           if (expecting_notif)
6523             return -1;
6524         }
6525     }
6526 }
6527
6528 static int
6529 getpkt_sane (char **buf, long *sizeof_buf, int forever)
6530 {
6531   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0);
6532 }
6533
6534 static int
6535 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever)
6536 {
6537   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1);
6538 }
6539
6540 \f
6541 static void
6542 remote_kill (struct target_ops *ops)
6543 {
6544   /* Use catch_errors so the user can quit from gdb even when we
6545      aren't on speaking terms with the remote system.  */
6546   catch_errors ((catch_errors_ftype *) putpkt, "k", "", RETURN_MASK_ERROR);
6547
6548   /* Don't wait for it to die.  I'm not really sure it matters whether
6549      we do or not.  For the existing stubs, kill is a noop.  */
6550   target_mourn_inferior ();
6551 }
6552
6553 static int
6554 remote_vkill (int pid, struct remote_state *rs)
6555 {
6556   if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6557     return -1;
6558
6559   /* Tell the remote target to detach.  */
6560   sprintf (rs->buf, "vKill;%x", pid);
6561   putpkt (rs->buf);
6562   getpkt (&rs->buf, &rs->buf_size, 0);
6563
6564   if (packet_ok (rs->buf,
6565                  &remote_protocol_packets[PACKET_vKill]) == PACKET_OK)
6566     return 0;
6567   else if (remote_protocol_packets[PACKET_vKill].support == PACKET_DISABLE)
6568     return -1;
6569   else
6570     return 1;
6571 }
6572
6573 static void
6574 extended_remote_kill (struct target_ops *ops)
6575 {
6576   int res;
6577   int pid = ptid_get_pid (inferior_ptid);
6578   struct remote_state *rs = get_remote_state ();
6579
6580   res = remote_vkill (pid, rs);
6581   if (res == -1 && !remote_multi_process_p (rs))
6582     {
6583       /* Don't try 'k' on a multi-process aware stub -- it has no way
6584          to specify the pid.  */
6585
6586       putpkt ("k");
6587 #if 0
6588       getpkt (&rs->buf, &rs->buf_size, 0);
6589       if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
6590         res = 1;
6591 #else
6592       /* Don't wait for it to die.  I'm not really sure it matters whether
6593          we do or not.  For the existing stubs, kill is a noop.  */
6594       res = 0;
6595 #endif
6596     }
6597
6598   if (res != 0)
6599     error (_("Can't kill process"));
6600
6601   target_mourn_inferior ();
6602 }
6603
6604 static void
6605 remote_mourn (struct target_ops *ops)
6606 {
6607   remote_mourn_1 (ops);
6608 }
6609
6610 /* Worker function for remote_mourn.  */
6611 static void
6612 remote_mourn_1 (struct target_ops *target)
6613 {
6614   unpush_target (target);
6615
6616   /* remote_close takes care of doing most of the clean up.  */
6617   generic_mourn_inferior ();
6618 }
6619
6620 static void
6621 extended_remote_mourn_1 (struct target_ops *target)
6622 {
6623   struct remote_state *rs = get_remote_state ();
6624
6625   /* In case we got here due to an error, but we're going to stay
6626      connected.  */
6627   rs->waiting_for_stop_reply = 0;
6628
6629   /* We're no longer interested in these events.  */
6630   discard_pending_stop_replies (ptid_get_pid (inferior_ptid));
6631
6632   /* If the current general thread belonged to the process we just
6633      detached from or has exited, the remote side current general
6634      thread becomes undefined.  Considering a case like this:
6635
6636      - We just got here due to a detach.
6637      - The process that we're detaching from happens to immediately
6638        report a global breakpoint being hit in non-stop mode, in the
6639        same thread we had selected before.
6640      - GDB attaches to this process again.
6641      - This event happens to be the next event we handle.
6642
6643      GDB would consider that the current general thread didn't need to
6644      be set on the stub side (with Hg), since for all it knew,
6645      GENERAL_THREAD hadn't changed.
6646
6647      Notice that although in all-stop mode, the remote server always
6648      sets the current thread to the thread reporting the stop event,
6649      that doesn't happen in non-stop mode; in non-stop, the stub *must
6650      not* change the current thread when reporting a breakpoint hit,
6651      due to the decoupling of event reporting and event handling.
6652
6653      To keep things simple, we always invalidate our notion of the
6654      current thread.  */
6655   record_currthread (minus_one_ptid);
6656
6657   /* Unlike "target remote", we do not want to unpush the target; then
6658      the next time the user says "run", we won't be connected.  */
6659
6660   /* Call common code to mark the inferior as not running.      */
6661   generic_mourn_inferior ();
6662
6663   if (!have_inferiors ())
6664     {
6665       if (!remote_multi_process_p (rs))
6666         {
6667           /* Check whether the target is running now - some remote stubs
6668              automatically restart after kill.  */
6669           putpkt ("?");
6670           getpkt (&rs->buf, &rs->buf_size, 0);
6671
6672           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
6673             {
6674               /* Assume that the target has been restarted.  Set inferior_ptid
6675                  so that bits of core GDB realizes there's something here, e.g.,
6676                  so that the user can say "kill" again.  */
6677               inferior_ptid = magic_null_ptid;
6678             }
6679         }
6680     }
6681 }
6682
6683 static void
6684 extended_remote_mourn (struct target_ops *ops)
6685 {
6686   extended_remote_mourn_1 (ops);
6687 }
6688
6689 static int
6690 extended_remote_run (char *args)
6691 {
6692   struct remote_state *rs = get_remote_state ();
6693   char *p;
6694   int len;
6695
6696   /* If the user has disabled vRun support, or we have detected that
6697      support is not available, do not try it.  */
6698   if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6699     return -1;
6700
6701   strcpy (rs->buf, "vRun;");
6702   len = strlen (rs->buf);
6703
6704   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
6705     error (_("Remote file name too long for run packet"));
6706   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len, 0);
6707
6708   gdb_assert (args != NULL);
6709   if (*args)
6710     {
6711       struct cleanup *back_to;
6712       int i;
6713       char **argv;
6714
6715       argv = gdb_buildargv (args);
6716       back_to = make_cleanup ((void (*) (void *)) freeargv, argv);
6717       for (i = 0; argv[i] != NULL; i++)
6718         {
6719           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
6720             error (_("Argument list too long for run packet"));
6721           rs->buf[len++] = ';';
6722           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len, 0);
6723         }
6724       do_cleanups (back_to);
6725     }
6726
6727   rs->buf[len++] = '\0';
6728
6729   putpkt (rs->buf);
6730   getpkt (&rs->buf, &rs->buf_size, 0);
6731
6732   if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]) == PACKET_OK)
6733     {
6734       /* We have a wait response; we don't need it, though.  All is well.  */
6735       return 0;
6736     }
6737   else if (remote_protocol_packets[PACKET_vRun].support == PACKET_DISABLE)
6738     /* It wasn't disabled before, but it is now.  */
6739     return -1;
6740   else
6741     {
6742       if (remote_exec_file[0] == '\0')
6743         error (_("Running the default executable on the remote target failed; "
6744                  "try \"set remote exec-file\"?"));
6745       else
6746         error (_("Running \"%s\" on the remote target failed"),
6747                remote_exec_file);
6748     }
6749 }
6750
6751 /* In the extended protocol we want to be able to do things like
6752    "run" and have them basically work as expected.  So we need
6753    a special create_inferior function.  We support changing the
6754    executable file and the command line arguments, but not the
6755    environment.  */
6756
6757 static void
6758 extended_remote_create_inferior_1 (char *exec_file, char *args,
6759                                    char **env, int from_tty)
6760 {
6761   /* If running asynchronously, register the target file descriptor
6762      with the event loop.  */
6763   if (target_can_async_p ())
6764     target_async (inferior_event_handler, 0);
6765
6766   /* Now restart the remote server.  */
6767   if (extended_remote_run (args) == -1)
6768     {
6769       /* vRun was not supported.  Fail if we need it to do what the
6770          user requested.  */
6771       if (remote_exec_file[0])
6772         error (_("Remote target does not support \"set remote exec-file\""));
6773       if (args[0])
6774         error (_("Remote target does not support \"set args\" or run <ARGS>"));
6775
6776       /* Fall back to "R".  */
6777       extended_remote_restart ();
6778     }
6779
6780   /* Clean up from the last time we ran, before we mark the target
6781      running again.  This will mark breakpoints uninserted, and
6782      get_offsets may insert breakpoints.  */
6783   init_thread_list ();
6784   init_wait_for_inferior ();
6785
6786   /* Now mark the inferior as running before we do anything else.  */
6787   inferior_ptid = magic_null_ptid;
6788
6789   /* Now, if we have thread information, update inferior_ptid.  */
6790   inferior_ptid = remote_current_thread (inferior_ptid);
6791
6792   remote_add_inferior (ptid_get_pid (inferior_ptid), 0);
6793   add_thread_silent (inferior_ptid);
6794
6795   /* Get updated offsets, if the stub uses qOffsets.  */
6796   get_offsets ();
6797 }
6798
6799 static void
6800 extended_remote_create_inferior (struct target_ops *ops, 
6801                                  char *exec_file, char *args,
6802                                  char **env, int from_tty)
6803 {
6804   extended_remote_create_inferior_1 (exec_file, args, env, from_tty);
6805 }
6806 \f
6807
6808 /* Insert a breakpoint.  On targets that have software breakpoint
6809    support, we ask the remote target to do the work; on targets
6810    which don't, we insert a traditional memory breakpoint.  */
6811
6812 static int
6813 remote_insert_breakpoint (struct gdbarch *gdbarch,
6814                           struct bp_target_info *bp_tgt)
6815 {
6816   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
6817      If it succeeds, then set the support to PACKET_ENABLE.  If it
6818      fails, and the user has explicitly requested the Z support then
6819      report an error, otherwise, mark it disabled and go on.  */
6820
6821   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6822     {
6823       CORE_ADDR addr = bp_tgt->placed_address;
6824       struct remote_state *rs;
6825       char *p;
6826       int bpsize;
6827
6828       gdbarch_breakpoint_from_pc (gdbarch, &addr, &bpsize);
6829
6830       rs = get_remote_state ();
6831       p = rs->buf;
6832
6833       *(p++) = 'Z';
6834       *(p++) = '0';
6835       *(p++) = ',';
6836       addr = (ULONGEST) remote_address_masked (addr);
6837       p += hexnumstr (p, addr);
6838       sprintf (p, ",%d", bpsize);
6839
6840       putpkt (rs->buf);
6841       getpkt (&rs->buf, &rs->buf_size, 0);
6842
6843       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
6844         {
6845         case PACKET_ERROR:
6846           return -1;
6847         case PACKET_OK:
6848           bp_tgt->placed_address = addr;
6849           bp_tgt->placed_size = bpsize;
6850           return 0;
6851         case PACKET_UNKNOWN:
6852           break;
6853         }
6854     }
6855
6856   return memory_insert_breakpoint (gdbarch, bp_tgt);
6857 }
6858
6859 static int
6860 remote_remove_breakpoint (struct gdbarch *gdbarch,
6861                           struct bp_target_info *bp_tgt)
6862 {
6863   CORE_ADDR addr = bp_tgt->placed_address;
6864   struct remote_state *rs = get_remote_state ();
6865   int bp_size;
6866
6867   if (remote_protocol_packets[PACKET_Z0].support != PACKET_DISABLE)
6868     {
6869       char *p = rs->buf;
6870
6871       *(p++) = 'z';
6872       *(p++) = '0';
6873       *(p++) = ',';
6874
6875       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
6876       p += hexnumstr (p, addr);
6877       sprintf (p, ",%d", bp_tgt->placed_size);
6878
6879       putpkt (rs->buf);
6880       getpkt (&rs->buf, &rs->buf_size, 0);
6881
6882       return (rs->buf[0] == 'E');
6883     }
6884
6885   return memory_remove_breakpoint (gdbarch, bp_tgt);
6886 }
6887
6888 static int
6889 watchpoint_to_Z_packet (int type)
6890 {
6891   switch (type)
6892     {
6893     case hw_write:
6894       return Z_PACKET_WRITE_WP;
6895       break;
6896     case hw_read:
6897       return Z_PACKET_READ_WP;
6898       break;
6899     case hw_access:
6900       return Z_PACKET_ACCESS_WP;
6901       break;
6902     default:
6903       internal_error (__FILE__, __LINE__,
6904                       _("hw_bp_to_z: bad watchpoint type %d"), type);
6905     }
6906 }
6907
6908 static int
6909 remote_insert_watchpoint (CORE_ADDR addr, int len, int type)
6910 {
6911   struct remote_state *rs = get_remote_state ();
6912   char *p;
6913   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
6914
6915   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
6916     return -1;
6917
6918   sprintf (rs->buf, "Z%x,", packet);
6919   p = strchr (rs->buf, '\0');
6920   addr = remote_address_masked (addr);
6921   p += hexnumstr (p, (ULONGEST) addr);
6922   sprintf (p, ",%x", len);
6923
6924   putpkt (rs->buf);
6925   getpkt (&rs->buf, &rs->buf_size, 0);
6926
6927   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
6928     {
6929     case PACKET_ERROR:
6930     case PACKET_UNKNOWN:
6931       return -1;
6932     case PACKET_OK:
6933       return 0;
6934     }
6935   internal_error (__FILE__, __LINE__,
6936                   _("remote_insert_watchpoint: reached end of function"));
6937 }
6938
6939
6940 static int
6941 remote_remove_watchpoint (CORE_ADDR addr, int len, int type)
6942 {
6943   struct remote_state *rs = get_remote_state ();
6944   char *p;
6945   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
6946
6947   if (remote_protocol_packets[PACKET_Z0 + packet].support == PACKET_DISABLE)
6948     return -1;
6949
6950   sprintf (rs->buf, "z%x,", packet);
6951   p = strchr (rs->buf, '\0');
6952   addr = remote_address_masked (addr);
6953   p += hexnumstr (p, (ULONGEST) addr);
6954   sprintf (p, ",%x", len);
6955   putpkt (rs->buf);
6956   getpkt (&rs->buf, &rs->buf_size, 0);
6957
6958   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
6959     {
6960     case PACKET_ERROR:
6961     case PACKET_UNKNOWN:
6962       return -1;
6963     case PACKET_OK:
6964       return 0;
6965     }
6966   internal_error (__FILE__, __LINE__,
6967                   _("remote_remove_watchpoint: reached end of function"));
6968 }
6969
6970
6971 int remote_hw_watchpoint_limit = -1;
6972 int remote_hw_breakpoint_limit = -1;
6973
6974 static int
6975 remote_check_watch_resources (int type, int cnt, int ot)
6976 {
6977   if (type == bp_hardware_breakpoint)
6978     {
6979       if (remote_hw_breakpoint_limit == 0)
6980         return 0;
6981       else if (remote_hw_breakpoint_limit < 0)
6982         return 1;
6983       else if (cnt <= remote_hw_breakpoint_limit)
6984         return 1;
6985     }
6986   else
6987     {
6988       if (remote_hw_watchpoint_limit == 0)
6989         return 0;
6990       else if (remote_hw_watchpoint_limit < 0)
6991         return 1;
6992       else if (ot)
6993         return -1;
6994       else if (cnt <= remote_hw_watchpoint_limit)
6995         return 1;
6996     }
6997   return -1;
6998 }
6999
7000 static int
7001 remote_stopped_by_watchpoint (void)
7002 {
7003   return remote_stopped_by_watchpoint_p;
7004 }
7005
7006 static int
7007 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
7008 {
7009   int rc = 0;
7010   if (remote_stopped_by_watchpoint ())
7011     {
7012       *addr_p = remote_watch_data_address;
7013       rc = 1;
7014     }
7015
7016   return rc;
7017 }
7018
7019
7020 static int
7021 remote_insert_hw_breakpoint (struct gdbarch *gdbarch,
7022                              struct bp_target_info *bp_tgt)
7023 {
7024   CORE_ADDR addr;
7025   struct remote_state *rs;
7026   char *p;
7027
7028   /* The length field should be set to the size of a breakpoint
7029      instruction, even though we aren't inserting one ourselves.  */
7030
7031   gdbarch_breakpoint_from_pc
7032     (gdbarch, &bp_tgt->placed_address, &bp_tgt->placed_size);
7033
7034   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7035     return -1;
7036
7037   rs = get_remote_state ();
7038   p = rs->buf;
7039
7040   *(p++) = 'Z';
7041   *(p++) = '1';
7042   *(p++) = ',';
7043
7044   addr = remote_address_masked (bp_tgt->placed_address);
7045   p += hexnumstr (p, (ULONGEST) addr);
7046   sprintf (p, ",%x", bp_tgt->placed_size);
7047
7048   putpkt (rs->buf);
7049   getpkt (&rs->buf, &rs->buf_size, 0);
7050
7051   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7052     {
7053     case PACKET_ERROR:
7054     case PACKET_UNKNOWN:
7055       return -1;
7056     case PACKET_OK:
7057       return 0;
7058     }
7059   internal_error (__FILE__, __LINE__,
7060                   _("remote_insert_hw_breakpoint: reached end of function"));
7061 }
7062
7063
7064 static int
7065 remote_remove_hw_breakpoint (struct gdbarch *gdbarch,
7066                              struct bp_target_info *bp_tgt)
7067 {
7068   CORE_ADDR addr;
7069   struct remote_state *rs = get_remote_state ();
7070   char *p = rs->buf;
7071
7072   if (remote_protocol_packets[PACKET_Z1].support == PACKET_DISABLE)
7073     return -1;
7074
7075   *(p++) = 'z';
7076   *(p++) = '1';
7077   *(p++) = ',';
7078
7079   addr = remote_address_masked (bp_tgt->placed_address);
7080   p += hexnumstr (p, (ULONGEST) addr);
7081   sprintf (p, ",%x", bp_tgt->placed_size);
7082
7083   putpkt (rs->buf);
7084   getpkt (&rs->buf, &rs->buf_size, 0);
7085
7086   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
7087     {
7088     case PACKET_ERROR:
7089     case PACKET_UNKNOWN:
7090       return -1;
7091     case PACKET_OK:
7092       return 0;
7093     }
7094   internal_error (__FILE__, __LINE__,
7095                   _("remote_remove_hw_breakpoint: reached end of function"));
7096 }
7097
7098 /* Table used by the crc32 function to calcuate the checksum.  */
7099
7100 static unsigned long crc32_table[256] =
7101 {0, 0};
7102
7103 static unsigned long
7104 crc32 (unsigned char *buf, int len, unsigned int crc)
7105 {
7106   if (!crc32_table[1])
7107     {
7108       /* Initialize the CRC table and the decoding table.  */
7109       int i, j;
7110       unsigned int c;
7111
7112       for (i = 0; i < 256; i++)
7113         {
7114           for (c = i << 24, j = 8; j > 0; --j)
7115             c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : (c << 1);
7116           crc32_table[i] = c;
7117         }
7118     }
7119
7120   while (len--)
7121     {
7122       crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ *buf) & 255];
7123       buf++;
7124     }
7125   return crc;
7126 }
7127
7128 /* compare-sections command
7129
7130    With no arguments, compares each loadable section in the exec bfd
7131    with the same memory range on the target, and reports mismatches.
7132    Useful for verifying the image on the target against the exec file.
7133    Depends on the target understanding the new "qCRC:" request.  */
7134
7135 /* FIXME: cagney/1999-10-26: This command should be broken down into a
7136    target method (target verify memory) and generic version of the
7137    actual command.  This will allow other high-level code (especially
7138    generic_load()) to make use of this target functionality.  */
7139
7140 static void
7141 compare_sections_command (char *args, int from_tty)
7142 {
7143   struct remote_state *rs = get_remote_state ();
7144   asection *s;
7145   unsigned long host_crc, target_crc;
7146   struct cleanup *old_chain;
7147   char *tmp;
7148   char *sectdata;
7149   const char *sectname;
7150   bfd_size_type size;
7151   bfd_vma lma;
7152   int matched = 0;
7153   int mismatched = 0;
7154
7155   if (!exec_bfd)
7156     error (_("command cannot be used without an exec file"));
7157   if (!current_target.to_shortname ||
7158       strcmp (current_target.to_shortname, "remote") != 0)
7159     error (_("command can only be used with remote target"));
7160
7161   for (s = exec_bfd->sections; s; s = s->next)
7162     {
7163       if (!(s->flags & SEC_LOAD))
7164         continue;               /* skip non-loadable section */
7165
7166       size = bfd_get_section_size (s);
7167       if (size == 0)
7168         continue;               /* skip zero-length section */
7169
7170       sectname = bfd_get_section_name (exec_bfd, s);
7171       if (args && strcmp (args, sectname) != 0)
7172         continue;               /* not the section selected by user */
7173
7174       matched = 1;              /* do this section */
7175       lma = s->lma;
7176       /* FIXME: assumes lma can fit into long.  */
7177       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
7178                  (long) lma, (long) size);
7179       putpkt (rs->buf);
7180
7181       /* Be clever; compute the host_crc before waiting for target
7182          reply.  */
7183       sectdata = xmalloc (size);
7184       old_chain = make_cleanup (xfree, sectdata);
7185       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
7186       host_crc = crc32 ((unsigned char *) sectdata, size, 0xffffffff);
7187
7188       getpkt (&rs->buf, &rs->buf_size, 0);
7189       if (rs->buf[0] == 'E')
7190         error (_("target memory fault, section %s, range %s -- %s"), sectname,
7191                paddress (target_gdbarch, lma),
7192                paddress (target_gdbarch, lma + size));
7193       if (rs->buf[0] != 'C')
7194         error (_("remote target does not support this operation"));
7195
7196       for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
7197         target_crc = target_crc * 16 + fromhex (*tmp);
7198
7199       printf_filtered ("Section %s, range %s -- %s: ", sectname,
7200                        paddress (target_gdbarch, lma),
7201                        paddress (target_gdbarch, lma + size));
7202       if (host_crc == target_crc)
7203         printf_filtered ("matched.\n");
7204       else
7205         {
7206           printf_filtered ("MIS-MATCHED!\n");
7207           mismatched++;
7208         }
7209
7210       do_cleanups (old_chain);
7211     }
7212   if (mismatched > 0)
7213     warning (_("One or more sections of the remote executable does not match\n\
7214 the loaded file\n"));
7215   if (args && !matched)
7216     printf_filtered (_("No loaded section named '%s'.\n"), args);
7217 }
7218
7219 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
7220    into remote target.  The number of bytes written to the remote
7221    target is returned, or -1 for error.  */
7222
7223 static LONGEST
7224 remote_write_qxfer (struct target_ops *ops, const char *object_name,
7225                     const char *annex, const gdb_byte *writebuf, 
7226                     ULONGEST offset, LONGEST len, 
7227                     struct packet_config *packet)
7228 {
7229   int i, buf_len;
7230   ULONGEST n;
7231   gdb_byte *wbuf;
7232   struct remote_state *rs = get_remote_state ();
7233   int max_size = get_memory_write_packet_size (); 
7234
7235   if (packet->support == PACKET_DISABLE)
7236     return -1;
7237
7238   /* Insert header.  */
7239   i = snprintf (rs->buf, max_size, 
7240                 "qXfer:%s:write:%s:%s:",
7241                 object_name, annex ? annex : "",
7242                 phex_nz (offset, sizeof offset));
7243   max_size -= (i + 1);
7244
7245   /* Escape as much data as fits into rs->buf.  */
7246   buf_len = remote_escape_output 
7247     (writebuf, len, (rs->buf + i), &max_size, max_size);
7248
7249   if (putpkt_binary (rs->buf, i + buf_len) < 0
7250       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7251       || packet_ok (rs->buf, packet) != PACKET_OK)
7252     return -1;
7253
7254   unpack_varlen_hex (rs->buf, &n);
7255   return n;
7256 }
7257
7258 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
7259    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
7260    number of bytes read is returned, or 0 for EOF, or -1 for error.
7261    The number of bytes read may be less than LEN without indicating an
7262    EOF.  PACKET is checked and updated to indicate whether the remote
7263    target supports this object.  */
7264
7265 static LONGEST
7266 remote_read_qxfer (struct target_ops *ops, const char *object_name,
7267                    const char *annex,
7268                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
7269                    struct packet_config *packet)
7270 {
7271   static char *finished_object;
7272   static char *finished_annex;
7273   static ULONGEST finished_offset;
7274
7275   struct remote_state *rs = get_remote_state ();
7276   unsigned int total = 0;
7277   LONGEST i, n, packet_len;
7278
7279   if (packet->support == PACKET_DISABLE)
7280     return -1;
7281
7282   /* Check whether we've cached an end-of-object packet that matches
7283      this request.  */
7284   if (finished_object)
7285     {
7286       if (strcmp (object_name, finished_object) == 0
7287           && strcmp (annex ? annex : "", finished_annex) == 0
7288           && offset == finished_offset)
7289         return 0;
7290
7291       /* Otherwise, we're now reading something different.  Discard
7292          the cache.  */
7293       xfree (finished_object);
7294       xfree (finished_annex);
7295       finished_object = NULL;
7296       finished_annex = NULL;
7297     }
7298
7299   /* Request only enough to fit in a single packet.  The actual data
7300      may not, since we don't know how much of it will need to be escaped;
7301      the target is free to respond with slightly less data.  We subtract
7302      five to account for the response type and the protocol frame.  */
7303   n = min (get_remote_packet_size () - 5, len);
7304   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
7305             object_name, annex ? annex : "",
7306             phex_nz (offset, sizeof offset),
7307             phex_nz (n, sizeof n));
7308   i = putpkt (rs->buf);
7309   if (i < 0)
7310     return -1;
7311
7312   rs->buf[0] = '\0';
7313   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
7314   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
7315     return -1;
7316
7317   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
7318     error (_("Unknown remote qXfer reply: %s"), rs->buf);
7319
7320   /* 'm' means there is (or at least might be) more data after this
7321      batch.  That does not make sense unless there's at least one byte
7322      of data in this reply.  */
7323   if (rs->buf[0] == 'm' && packet_len == 1)
7324     error (_("Remote qXfer reply contained no data."));
7325
7326   /* Got some data.  */
7327   i = remote_unescape_input (rs->buf + 1, packet_len - 1, readbuf, n);
7328
7329   /* 'l' is an EOF marker, possibly including a final block of data,
7330      or possibly empty.  If we have the final block of a non-empty
7331      object, record this fact to bypass a subsequent partial read.  */
7332   if (rs->buf[0] == 'l' && offset + i > 0)
7333     {
7334       finished_object = xstrdup (object_name);
7335       finished_annex = xstrdup (annex ? annex : "");
7336       finished_offset = offset + i;
7337     }
7338
7339   return i;
7340 }
7341
7342 static LONGEST
7343 remote_xfer_partial (struct target_ops *ops, enum target_object object,
7344                      const char *annex, gdb_byte *readbuf,
7345                      const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
7346 {
7347   struct remote_state *rs;
7348   int i;
7349   char *p2;
7350   char query_type;
7351
7352   set_general_thread (inferior_ptid);
7353
7354   rs = get_remote_state ();
7355
7356   /* Handle memory using the standard memory routines.  */
7357   if (object == TARGET_OBJECT_MEMORY)
7358     {
7359       int xfered;
7360       errno = 0;
7361
7362       /* If the remote target is connected but not running, we should
7363          pass this request down to a lower stratum (e.g. the executable
7364          file).  */
7365       if (!target_has_execution)
7366         return 0;
7367
7368       if (writebuf != NULL)
7369         xfered = remote_write_bytes (offset, writebuf, len);
7370       else
7371         xfered = remote_read_bytes (offset, readbuf, len);
7372
7373       if (xfered > 0)
7374         return xfered;
7375       else if (xfered == 0 && errno == 0)
7376         return 0;
7377       else
7378         return -1;
7379     }
7380
7381   /* Handle SPU memory using qxfer packets. */
7382   if (object == TARGET_OBJECT_SPU)
7383     {
7384       if (readbuf)
7385         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
7386                                   &remote_protocol_packets
7387                                     [PACKET_qXfer_spu_read]);
7388       else
7389         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
7390                                    &remote_protocol_packets
7391                                      [PACKET_qXfer_spu_write]);
7392     }
7393
7394   /* Handle extra signal info using qxfer packets.  */
7395   if (object == TARGET_OBJECT_SIGNAL_INFO)
7396     {
7397       if (readbuf)
7398         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
7399                                   &remote_protocol_packets
7400                                   [PACKET_qXfer_siginfo_read]);
7401       else
7402         return remote_write_qxfer (ops, "siginfo", annex, writebuf, offset, len,
7403                                    &remote_protocol_packets
7404                                    [PACKET_qXfer_siginfo_write]);
7405     }
7406
7407   /* Only handle flash writes.  */
7408   if (writebuf != NULL)
7409     {
7410       LONGEST xfered;
7411
7412       switch (object)
7413         {
7414         case TARGET_OBJECT_FLASH:
7415           xfered = remote_flash_write (ops, offset, len, writebuf);
7416
7417           if (xfered > 0)
7418             return xfered;
7419           else if (xfered == 0 && errno == 0)
7420             return 0;
7421           else
7422             return -1;
7423
7424         default:
7425           return -1;
7426         }
7427     }
7428
7429   /* Map pre-existing objects onto letters.  DO NOT do this for new
7430      objects!!!  Instead specify new query packets.  */
7431   switch (object)
7432     {
7433     case TARGET_OBJECT_AVR:
7434       query_type = 'R';
7435       break;
7436
7437     case TARGET_OBJECT_AUXV:
7438       gdb_assert (annex == NULL);
7439       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
7440                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
7441
7442     case TARGET_OBJECT_AVAILABLE_FEATURES:
7443       return remote_read_qxfer
7444         (ops, "features", annex, readbuf, offset, len,
7445          &remote_protocol_packets[PACKET_qXfer_features]);
7446
7447     case TARGET_OBJECT_LIBRARIES:
7448       return remote_read_qxfer
7449         (ops, "libraries", annex, readbuf, offset, len,
7450          &remote_protocol_packets[PACKET_qXfer_libraries]);
7451
7452     case TARGET_OBJECT_MEMORY_MAP:
7453       gdb_assert (annex == NULL);
7454       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
7455                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
7456
7457     case TARGET_OBJECT_OSDATA:
7458       /* Should only get here if we're connected.  */
7459       gdb_assert (remote_desc);
7460       return remote_read_qxfer
7461        (ops, "osdata", annex, readbuf, offset, len,
7462         &remote_protocol_packets[PACKET_qXfer_osdata]);
7463
7464     default:
7465       return -1;
7466     }
7467
7468   /* Note: a zero OFFSET and LEN can be used to query the minimum
7469      buffer size.  */
7470   if (offset == 0 && len == 0)
7471     return (get_remote_packet_size ());
7472   /* Minimum outbuf size is get_remote_packet_size (). If LEN is not
7473      large enough let the caller deal with it.  */
7474   if (len < get_remote_packet_size ())
7475     return -1;
7476   len = get_remote_packet_size ();
7477
7478   /* Except for querying the minimum buffer size, target must be open.  */
7479   if (!remote_desc)
7480     error (_("remote query is only available after target open"));
7481
7482   gdb_assert (annex != NULL);
7483   gdb_assert (readbuf != NULL);
7484
7485   p2 = rs->buf;
7486   *p2++ = 'q';
7487   *p2++ = query_type;
7488
7489   /* We used one buffer char for the remote protocol q command and
7490      another for the query type.  As the remote protocol encapsulation
7491      uses 4 chars plus one extra in case we are debugging
7492      (remote_debug), we have PBUFZIZ - 7 left to pack the query
7493      string.  */
7494   i = 0;
7495   while (annex[i] && (i < (get_remote_packet_size () - 8)))
7496     {
7497       /* Bad caller may have sent forbidden characters.  */
7498       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
7499       *p2++ = annex[i];
7500       i++;
7501     }
7502   *p2 = '\0';
7503   gdb_assert (annex[i] == '\0');
7504
7505   i = putpkt (rs->buf);
7506   if (i < 0)
7507     return i;
7508
7509   getpkt (&rs->buf, &rs->buf_size, 0);
7510   strcpy ((char *) readbuf, rs->buf);
7511
7512   return strlen ((char *) readbuf);
7513 }
7514
7515 static int
7516 remote_search_memory (struct target_ops* ops,
7517                       CORE_ADDR start_addr, ULONGEST search_space_len,
7518                       const gdb_byte *pattern, ULONGEST pattern_len,
7519                       CORE_ADDR *found_addrp)
7520 {
7521   int addr_size = gdbarch_addr_bit (target_gdbarch) / 8;
7522   struct remote_state *rs = get_remote_state ();
7523   int max_size = get_memory_write_packet_size ();
7524   struct packet_config *packet =
7525     &remote_protocol_packets[PACKET_qSearch_memory];
7526   /* number of packet bytes used to encode the pattern,
7527      this could be more than PATTERN_LEN due to escape characters */
7528   int escaped_pattern_len;
7529   /* amount of pattern that was encodable in the packet */
7530   int used_pattern_len;
7531   int i;
7532   int found;
7533   ULONGEST found_addr;
7534
7535   /* Don't go to the target if we don't have to.
7536      This is done before checking packet->support to avoid the possibility that
7537      a success for this edge case means the facility works in general.  */
7538   if (pattern_len > search_space_len)
7539     return 0;
7540   if (pattern_len == 0)
7541     {
7542       *found_addrp = start_addr;
7543       return 1;
7544     }
7545
7546   /* If we already know the packet isn't supported, fall back to the simple
7547      way of searching memory.  */
7548
7549   if (packet->support == PACKET_DISABLE)
7550     {
7551       /* Target doesn't provided special support, fall back and use the
7552          standard support (copy memory and do the search here).  */
7553       return simple_search_memory (ops, start_addr, search_space_len,
7554                                    pattern, pattern_len, found_addrp);
7555     }
7556
7557   /* Insert header.  */
7558   i = snprintf (rs->buf, max_size, 
7559                 "qSearch:memory:%s;%s;",
7560                 phex_nz (start_addr, addr_size),
7561                 phex_nz (search_space_len, sizeof (search_space_len)));
7562   max_size -= (i + 1);
7563
7564   /* Escape as much data as fits into rs->buf.  */
7565   escaped_pattern_len =
7566     remote_escape_output (pattern, pattern_len, (rs->buf + i),
7567                           &used_pattern_len, max_size);
7568
7569   /* Bail if the pattern is too large.  */
7570   if (used_pattern_len != pattern_len)
7571     error ("Pattern is too large to transmit to remote target.");
7572
7573   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
7574       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
7575       || packet_ok (rs->buf, packet) != PACKET_OK)
7576     {
7577       /* The request may not have worked because the command is not
7578          supported.  If so, fall back to the simple way.  */
7579       if (packet->support == PACKET_DISABLE)
7580         {
7581           return simple_search_memory (ops, start_addr, search_space_len,
7582                                        pattern, pattern_len, found_addrp);
7583         }
7584       return -1;
7585     }
7586
7587   if (rs->buf[0] == '0')
7588     found = 0;
7589   else if (rs->buf[0] == '1')
7590     {
7591       found = 1;
7592       if (rs->buf[1] != ',')
7593         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7594       unpack_varlen_hex (rs->buf + 2, &found_addr);
7595       *found_addrp = found_addr;
7596     }
7597   else
7598     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
7599
7600   return found;
7601 }
7602
7603 static void
7604 remote_rcmd (char *command,
7605              struct ui_file *outbuf)
7606 {
7607   struct remote_state *rs = get_remote_state ();
7608   char *p = rs->buf;
7609
7610   if (!remote_desc)
7611     error (_("remote rcmd is only available after target open"));
7612
7613   /* Send a NULL command across as an empty command.  */
7614   if (command == NULL)
7615     command = "";
7616
7617   /* The query prefix.  */
7618   strcpy (rs->buf, "qRcmd,");
7619   p = strchr (rs->buf, '\0');
7620
7621   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/) > get_remote_packet_size ())
7622     error (_("\"monitor\" command ``%s'' is too long."), command);
7623
7624   /* Encode the actual command.  */
7625   bin2hex ((gdb_byte *) command, p, 0);
7626
7627   if (putpkt (rs->buf) < 0)
7628     error (_("Communication problem with target."));
7629
7630   /* get/display the response */
7631   while (1)
7632     {
7633       char *buf;
7634
7635       /* XXX - see also tracepoint.c:remote_get_noisy_reply().  */
7636       rs->buf[0] = '\0';
7637       getpkt (&rs->buf, &rs->buf_size, 0);
7638       buf = rs->buf;
7639       if (buf[0] == '\0')
7640         error (_("Target does not support this command."));
7641       if (buf[0] == 'O' && buf[1] != 'K')
7642         {
7643           remote_console_output (buf + 1); /* 'O' message from stub.  */
7644           continue;
7645         }
7646       if (strcmp (buf, "OK") == 0)
7647         break;
7648       if (strlen (buf) == 3 && buf[0] == 'E'
7649           && isdigit (buf[1]) && isdigit (buf[2]))
7650         {
7651           error (_("Protocol error with Rcmd"));
7652         }
7653       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
7654         {
7655           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
7656           fputc_unfiltered (c, outbuf);
7657         }
7658       break;
7659     }
7660 }
7661
7662 static VEC(mem_region_s) *
7663 remote_memory_map (struct target_ops *ops)
7664 {
7665   VEC(mem_region_s) *result = NULL;
7666   char *text = target_read_stralloc (&current_target,
7667                                      TARGET_OBJECT_MEMORY_MAP, NULL);
7668
7669   if (text)
7670     {
7671       struct cleanup *back_to = make_cleanup (xfree, text);
7672       result = parse_memory_map (text);
7673       do_cleanups (back_to);
7674     }
7675
7676   return result;
7677 }
7678
7679 static void
7680 packet_command (char *args, int from_tty)
7681 {
7682   struct remote_state *rs = get_remote_state ();
7683
7684   if (!remote_desc)
7685     error (_("command can only be used with remote target"));
7686
7687   if (!args)
7688     error (_("remote-packet command requires packet text as argument"));
7689
7690   puts_filtered ("sending: ");
7691   print_packet (args);
7692   puts_filtered ("\n");
7693   putpkt (args);
7694
7695   getpkt (&rs->buf, &rs->buf_size, 0);
7696   puts_filtered ("received: ");
7697   print_packet (rs->buf);
7698   puts_filtered ("\n");
7699 }
7700
7701 #if 0
7702 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
7703
7704 static void display_thread_info (struct gdb_ext_thread_info *info);
7705
7706 static void threadset_test_cmd (char *cmd, int tty);
7707
7708 static void threadalive_test (char *cmd, int tty);
7709
7710 static void threadlist_test_cmd (char *cmd, int tty);
7711
7712 int get_and_display_threadinfo (threadref *ref);
7713
7714 static void threadinfo_test_cmd (char *cmd, int tty);
7715
7716 static int thread_display_step (threadref *ref, void *context);
7717
7718 static void threadlist_update_test_cmd (char *cmd, int tty);
7719
7720 static void init_remote_threadtests (void);
7721
7722 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
7723
7724 static void
7725 threadset_test_cmd (char *cmd, int tty)
7726 {
7727   int sample_thread = SAMPLE_THREAD;
7728
7729   printf_filtered (_("Remote threadset test\n"));
7730   set_general_thread (sample_thread);
7731 }
7732
7733
7734 static void
7735 threadalive_test (char *cmd, int tty)
7736 {
7737   int sample_thread = SAMPLE_THREAD;
7738   int pid = ptid_get_pid (inferior_ptid);
7739   ptid_t ptid = ptid_build (pid, 0, sample_thread);
7740
7741   if (remote_thread_alive (ptid))
7742     printf_filtered ("PASS: Thread alive test\n");
7743   else
7744     printf_filtered ("FAIL: Thread alive test\n");
7745 }
7746
7747 void output_threadid (char *title, threadref *ref);
7748
7749 void
7750 output_threadid (char *title, threadref *ref)
7751 {
7752   char hexid[20];
7753
7754   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
7755   hexid[16] = 0;
7756   printf_filtered ("%s  %s\n", title, (&hexid[0]));
7757 }
7758
7759 static void
7760 threadlist_test_cmd (char *cmd, int tty)
7761 {
7762   int startflag = 1;
7763   threadref nextthread;
7764   int done, result_count;
7765   threadref threadlist[3];
7766
7767   printf_filtered ("Remote Threadlist test\n");
7768   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
7769                               &result_count, &threadlist[0]))
7770     printf_filtered ("FAIL: threadlist test\n");
7771   else
7772     {
7773       threadref *scan = threadlist;
7774       threadref *limit = scan + result_count;
7775
7776       while (scan < limit)
7777         output_threadid (" thread ", scan++);
7778     }
7779 }
7780
7781 void
7782 display_thread_info (struct gdb_ext_thread_info *info)
7783 {
7784   output_threadid ("Threadid: ", &info->threadid);
7785   printf_filtered ("Name: %s\n ", info->shortname);
7786   printf_filtered ("State: %s\n", info->display);
7787   printf_filtered ("other: %s\n\n", info->more_display);
7788 }
7789
7790 int
7791 get_and_display_threadinfo (threadref *ref)
7792 {
7793   int result;
7794   int set;
7795   struct gdb_ext_thread_info threadinfo;
7796
7797   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
7798     | TAG_MOREDISPLAY | TAG_DISPLAY;
7799   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
7800     display_thread_info (&threadinfo);
7801   return result;
7802 }
7803
7804 static void
7805 threadinfo_test_cmd (char *cmd, int tty)
7806 {
7807   int athread = SAMPLE_THREAD;
7808   threadref thread;
7809   int set;
7810
7811   int_to_threadref (&thread, athread);
7812   printf_filtered ("Remote Threadinfo test\n");
7813   if (!get_and_display_threadinfo (&thread))
7814     printf_filtered ("FAIL cannot get thread info\n");
7815 }
7816
7817 static int
7818 thread_display_step (threadref *ref, void *context)
7819 {
7820   /* output_threadid(" threadstep ",ref); *//* simple test */
7821   return get_and_display_threadinfo (ref);
7822 }
7823
7824 static void
7825 threadlist_update_test_cmd (char *cmd, int tty)
7826 {
7827   printf_filtered ("Remote Threadlist update test\n");
7828   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
7829 }
7830
7831 static void
7832 init_remote_threadtests (void)
7833 {
7834   add_com ("tlist", class_obscure, threadlist_test_cmd, _("\
7835 Fetch and print the remote list of thread identifiers, one pkt only"));
7836   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
7837            _("Fetch and display info about one thread"));
7838   add_com ("tset", class_obscure, threadset_test_cmd,
7839            _("Test setting to a different thread"));
7840   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
7841            _("Iterate through updating all remote thread info"));
7842   add_com ("talive", class_obscure, threadalive_test,
7843            _(" Remote thread alive test "));
7844 }
7845
7846 #endif /* 0 */
7847
7848 /* Convert a thread ID to a string.  Returns the string in a static
7849    buffer.  */
7850
7851 static char *
7852 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
7853 {
7854   static char buf[64];
7855   struct remote_state *rs = get_remote_state ();
7856
7857   if (ptid_equal (magic_null_ptid, ptid))
7858     {
7859       xsnprintf (buf, sizeof buf, "Thread <main>");
7860       return buf;
7861     }
7862   else if (remote_multi_process_p (rs)
7863            && ptid_get_tid (ptid) != 0 && ptid_get_pid (ptid) != 0)
7864     {
7865       xsnprintf (buf, sizeof buf, "Thread %d.%ld",
7866                  ptid_get_pid (ptid), ptid_get_tid (ptid));
7867       return buf;
7868     }
7869   else if (ptid_get_tid (ptid) != 0)
7870     {
7871       xsnprintf (buf, sizeof buf, "Thread %ld",
7872                  ptid_get_tid (ptid));
7873       return buf;
7874     }
7875
7876   return normal_pid_to_str (ptid);
7877 }
7878
7879 /* Get the address of the thread local variable in OBJFILE which is
7880    stored at OFFSET within the thread local storage for thread PTID.  */
7881
7882 static CORE_ADDR
7883 remote_get_thread_local_address (struct target_ops *ops,
7884                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
7885 {
7886   if (remote_protocol_packets[PACKET_qGetTLSAddr].support != PACKET_DISABLE)
7887     {
7888       struct remote_state *rs = get_remote_state ();
7889       char *p = rs->buf;
7890       char *endp = rs->buf + get_remote_packet_size ();
7891       enum packet_result result;
7892
7893       strcpy (p, "qGetTLSAddr:");
7894       p += strlen (p);
7895       p = write_ptid (p, endp, ptid);
7896       *p++ = ',';
7897       p += hexnumstr (p, offset);
7898       *p++ = ',';
7899       p += hexnumstr (p, lm);
7900       *p++ = '\0';
7901
7902       putpkt (rs->buf);
7903       getpkt (&rs->buf, &rs->buf_size, 0);
7904       result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_qGetTLSAddr]);
7905       if (result == PACKET_OK)
7906         {
7907           ULONGEST result;
7908
7909           unpack_varlen_hex (rs->buf, &result);
7910           return result;
7911         }
7912       else if (result == PACKET_UNKNOWN)
7913         throw_error (TLS_GENERIC_ERROR,
7914                      _("Remote target doesn't support qGetTLSAddr packet"));
7915       else
7916         throw_error (TLS_GENERIC_ERROR,
7917                      _("Remote target failed to process qGetTLSAddr request"));
7918     }
7919   else
7920     throw_error (TLS_GENERIC_ERROR,
7921                  _("TLS not supported or disabled on this target"));
7922   /* Not reached.  */
7923   return 0;
7924 }
7925
7926 /* Support for inferring a target description based on the current
7927    architecture and the size of a 'g' packet.  While the 'g' packet
7928    can have any size (since optional registers can be left off the
7929    end), some sizes are easily recognizable given knowledge of the
7930    approximate architecture.  */
7931
7932 struct remote_g_packet_guess
7933 {
7934   int bytes;
7935   const struct target_desc *tdesc;
7936 };
7937 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
7938 DEF_VEC_O(remote_g_packet_guess_s);
7939
7940 struct remote_g_packet_data
7941 {
7942   VEC(remote_g_packet_guess_s) *guesses;
7943 };
7944
7945 static struct gdbarch_data *remote_g_packet_data_handle;
7946
7947 static void *
7948 remote_g_packet_data_init (struct obstack *obstack)
7949 {
7950   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
7951 }
7952
7953 void
7954 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
7955                                 const struct target_desc *tdesc)
7956 {
7957   struct remote_g_packet_data *data
7958     = gdbarch_data (gdbarch, remote_g_packet_data_handle);
7959   struct remote_g_packet_guess new_guess, *guess;
7960   int ix;
7961
7962   gdb_assert (tdesc != NULL);
7963
7964   for (ix = 0;
7965        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
7966        ix++)
7967     if (guess->bytes == bytes)
7968       internal_error (__FILE__, __LINE__,
7969                       "Duplicate g packet description added for size %d",
7970                       bytes);
7971
7972   new_guess.bytes = bytes;
7973   new_guess.tdesc = tdesc;
7974   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
7975 }
7976
7977 /* Return 1 if remote_read_description would do anything on this target
7978    and architecture, 0 otherwise.  */
7979
7980 static int
7981 remote_read_description_p (struct target_ops *target)
7982 {
7983   struct remote_g_packet_data *data
7984     = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
7985
7986   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
7987     return 1;
7988
7989   return 0;
7990 }
7991
7992 static const struct target_desc *
7993 remote_read_description (struct target_ops *target)
7994 {
7995   struct remote_g_packet_data *data
7996     = gdbarch_data (target_gdbarch, remote_g_packet_data_handle);
7997
7998   /* Do not try this during initial connection, when we do not know
7999      whether there is a running but stopped thread.  */
8000   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
8001     return NULL;
8002
8003   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
8004     {
8005       struct remote_g_packet_guess *guess;
8006       int ix;
8007       int bytes = send_g_packet ();
8008
8009       for (ix = 0;
8010            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
8011            ix++)
8012         if (guess->bytes == bytes)
8013           return guess->tdesc;
8014
8015       /* We discard the g packet.  A minor optimization would be to
8016          hold on to it, and fill the register cache once we have selected
8017          an architecture, but it's too tricky to do safely.  */
8018     }
8019
8020   return NULL;
8021 }
8022
8023 /* Remote file transfer support.  This is host-initiated I/O, not
8024    target-initiated; for target-initiated, see remote-fileio.c.  */
8025
8026 /* If *LEFT is at least the length of STRING, copy STRING to
8027    *BUFFER, update *BUFFER to point to the new end of the buffer, and
8028    decrease *LEFT.  Otherwise raise an error.  */
8029
8030 static void
8031 remote_buffer_add_string (char **buffer, int *left, char *string)
8032 {
8033   int len = strlen (string);
8034
8035   if (len > *left)
8036     error (_("Packet too long for target."));
8037
8038   memcpy (*buffer, string, len);
8039   *buffer += len;
8040   *left -= len;
8041
8042   /* NUL-terminate the buffer as a convenience, if there is
8043      room.  */
8044   if (*left)
8045     **buffer = '\0';
8046 }
8047
8048 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
8049    *BUFFER, update *BUFFER to point to the new end of the buffer, and
8050    decrease *LEFT.  Otherwise raise an error.  */
8051
8052 static void
8053 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
8054                          int len)
8055 {
8056   if (2 * len > *left)
8057     error (_("Packet too long for target."));
8058
8059   bin2hex (bytes, *buffer, len);
8060   *buffer += 2 * len;
8061   *left -= 2 * len;
8062
8063   /* NUL-terminate the buffer as a convenience, if there is
8064      room.  */
8065   if (*left)
8066     **buffer = '\0';
8067 }
8068
8069 /* If *LEFT is large enough, convert VALUE to hex and add it to
8070    *BUFFER, update *BUFFER to point to the new end of the buffer, and
8071    decrease *LEFT.  Otherwise raise an error.  */
8072
8073 static void
8074 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
8075 {
8076   int len = hexnumlen (value);
8077
8078   if (len > *left)
8079     error (_("Packet too long for target."));
8080
8081   hexnumstr (*buffer, value);
8082   *buffer += len;
8083   *left -= len;
8084
8085   /* NUL-terminate the buffer as a convenience, if there is
8086      room.  */
8087   if (*left)
8088     **buffer = '\0';
8089 }
8090
8091 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
8092    value, *REMOTE_ERRNO to the remote error number or zero if none
8093    was included, and *ATTACHMENT to point to the start of the annex
8094    if any.  The length of the packet isn't needed here; there may
8095    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
8096
8097    Return 0 if the packet could be parsed, -1 if it could not.  If
8098    -1 is returned, the other variables may not be initialized.  */
8099
8100 static int
8101 remote_hostio_parse_result (char *buffer, int *retcode,
8102                             int *remote_errno, char **attachment)
8103 {
8104   char *p, *p2;
8105
8106   *remote_errno = 0;
8107   *attachment = NULL;
8108
8109   if (buffer[0] != 'F')
8110     return -1;
8111
8112   errno = 0;
8113   *retcode = strtol (&buffer[1], &p, 16);
8114   if (errno != 0 || p == &buffer[1])
8115     return -1;
8116
8117   /* Check for ",errno".  */
8118   if (*p == ',')
8119     {
8120       errno = 0;
8121       *remote_errno = strtol (p + 1, &p2, 16);
8122       if (errno != 0 || p + 1 == p2)
8123         return -1;
8124       p = p2;
8125     }
8126
8127   /* Check for ";attachment".  If there is no attachment, the
8128      packet should end here.  */
8129   if (*p == ';')
8130     {
8131       *attachment = p + 1;
8132       return 0;
8133     }
8134   else if (*p == '\0')
8135     return 0;
8136   else
8137     return -1;
8138 }
8139
8140 /* Send a prepared I/O packet to the target and read its response.
8141    The prepared packet is in the global RS->BUF before this function
8142    is called, and the answer is there when we return.
8143
8144    COMMAND_BYTES is the length of the request to send, which may include
8145    binary data.  WHICH_PACKET is the packet configuration to check
8146    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
8147    is set to the error number and -1 is returned.  Otherwise the value
8148    returned by the function is returned.
8149
8150    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
8151    attachment is expected; an error will be reported if there's a
8152    mismatch.  If one is found, *ATTACHMENT will be set to point into
8153    the packet buffer and *ATTACHMENT_LEN will be set to the
8154    attachment's length.  */
8155
8156 static int
8157 remote_hostio_send_command (int command_bytes, int which_packet,
8158                             int *remote_errno, char **attachment,
8159                             int *attachment_len)
8160 {
8161   struct remote_state *rs = get_remote_state ();
8162   int ret, bytes_read;
8163   char *attachment_tmp;
8164
8165   if (!remote_desc
8166       || remote_protocol_packets[which_packet].support == PACKET_DISABLE)
8167     {
8168       *remote_errno = FILEIO_ENOSYS;
8169       return -1;
8170     }
8171
8172   putpkt_binary (rs->buf, command_bytes);
8173   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
8174
8175   /* If it timed out, something is wrong.  Don't try to parse the
8176      buffer.  */
8177   if (bytes_read < 0)
8178     {
8179       *remote_errno = FILEIO_EINVAL;
8180       return -1;
8181     }
8182
8183   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
8184     {
8185     case PACKET_ERROR:
8186       *remote_errno = FILEIO_EINVAL;
8187       return -1;
8188     case PACKET_UNKNOWN:
8189       *remote_errno = FILEIO_ENOSYS;
8190       return -1;
8191     case PACKET_OK:
8192       break;
8193     }
8194
8195   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
8196                                   &attachment_tmp))
8197     {
8198       *remote_errno = FILEIO_EINVAL;
8199       return -1;
8200     }
8201
8202   /* Make sure we saw an attachment if and only if we expected one.  */
8203   if ((attachment_tmp == NULL && attachment != NULL)
8204       || (attachment_tmp != NULL && attachment == NULL))
8205     {
8206       *remote_errno = FILEIO_EINVAL;
8207       return -1;
8208     }
8209
8210   /* If an attachment was found, it must point into the packet buffer;
8211      work out how many bytes there were.  */
8212   if (attachment_tmp != NULL)
8213     {
8214       *attachment = attachment_tmp;
8215       *attachment_len = bytes_read - (*attachment - rs->buf);
8216     }
8217
8218   return ret;
8219 }
8220
8221 /* Open FILENAME on the remote target, using FLAGS and MODE.  Return a
8222    remote file descriptor, or -1 if an error occurs (and set
8223    *REMOTE_ERRNO).  */
8224
8225 static int
8226 remote_hostio_open (const char *filename, int flags, int mode,
8227                     int *remote_errno)
8228 {
8229   struct remote_state *rs = get_remote_state ();
8230   char *p = rs->buf;
8231   int left = get_remote_packet_size () - 1;
8232
8233   remote_buffer_add_string (&p, &left, "vFile:open:");
8234
8235   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8236                            strlen (filename));
8237   remote_buffer_add_string (&p, &left, ",");
8238
8239   remote_buffer_add_int (&p, &left, flags);
8240   remote_buffer_add_string (&p, &left, ",");
8241
8242   remote_buffer_add_int (&p, &left, mode);
8243
8244   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
8245                                      remote_errno, NULL, NULL);
8246 }
8247
8248 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
8249    Return the number of bytes written, or -1 if an error occurs (and
8250    set *REMOTE_ERRNO).  */
8251
8252 static int
8253 remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
8254                       ULONGEST offset, int *remote_errno)
8255 {
8256   struct remote_state *rs = get_remote_state ();
8257   char *p = rs->buf;
8258   int left = get_remote_packet_size ();
8259   int out_len;
8260
8261   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
8262
8263   remote_buffer_add_int (&p, &left, fd);
8264   remote_buffer_add_string (&p, &left, ",");
8265
8266   remote_buffer_add_int (&p, &left, offset);
8267   remote_buffer_add_string (&p, &left, ",");
8268
8269   p += remote_escape_output (write_buf, len, p, &out_len,
8270                              get_remote_packet_size () - (p - rs->buf));
8271
8272   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
8273                                      remote_errno, NULL, NULL);
8274 }
8275
8276 /* Read up to LEN bytes FD on the remote target into READ_BUF
8277    Return the number of bytes read, or -1 if an error occurs (and
8278    set *REMOTE_ERRNO).  */
8279
8280 static int
8281 remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
8282                      ULONGEST offset, int *remote_errno)
8283 {
8284   struct remote_state *rs = get_remote_state ();
8285   char *p = rs->buf;
8286   char *attachment;
8287   int left = get_remote_packet_size ();
8288   int ret, attachment_len;
8289   int read_len;
8290
8291   remote_buffer_add_string (&p, &left, "vFile:pread:");
8292
8293   remote_buffer_add_int (&p, &left, fd);
8294   remote_buffer_add_string (&p, &left, ",");
8295
8296   remote_buffer_add_int (&p, &left, len);
8297   remote_buffer_add_string (&p, &left, ",");
8298
8299   remote_buffer_add_int (&p, &left, offset);
8300
8301   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
8302                                     remote_errno, &attachment,
8303                                     &attachment_len);
8304
8305   if (ret < 0)
8306     return ret;
8307
8308   read_len = remote_unescape_input (attachment, attachment_len,
8309                                     read_buf, len);
8310   if (read_len != ret)
8311     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
8312
8313   return ret;
8314 }
8315
8316 /* Close FD on the remote target.  Return 0, or -1 if an error occurs
8317    (and set *REMOTE_ERRNO).  */
8318
8319 static int
8320 remote_hostio_close (int fd, int *remote_errno)
8321 {
8322   struct remote_state *rs = get_remote_state ();
8323   char *p = rs->buf;
8324   int left = get_remote_packet_size () - 1;
8325
8326   remote_buffer_add_string (&p, &left, "vFile:close:");
8327
8328   remote_buffer_add_int (&p, &left, fd);
8329
8330   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
8331                                      remote_errno, NULL, NULL);
8332 }
8333
8334 /* Unlink FILENAME on the remote target.  Return 0, or -1 if an error
8335    occurs (and set *REMOTE_ERRNO).  */
8336
8337 static int
8338 remote_hostio_unlink (const char *filename, int *remote_errno)
8339 {
8340   struct remote_state *rs = get_remote_state ();
8341   char *p = rs->buf;
8342   int left = get_remote_packet_size () - 1;
8343
8344   remote_buffer_add_string (&p, &left, "vFile:unlink:");
8345
8346   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
8347                            strlen (filename));
8348
8349   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
8350                                      remote_errno, NULL, NULL);
8351 }
8352
8353 static int
8354 remote_fileio_errno_to_host (int errnum)
8355 {
8356   switch (errnum)
8357     {
8358       case FILEIO_EPERM:
8359         return EPERM;
8360       case FILEIO_ENOENT:
8361         return ENOENT;
8362       case FILEIO_EINTR:
8363         return EINTR;
8364       case FILEIO_EIO:
8365         return EIO;
8366       case FILEIO_EBADF:
8367         return EBADF;
8368       case FILEIO_EACCES:
8369         return EACCES;
8370       case FILEIO_EFAULT:
8371         return EFAULT;
8372       case FILEIO_EBUSY:
8373         return EBUSY;
8374       case FILEIO_EEXIST:
8375         return EEXIST;
8376       case FILEIO_ENODEV:
8377         return ENODEV;
8378       case FILEIO_ENOTDIR:
8379         return ENOTDIR;
8380       case FILEIO_EISDIR:
8381         return EISDIR;
8382       case FILEIO_EINVAL:
8383         return EINVAL;
8384       case FILEIO_ENFILE:
8385         return ENFILE;
8386       case FILEIO_EMFILE:
8387         return EMFILE;
8388       case FILEIO_EFBIG:
8389         return EFBIG;
8390       case FILEIO_ENOSPC:
8391         return ENOSPC;
8392       case FILEIO_ESPIPE:
8393         return ESPIPE;
8394       case FILEIO_EROFS:
8395         return EROFS;
8396       case FILEIO_ENOSYS:
8397         return ENOSYS;
8398       case FILEIO_ENAMETOOLONG:
8399         return ENAMETOOLONG;
8400     }
8401   return -1;
8402 }
8403
8404 static char *
8405 remote_hostio_error (int errnum)
8406 {
8407   int host_error = remote_fileio_errno_to_host (errnum);
8408
8409   if (host_error == -1)
8410     error (_("Unknown remote I/O error %d"), errnum);
8411   else
8412     error (_("Remote I/O error: %s"), safe_strerror (host_error));
8413 }
8414
8415 static void
8416 remote_hostio_close_cleanup (void *opaque)
8417 {
8418   int fd = *(int *) opaque;
8419   int remote_errno;
8420
8421   remote_hostio_close (fd, &remote_errno);
8422 }
8423
8424
8425 static void *
8426 remote_bfd_iovec_open (struct bfd *abfd, void *open_closure)
8427 {
8428   const char *filename = bfd_get_filename (abfd);
8429   int fd, remote_errno;
8430   int *stream;
8431
8432   gdb_assert (remote_filename_p (filename));
8433
8434   fd = remote_hostio_open (filename + 7, FILEIO_O_RDONLY, 0, &remote_errno);
8435   if (fd == -1)
8436     {
8437       errno = remote_fileio_errno_to_host (remote_errno);
8438       bfd_set_error (bfd_error_system_call);
8439       return NULL;
8440     }
8441
8442   stream = xmalloc (sizeof (int));
8443   *stream = fd;
8444   return stream;
8445 }
8446
8447 static int
8448 remote_bfd_iovec_close (struct bfd *abfd, void *stream)
8449 {
8450   int fd = *(int *)stream;
8451   int remote_errno;
8452
8453   xfree (stream);
8454
8455   /* Ignore errors on close; these may happen if the remote
8456      connection was already torn down.  */
8457   remote_hostio_close (fd, &remote_errno);
8458
8459   return 1;
8460 }
8461
8462 static file_ptr
8463 remote_bfd_iovec_pread (struct bfd *abfd, void *stream, void *buf,
8464                         file_ptr nbytes, file_ptr offset)
8465 {
8466   int fd = *(int *)stream;
8467   int remote_errno;
8468   file_ptr pos, bytes;
8469
8470   pos = 0;
8471   while (nbytes > pos)
8472     {
8473       bytes = remote_hostio_pread (fd, (char *)buf + pos, nbytes - pos,
8474                                    offset + pos, &remote_errno);
8475       if (bytes == 0)
8476         /* Success, but no bytes, means end-of-file.  */
8477         break;
8478       if (bytes == -1)
8479         {
8480           errno = remote_fileio_errno_to_host (remote_errno);
8481           bfd_set_error (bfd_error_system_call);
8482           return -1;
8483         }
8484
8485       pos += bytes;
8486     }
8487
8488   return pos;
8489 }
8490
8491 static int
8492 remote_bfd_iovec_stat (struct bfd *abfd, void *stream, struct stat *sb)
8493 {
8494   /* FIXME: We should probably implement remote_hostio_stat.  */
8495   sb->st_size = INT_MAX;
8496   return 0;
8497 }
8498
8499 int
8500 remote_filename_p (const char *filename)
8501 {
8502   return strncmp (filename, "remote:", 7) == 0;
8503 }
8504
8505 bfd *
8506 remote_bfd_open (const char *remote_file, const char *target)
8507 {
8508   return bfd_openr_iovec (remote_file, target,
8509                           remote_bfd_iovec_open, NULL,
8510                           remote_bfd_iovec_pread,
8511                           remote_bfd_iovec_close,
8512                           remote_bfd_iovec_stat);
8513 }
8514
8515 void
8516 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
8517 {
8518   struct cleanup *back_to, *close_cleanup;
8519   int retcode, fd, remote_errno, bytes, io_size;
8520   FILE *file;
8521   gdb_byte *buffer;
8522   int bytes_in_buffer;
8523   int saw_eof;
8524   ULONGEST offset;
8525
8526   if (!remote_desc)
8527     error (_("command can only be used with remote target"));
8528
8529   file = fopen (local_file, "rb");
8530   if (file == NULL)
8531     perror_with_name (local_file);
8532   back_to = make_cleanup_fclose (file);
8533
8534   fd = remote_hostio_open (remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
8535                                          | FILEIO_O_TRUNC),
8536                            0700, &remote_errno);
8537   if (fd == -1)
8538     remote_hostio_error (remote_errno);
8539
8540   /* Send up to this many bytes at once.  They won't all fit in the
8541      remote packet limit, so we'll transfer slightly fewer.  */
8542   io_size = get_remote_packet_size ();
8543   buffer = xmalloc (io_size);
8544   make_cleanup (xfree, buffer);
8545
8546   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8547
8548   bytes_in_buffer = 0;
8549   saw_eof = 0;
8550   offset = 0;
8551   while (bytes_in_buffer || !saw_eof)
8552     {
8553       if (!saw_eof)
8554         {
8555           bytes = fread (buffer + bytes_in_buffer, 1, io_size - bytes_in_buffer,
8556                          file);
8557           if (bytes == 0)
8558             {
8559               if (ferror (file))
8560                 error (_("Error reading %s."), local_file);
8561               else
8562                 {
8563                   /* EOF.  Unless there is something still in the
8564                      buffer from the last iteration, we are done.  */
8565                   saw_eof = 1;
8566                   if (bytes_in_buffer == 0)
8567                     break;
8568                 }
8569             }
8570         }
8571       else
8572         bytes = 0;
8573
8574       bytes += bytes_in_buffer;
8575       bytes_in_buffer = 0;
8576
8577       retcode = remote_hostio_pwrite (fd, buffer, bytes, offset, &remote_errno);
8578
8579       if (retcode < 0)
8580         remote_hostio_error (remote_errno);
8581       else if (retcode == 0)
8582         error (_("Remote write of %d bytes returned 0!"), bytes);
8583       else if (retcode < bytes)
8584         {
8585           /* Short write.  Save the rest of the read data for the next
8586              write.  */
8587           bytes_in_buffer = bytes - retcode;
8588           memmove (buffer, buffer + retcode, bytes_in_buffer);
8589         }
8590
8591       offset += retcode;
8592     }
8593
8594   discard_cleanups (close_cleanup);
8595   if (remote_hostio_close (fd, &remote_errno))
8596     remote_hostio_error (remote_errno);
8597
8598   if (from_tty)
8599     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
8600   do_cleanups (back_to);
8601 }
8602
8603 void
8604 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
8605 {
8606   struct cleanup *back_to, *close_cleanup;
8607   int retcode, fd, remote_errno, bytes, io_size;
8608   FILE *file;
8609   gdb_byte *buffer;
8610   ULONGEST offset;
8611
8612   if (!remote_desc)
8613     error (_("command can only be used with remote target"));
8614
8615   fd = remote_hostio_open (remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
8616   if (fd == -1)
8617     remote_hostio_error (remote_errno);
8618
8619   file = fopen (local_file, "wb");
8620   if (file == NULL)
8621     perror_with_name (local_file);
8622   back_to = make_cleanup_fclose (file);
8623
8624   /* Send up to this many bytes at once.  They won't all fit in the
8625      remote packet limit, so we'll transfer slightly fewer.  */
8626   io_size = get_remote_packet_size ();
8627   buffer = xmalloc (io_size);
8628   make_cleanup (xfree, buffer);
8629
8630   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
8631
8632   offset = 0;
8633   while (1)
8634     {
8635       bytes = remote_hostio_pread (fd, buffer, io_size, offset, &remote_errno);
8636       if (bytes == 0)
8637         /* Success, but no bytes, means end-of-file.  */
8638         break;
8639       if (bytes == -1)
8640         remote_hostio_error (remote_errno);
8641
8642       offset += bytes;
8643
8644       bytes = fwrite (buffer, 1, bytes, file);
8645       if (bytes == 0)
8646         perror_with_name (local_file);
8647     }
8648
8649   discard_cleanups (close_cleanup);
8650   if (remote_hostio_close (fd, &remote_errno))
8651     remote_hostio_error (remote_errno);
8652
8653   if (from_tty)
8654     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
8655   do_cleanups (back_to);
8656 }
8657
8658 void
8659 remote_file_delete (const char *remote_file, int from_tty)
8660 {
8661   int retcode, remote_errno;
8662
8663   if (!remote_desc)
8664     error (_("command can only be used with remote target"));
8665
8666   retcode = remote_hostio_unlink (remote_file, &remote_errno);
8667   if (retcode == -1)
8668     remote_hostio_error (remote_errno);
8669
8670   if (from_tty)
8671     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
8672 }
8673
8674 static void
8675 remote_put_command (char *args, int from_tty)
8676 {
8677   struct cleanup *back_to;
8678   char **argv;
8679
8680   if (args == NULL)
8681     error_no_arg (_("file to put"));
8682
8683   argv = gdb_buildargv (args);
8684   back_to = make_cleanup_freeargv (argv);
8685   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8686     error (_("Invalid parameters to remote put"));
8687
8688   remote_file_put (argv[0], argv[1], from_tty);
8689
8690   do_cleanups (back_to);
8691 }
8692
8693 static void
8694 remote_get_command (char *args, int from_tty)
8695 {
8696   struct cleanup *back_to;
8697   char **argv;
8698
8699   if (args == NULL)
8700     error_no_arg (_("file to get"));
8701
8702   argv = gdb_buildargv (args);
8703   back_to = make_cleanup_freeargv (argv);
8704   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
8705     error (_("Invalid parameters to remote get"));
8706
8707   remote_file_get (argv[0], argv[1], from_tty);
8708
8709   do_cleanups (back_to);
8710 }
8711
8712 static void
8713 remote_delete_command (char *args, int from_tty)
8714 {
8715   struct cleanup *back_to;
8716   char **argv;
8717
8718   if (args == NULL)
8719     error_no_arg (_("file to delete"));
8720
8721   argv = gdb_buildargv (args);
8722   back_to = make_cleanup_freeargv (argv);
8723   if (argv[0] == NULL || argv[1] != NULL)
8724     error (_("Invalid parameters to remote delete"));
8725
8726   remote_file_delete (argv[0], from_tty);
8727
8728   do_cleanups (back_to);
8729 }
8730
8731 static void
8732 remote_command (char *args, int from_tty)
8733 {
8734   help_list (remote_cmdlist, "remote ", -1, gdb_stdout);
8735 }
8736
8737 static int remote_target_can_reverse = 1;
8738
8739 static int
8740 remote_can_execute_reverse (void)
8741 {
8742   return remote_target_can_reverse;
8743 }
8744
8745 static int
8746 remote_supports_non_stop (void)
8747 {
8748   return 1;
8749 }
8750
8751 static int
8752 remote_supports_multi_process (void)
8753 {
8754   struct remote_state *rs = get_remote_state ();
8755   return remote_multi_process_p (rs);
8756 }
8757
8758 int
8759 remote_supports_cond_tracepoints (void)
8760 {
8761   struct remote_state *rs = get_remote_state ();
8762   return rs->cond_tracepoints;
8763 }
8764
8765 static void
8766 init_remote_ops (void)
8767 {
8768   remote_ops.to_shortname = "remote";
8769   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
8770   remote_ops.to_doc =
8771     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8772 Specify the serial device it is connected to\n\
8773 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
8774   remote_ops.to_open = remote_open;
8775   remote_ops.to_close = remote_close;
8776   remote_ops.to_detach = remote_detach;
8777   remote_ops.to_disconnect = remote_disconnect;
8778   remote_ops.to_resume = remote_resume;
8779   remote_ops.to_wait = remote_wait;
8780   remote_ops.to_fetch_registers = remote_fetch_registers;
8781   remote_ops.to_store_registers = remote_store_registers;
8782   remote_ops.to_prepare_to_store = remote_prepare_to_store;
8783   remote_ops.deprecated_xfer_memory = remote_xfer_memory;
8784   remote_ops.to_files_info = remote_files_info;
8785   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
8786   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
8787   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
8788   remote_ops.to_stopped_data_address = remote_stopped_data_address;
8789   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
8790   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
8791   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
8792   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
8793   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
8794   remote_ops.to_kill = remote_kill;
8795   remote_ops.to_load = generic_load;
8796   remote_ops.to_mourn_inferior = remote_mourn;
8797   remote_ops.to_thread_alive = remote_thread_alive;
8798   remote_ops.to_find_new_threads = remote_threads_info;
8799   remote_ops.to_pid_to_str = remote_pid_to_str;
8800   remote_ops.to_extra_thread_info = remote_threads_extra_info;
8801   remote_ops.to_stop = remote_stop;
8802   remote_ops.to_xfer_partial = remote_xfer_partial;
8803   remote_ops.to_rcmd = remote_rcmd;
8804   remote_ops.to_log_command = serial_log_command;
8805   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
8806   remote_ops.to_stratum = process_stratum;
8807   remote_ops.to_has_all_memory = default_child_has_all_memory;
8808   remote_ops.to_has_memory = default_child_has_memory;
8809   remote_ops.to_has_stack = default_child_has_stack;
8810   remote_ops.to_has_registers = default_child_has_registers;
8811   remote_ops.to_has_execution = default_child_has_execution;
8812   remote_ops.to_has_thread_control = tc_schedlock;      /* can lock scheduler */
8813   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
8814   remote_ops.to_magic = OPS_MAGIC;
8815   remote_ops.to_memory_map = remote_memory_map;
8816   remote_ops.to_flash_erase = remote_flash_erase;
8817   remote_ops.to_flash_done = remote_flash_done;
8818   remote_ops.to_read_description = remote_read_description;
8819   remote_ops.to_search_memory = remote_search_memory;
8820   remote_ops.to_can_async_p = remote_can_async_p;
8821   remote_ops.to_is_async_p = remote_is_async_p;
8822   remote_ops.to_async = remote_async;
8823   remote_ops.to_async_mask = remote_async_mask;
8824   remote_ops.to_terminal_inferior = remote_terminal_inferior;
8825   remote_ops.to_terminal_ours = remote_terminal_ours;
8826   remote_ops.to_supports_non_stop = remote_supports_non_stop;
8827   remote_ops.to_supports_multi_process = remote_supports_multi_process;
8828 }
8829
8830 /* Set up the extended remote vector by making a copy of the standard
8831    remote vector and adding to it.  */
8832
8833 static void
8834 init_extended_remote_ops (void)
8835 {
8836   extended_remote_ops = remote_ops;
8837
8838   extended_remote_ops.to_shortname = "extended-remote";
8839   extended_remote_ops.to_longname =
8840     "Extended remote serial target in gdb-specific protocol";
8841   extended_remote_ops.to_doc =
8842     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
8843 Specify the serial device it is connected to (e.g. /dev/ttya).";
8844   extended_remote_ops.to_open = extended_remote_open;
8845   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
8846   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
8847   extended_remote_ops.to_detach = extended_remote_detach;
8848   extended_remote_ops.to_attach = extended_remote_attach;
8849   extended_remote_ops.to_kill = extended_remote_kill;
8850 }
8851
8852 static int
8853 remote_can_async_p (void)
8854 {
8855   if (!target_async_permitted)
8856     /* We only enable async when the user specifically asks for it.  */
8857     return 0;
8858
8859   /* We're async whenever the serial device is.  */
8860   return remote_async_mask_value && serial_can_async_p (remote_desc);
8861 }
8862
8863 static int
8864 remote_is_async_p (void)
8865 {
8866   if (!target_async_permitted)
8867     /* We only enable async when the user specifically asks for it.  */
8868     return 0;
8869
8870   /* We're async whenever the serial device is.  */
8871   return remote_async_mask_value && serial_is_async_p (remote_desc);
8872 }
8873
8874 /* Pass the SERIAL event on and up to the client.  One day this code
8875    will be able to delay notifying the client of an event until the
8876    point where an entire packet has been received.  */
8877
8878 static void (*async_client_callback) (enum inferior_event_type event_type,
8879                                       void *context);
8880 static void *async_client_context;
8881 static serial_event_ftype remote_async_serial_handler;
8882
8883 static void
8884 remote_async_serial_handler (struct serial *scb, void *context)
8885 {
8886   /* Don't propogate error information up to the client.  Instead let
8887      the client find out about the error by querying the target.  */
8888   async_client_callback (INF_REG_EVENT, async_client_context);
8889 }
8890
8891 static void
8892 remote_async_inferior_event_handler (gdb_client_data data)
8893 {
8894   inferior_event_handler (INF_REG_EVENT, NULL);
8895 }
8896
8897 static void
8898 remote_async_get_pending_events_handler (gdb_client_data data)
8899 {
8900   remote_get_pending_stop_replies ();
8901 }
8902
8903 static void
8904 remote_async (void (*callback) (enum inferior_event_type event_type,
8905                                 void *context), void *context)
8906 {
8907   if (remote_async_mask_value == 0)
8908     internal_error (__FILE__, __LINE__,
8909                     _("Calling remote_async when async is masked"));
8910
8911   if (callback != NULL)
8912     {
8913       serial_async (remote_desc, remote_async_serial_handler, NULL);
8914       async_client_callback = callback;
8915       async_client_context = context;
8916     }
8917   else
8918     serial_async (remote_desc, NULL, NULL);
8919 }
8920
8921 static int
8922 remote_async_mask (int new_mask)
8923 {
8924   int curr_mask = remote_async_mask_value;
8925   remote_async_mask_value = new_mask;
8926   return curr_mask;
8927 }
8928
8929 static void
8930 set_remote_cmd (char *args, int from_tty)
8931 {
8932   help_list (remote_set_cmdlist, "set remote ", -1, gdb_stdout);
8933 }
8934
8935 static void
8936 show_remote_cmd (char *args, int from_tty)
8937 {
8938   /* We can't just use cmd_show_list here, because we want to skip
8939      the redundant "show remote Z-packet" and the legacy aliases.  */
8940   struct cleanup *showlist_chain;
8941   struct cmd_list_element *list = remote_show_cmdlist;
8942
8943   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
8944   for (; list != NULL; list = list->next)
8945     if (strcmp (list->name, "Z-packet") == 0)
8946       continue;
8947     else if (list->type == not_set_cmd)
8948       /* Alias commands are exactly like the original, except they
8949          don't have the normal type.  */
8950       continue;
8951     else
8952       {
8953         struct cleanup *option_chain
8954           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
8955         ui_out_field_string (uiout, "name", list->name);
8956         ui_out_text (uiout, ":  ");
8957         if (list->type == show_cmd)
8958           do_setshow_command ((char *) NULL, from_tty, list);
8959         else
8960           cmd_func (list, NULL, from_tty);
8961         /* Close the tuple.  */
8962         do_cleanups (option_chain);
8963       }
8964
8965   /* Close the tuple.  */
8966   do_cleanups (showlist_chain);
8967 }
8968
8969
8970 /* Function to be called whenever a new objfile (shlib) is detected.  */
8971 static void
8972 remote_new_objfile (struct objfile *objfile)
8973 {
8974   if (remote_desc != 0)         /* Have a remote connection.  */
8975     remote_check_symbols (objfile);
8976 }
8977
8978 void
8979 _initialize_remote (void)
8980 {
8981   struct remote_state *rs;
8982
8983   /* architecture specific data */
8984   remote_gdbarch_data_handle =
8985     gdbarch_data_register_post_init (init_remote_state);
8986   remote_g_packet_data_handle =
8987     gdbarch_data_register_pre_init (remote_g_packet_data_init);
8988
8989   /* Initialize the per-target state.  At the moment there is only one
8990      of these, not one per target.  Only one target is active at a
8991      time.  The default buffer size is unimportant; it will be expanded
8992      whenever a larger buffer is needed.  */
8993   rs = get_remote_state_raw ();
8994   rs->buf_size = 400;
8995   rs->buf = xmalloc (rs->buf_size);
8996
8997   init_remote_ops ();
8998   add_target (&remote_ops);
8999
9000   init_extended_remote_ops ();
9001   add_target (&extended_remote_ops);
9002
9003   /* Hook into new objfile notification.  */
9004   observer_attach_new_objfile (remote_new_objfile);
9005
9006   /* Set up signal handlers.  */
9007   sigint_remote_token =
9008     create_async_signal_handler (async_remote_interrupt, NULL);
9009   sigint_remote_twice_token =
9010     create_async_signal_handler (inferior_event_handler_wrapper, NULL);
9011
9012 #if 0
9013   init_remote_threadtests ();
9014 #endif
9015
9016   /* set/show remote ...  */
9017
9018   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
9019 Remote protocol specific variables\n\
9020 Configure various remote-protocol specific variables such as\n\
9021 the packets being used"),
9022                   &remote_set_cmdlist, "set remote ",
9023                   0 /* allow-unknown */, &setlist);
9024   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
9025 Remote protocol specific variables\n\
9026 Configure various remote-protocol specific variables such as\n\
9027 the packets being used"),
9028                   &remote_show_cmdlist, "show remote ",
9029                   0 /* allow-unknown */, &showlist);
9030
9031   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
9032 Compare section data on target to the exec file.\n\
9033 Argument is a single section name (default: all loaded sections)."),
9034            &cmdlist);
9035
9036   add_cmd ("packet", class_maintenance, packet_command, _("\
9037 Send an arbitrary packet to a remote target.\n\
9038    maintenance packet TEXT\n\
9039 If GDB is talking to an inferior via the GDB serial protocol, then\n\
9040 this command sends the string TEXT to the inferior, and displays the\n\
9041 response packet.  GDB supplies the initial `$' character, and the\n\
9042 terminating `#' character and checksum."),
9043            &maintenancelist);
9044
9045   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
9046 Set whether to send break if interrupted."), _("\
9047 Show whether to send break if interrupted."), _("\
9048 If set, a break, instead of a cntrl-c, is sent to the remote target."),
9049                            NULL, NULL, /* FIXME: i18n: Whether to send break if interrupted is %s.  */
9050                            &setlist, &showlist);
9051
9052   /* Install commands for configuring memory read/write packets.  */
9053
9054   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
9055 Set the maximum number of bytes per memory write packet (deprecated)."),
9056            &setlist);
9057   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
9058 Show the maximum number of bytes per memory write packet (deprecated)."),
9059            &showlist);
9060   add_cmd ("memory-write-packet-size", no_class,
9061            set_memory_write_packet_size, _("\
9062 Set the maximum number of bytes per memory-write packet.\n\
9063 Specify the number of bytes in a packet or 0 (zero) for the\n\
9064 default packet size.  The actual limit is further reduced\n\
9065 dependent on the target.  Specify ``fixed'' to disable the\n\
9066 further restriction and ``limit'' to enable that restriction."),
9067            &remote_set_cmdlist);
9068   add_cmd ("memory-read-packet-size", no_class,
9069            set_memory_read_packet_size, _("\
9070 Set the maximum number of bytes per memory-read packet.\n\
9071 Specify the number of bytes in a packet or 0 (zero) for the\n\
9072 default packet size.  The actual limit is further reduced\n\
9073 dependent on the target.  Specify ``fixed'' to disable the\n\
9074 further restriction and ``limit'' to enable that restriction."),
9075            &remote_set_cmdlist);
9076   add_cmd ("memory-write-packet-size", no_class,
9077            show_memory_write_packet_size,
9078            _("Show the maximum number of bytes per memory-write packet."),
9079            &remote_show_cmdlist);
9080   add_cmd ("memory-read-packet-size", no_class,
9081            show_memory_read_packet_size,
9082            _("Show the maximum number of bytes per memory-read packet."),
9083            &remote_show_cmdlist);
9084
9085   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
9086                             &remote_hw_watchpoint_limit, _("\
9087 Set the maximum number of target hardware watchpoints."), _("\
9088 Show the maximum number of target hardware watchpoints."), _("\
9089 Specify a negative limit for unlimited."),
9090                             NULL, NULL, /* FIXME: i18n: The maximum number of target hardware watchpoints is %s.  */
9091                             &remote_set_cmdlist, &remote_show_cmdlist);
9092   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
9093                             &remote_hw_breakpoint_limit, _("\
9094 Set the maximum number of target hardware breakpoints."), _("\
9095 Show the maximum number of target hardware breakpoints."), _("\
9096 Specify a negative limit for unlimited."),
9097                             NULL, NULL, /* FIXME: i18n: The maximum number of target hardware breakpoints is %s.  */
9098                             &remote_set_cmdlist, &remote_show_cmdlist);
9099
9100   add_setshow_integer_cmd ("remoteaddresssize", class_obscure,
9101                            &remote_address_size, _("\
9102 Set the maximum size of the address (in bits) in a memory packet."), _("\
9103 Show the maximum size of the address (in bits) in a memory packet."), NULL,
9104                            NULL,
9105                            NULL, /* FIXME: i18n: */
9106                            &setlist, &showlist);
9107
9108   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
9109                          "X", "binary-download", 1);
9110
9111   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
9112                          "vCont", "verbose-resume", 0);
9113
9114   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
9115                          "QPassSignals", "pass-signals", 0);
9116
9117   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
9118                          "qSymbol", "symbol-lookup", 0);
9119
9120   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
9121                          "P", "set-register", 1);
9122
9123   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
9124                          "p", "fetch-register", 1);
9125
9126   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
9127                          "Z0", "software-breakpoint", 0);
9128
9129   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
9130                          "Z1", "hardware-breakpoint", 0);
9131
9132   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
9133                          "Z2", "write-watchpoint", 0);
9134
9135   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
9136                          "Z3", "read-watchpoint", 0);
9137
9138   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
9139                          "Z4", "access-watchpoint", 0);
9140
9141   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
9142                          "qXfer:auxv:read", "read-aux-vector", 0);
9143
9144   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
9145                          "qXfer:features:read", "target-features", 0);
9146
9147   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
9148                          "qXfer:libraries:read", "library-info", 0);
9149
9150   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
9151                          "qXfer:memory-map:read", "memory-map", 0);
9152
9153   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
9154                          "qXfer:spu:read", "read-spu-object", 0);
9155
9156   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
9157                          "qXfer:spu:write", "write-spu-object", 0);
9158
9159   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
9160                         "qXfer:osdata:read", "osdata", 0);
9161
9162   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
9163                          "qXfer:siginfo:read", "read-siginfo-object", 0);
9164
9165   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
9166                          "qXfer:siginfo:write", "write-siginfo-object", 0);
9167
9168   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
9169                          "qGetTLSAddr", "get-thread-local-storage-address",
9170                          0);
9171
9172   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
9173                          "qSupported", "supported-packets", 0);
9174
9175   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
9176                          "qSearch:memory", "search-memory", 0);
9177
9178   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
9179                          "vFile:open", "hostio-open", 0);
9180
9181   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
9182                          "vFile:pread", "hostio-pread", 0);
9183
9184   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
9185                          "vFile:pwrite", "hostio-pwrite", 0);
9186
9187   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
9188                          "vFile:close", "hostio-close", 0);
9189
9190   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
9191                          "vFile:unlink", "hostio-unlink", 0);
9192
9193   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
9194                          "vAttach", "attach", 0);
9195
9196   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
9197                          "vRun", "run", 0);
9198
9199   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
9200                          "QStartNoAckMode", "noack", 0);
9201
9202   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
9203                          "vKill", "kill", 0);
9204
9205   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
9206                          "qAttached", "query-attached", 0);
9207
9208   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
9209                          "ConditionalTracepoints", "conditional-tracepoints", 0);
9210
9211   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
9212      Z sub-packet has its own set and show commands, but users may
9213      have sets to this variable in their .gdbinit files (or in their
9214      documentation).  */
9215   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
9216                                 &remote_Z_packet_detect, _("\
9217 Set use of remote protocol `Z' packets"), _("\
9218 Show use of remote protocol `Z' packets "), _("\
9219 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
9220 packets."),
9221                                 set_remote_protocol_Z_packet_cmd,
9222                                 show_remote_protocol_Z_packet_cmd, /* FIXME: i18n: Use of remote protocol `Z' packets is %s.  */
9223                                 &remote_set_cmdlist, &remote_show_cmdlist);
9224
9225   add_prefix_cmd ("remote", class_files, remote_command, _("\
9226 Manipulate files on the remote system\n\
9227 Transfer files to and from the remote target system."),
9228                   &remote_cmdlist, "remote ",
9229                   0 /* allow-unknown */, &cmdlist);
9230
9231   add_cmd ("put", class_files, remote_put_command,
9232            _("Copy a local file to the remote system."),
9233            &remote_cmdlist);
9234
9235   add_cmd ("get", class_files, remote_get_command,
9236            _("Copy a remote file to the local system."),
9237            &remote_cmdlist);
9238
9239   add_cmd ("delete", class_files, remote_delete_command,
9240            _("Delete a remote file."),
9241            &remote_cmdlist);
9242
9243   remote_exec_file = xstrdup ("");
9244   add_setshow_string_noescape_cmd ("exec-file", class_files,
9245                                    &remote_exec_file, _("\
9246 Set the remote pathname for \"run\""), _("\
9247 Show the remote pathname for \"run\""), NULL, NULL, NULL,
9248                                    &remote_set_cmdlist, &remote_show_cmdlist);
9249
9250   /* Eventually initialize fileio.  See fileio.c */
9251   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
9252
9253   /* Take advantage of the fact that the LWP field is not used, to tag
9254      special ptids with it set to != 0.  */
9255   magic_null_ptid = ptid_build (42000, 1, -1);
9256   not_sent_ptid = ptid_build (42000, 1, -2);
9257   any_thread_ptid = ptid_build (42000, 1, 0);
9258 }