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