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