Extended-remote fork catch
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2015 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observer.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47
48 #include <sys/time.h>
49
50 #include "event-loop.h"
51 #include "event-top.h"
52 #include "inf-loop.h"
53
54 #include <signal.h>
55 #include "serial.h"
56
57 #include "gdbcore.h" /* for exec_bfd */
58
59 #include "remote-fileio.h"
60 #include "gdb/fileio.h"
61 #include <sys/stat.h>
62 #include "xml-support.h"
63
64 #include "memory-map.h"
65
66 #include "tracepoint.h"
67 #include "ax.h"
68 #include "ax-gdb.h"
69 #include "agent.h"
70 #include "btrace.h"
71
72 /* Temp hacks for tracepoint encoding migration.  */
73 static char *target_buf;
74 static long target_buf_size;
75
76 /* The size to align memory write packets, when practical.  The protocol
77    does not guarantee any alignment, and gdb will generate short
78    writes and unaligned writes, but even as a best-effort attempt this
79    can improve bulk transfers.  For instance, if a write is misaligned
80    relative to the target's data bus, the stub may need to make an extra
81    round trip fetching data from the target.  This doesn't make a
82    huge difference, but it's easy to do, so we try to be helpful.
83
84    The alignment chosen is arbitrary; usually data bus width is
85    important here, not the possibly larger cache line size.  */
86 enum { REMOTE_ALIGN_WRITES = 16 };
87
88 /* Prototypes for local functions.  */
89 static void async_cleanup_sigint_signal_handler (void *dummy);
90 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
91 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
92                                  int forever, int *is_notif);
93
94 static void async_handle_remote_sigint (int);
95 static void async_handle_remote_sigint_twice (int);
96
97 static void remote_files_info (struct target_ops *ignore);
98
99 static void remote_prepare_to_store (struct target_ops *self,
100                                      struct regcache *regcache);
101
102 static void remote_open_1 (const char *, int, struct target_ops *,
103                            int extended_p);
104
105 static void remote_close (struct target_ops *self);
106
107 struct remote_state;
108
109 static int remote_vkill (int pid, struct remote_state *rs);
110
111 static void remote_mourn (struct target_ops *ops);
112
113 static void extended_remote_restart (void);
114
115 static void extended_remote_mourn (struct target_ops *);
116
117 static void remote_send (char **buf, long *sizeof_buf_p);
118
119 static int readchar (int timeout);
120
121 static void remote_serial_write (const char *str, int len);
122
123 static void remote_kill (struct target_ops *ops);
124
125 static int remote_can_async_p (struct target_ops *);
126
127 static int remote_is_async_p (struct target_ops *);
128
129 static void remote_async (struct target_ops *ops, int enable);
130
131 static void sync_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 (struct target_ops *self, ptid_t);
151
152 static int stubhex (int ch);
153
154 static int hexnumstr (char *, ULONGEST);
155
156 static int hexnumnstr (char *, ULONGEST, int);
157
158 static CORE_ADDR remote_address_masked (CORE_ADDR);
159
160 static void print_packet (const char *);
161
162 static void compare_sections_command (char *, int);
163
164 static void packet_command (char *, int);
165
166 static int stub_unpack_int (char *buff, int fieldlength);
167
168 static ptid_t remote_current_thread (ptid_t oldptid);
169
170 static int putpkt_binary (const char *buf, int cnt);
171
172 static void check_binary_download (CORE_ADDR addr);
173
174 struct packet_config;
175
176 static void show_packet_config_cmd (struct packet_config *config);
177
178 static void show_remote_protocol_packet_cmd (struct ui_file *file,
179                                              int from_tty,
180                                              struct cmd_list_element *c,
181                                              const char *value);
182
183 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
184 static ptid_t read_ptid (char *buf, char **obuf);
185
186 static void remote_set_permissions (struct target_ops *self);
187
188 static int remote_get_trace_status (struct target_ops *self,
189                                     struct trace_status *ts);
190
191 static int remote_upload_tracepoints (struct target_ops *self,
192                                       struct uploaded_tp **utpp);
193
194 static int remote_upload_trace_state_variables (struct target_ops *self,
195                                                 struct uploaded_tsv **utsvp);
196   
197 static void remote_query_supported (void);
198
199 static void remote_check_symbols (void);
200
201 void _initialize_remote (void);
202
203 struct stop_reply;
204 static void stop_reply_xfree (struct stop_reply *);
205 static void remote_parse_stop_reply (char *, struct stop_reply *);
206 static void push_stop_reply (struct stop_reply *);
207 static void discard_pending_stop_replies_in_queue (struct remote_state *);
208 static int peek_stop_reply (ptid_t ptid);
209
210 struct threads_listing_context;
211 static void remove_new_fork_children (struct threads_listing_context *);
212
213 static void remote_async_inferior_event_handler (gdb_client_data);
214
215 static void remote_terminal_ours (struct target_ops *self);
216
217 static int remote_read_description_p (struct target_ops *target);
218
219 static void remote_console_output (char *msg);
220
221 static int remote_supports_cond_breakpoints (struct target_ops *self);
222
223 static int remote_can_run_breakpoint_commands (struct target_ops *self);
224
225 static void remote_btrace_reset (void);
226
227 /* For "remote".  */
228
229 static struct cmd_list_element *remote_cmdlist;
230
231 /* For "set remote" and "show remote".  */
232
233 static struct cmd_list_element *remote_set_cmdlist;
234 static struct cmd_list_element *remote_show_cmdlist;
235
236 /* Stub vCont actions support.
237
238    Each field is a boolean flag indicating whether the stub reports
239    support for the corresponding action.  */
240
241 struct vCont_action_support
242 {
243   /* vCont;t */
244   int t;
245
246   /* vCont;r */
247   int r;
248 };
249
250 /* Controls whether GDB is willing to use range stepping.  */
251
252 static int use_range_stepping = 1;
253
254 #define OPAQUETHREADBYTES 8
255
256 /* a 64 bit opaque identifier */
257 typedef unsigned char threadref[OPAQUETHREADBYTES];
258
259 /* About this many threadisds fit in a packet.  */
260
261 #define MAXTHREADLISTRESULTS 32
262
263 /* Description of the remote protocol state for the currently
264    connected target.  This is per-target state, and independent of the
265    selected architecture.  */
266
267 struct remote_state
268 {
269   /* A buffer to use for incoming packets, and its current size.  The
270      buffer is grown dynamically for larger incoming packets.
271      Outgoing packets may also be constructed in this buffer.
272      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
273      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
274      packets.  */
275   char *buf;
276   long buf_size;
277
278   /* True if we're going through initial connection setup (finding out
279      about the remote side's threads, relocating symbols, etc.).  */
280   int starting_up;
281
282   /* If we negotiated packet size explicitly (and thus can bypass
283      heuristics for the largest packet size that will not overflow
284      a buffer in the stub), this will be set to that packet size.
285      Otherwise zero, meaning to use the guessed size.  */
286   long explicit_packet_size;
287
288   /* remote_wait is normally called when the target is running and
289      waits for a stop reply packet.  But sometimes we need to call it
290      when the target is already stopped.  We can send a "?" packet
291      and have remote_wait read the response.  Or, if we already have
292      the response, we can stash it in BUF and tell remote_wait to
293      skip calling getpkt.  This flag is set when BUF contains a
294      stop reply packet and the target is not waiting.  */
295   int cached_wait_status;
296
297   /* True, if in no ack mode.  That is, neither GDB nor the stub will
298      expect acks from each other.  The connection is assumed to be
299      reliable.  */
300   int noack_mode;
301
302   /* True if we're connected in extended remote mode.  */
303   int extended;
304
305   /* True if we resumed the target and we're waiting for the target to
306      stop.  In the mean time, we can't start another command/query.
307      The remote server wouldn't be ready to process it, so we'd
308      timeout waiting for a reply that would never come and eventually
309      we'd close the connection.  This can happen in asynchronous mode
310      because we allow GDB commands while the target is running.  */
311   int waiting_for_stop_reply;
312
313   /* The status of the stub support for the various vCont actions.  */
314   struct vCont_action_support supports_vCont;
315
316   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
317      responded to that.  */
318   int ctrlc_pending_p;
319
320   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
321      remote_open knows that we don't have a file open when the program
322      starts.  */
323   struct serial *remote_desc;
324
325   /* These are the threads which we last sent to the remote system.  The
326      TID member will be -1 for all or -2 for not sent yet.  */
327   ptid_t general_thread;
328   ptid_t continue_thread;
329
330   /* This is the traceframe which we last selected on the remote system.
331      It will be -1 if no traceframe is selected.  */
332   int remote_traceframe_number;
333
334   char *last_pass_packet;
335
336   /* The last QProgramSignals packet sent to the target.  We bypass
337      sending a new program signals list down to the target if the new
338      packet is exactly the same as the last we sent.  IOW, we only let
339      the target know about program signals list changes.  */
340   char *last_program_signals_packet;
341
342   enum gdb_signal last_sent_signal;
343
344   int last_sent_step;
345
346   char *finished_object;
347   char *finished_annex;
348   ULONGEST finished_offset;
349
350   /* Should we try the 'ThreadInfo' query packet?
351
352      This variable (NOT available to the user: auto-detect only!)
353      determines whether GDB will use the new, simpler "ThreadInfo"
354      query or the older, more complex syntax for thread queries.
355      This is an auto-detect variable (set to true at each connect,
356      and set to false when the target fails to recognize it).  */
357   int use_threadinfo_query;
358   int use_threadextra_query;
359
360   /* This is set to the data address of the access causing the target
361      to stop for a watchpoint.  */
362   CORE_ADDR remote_watch_data_address;
363
364   /* Whether the target stopped for a breakpoint/watchpoint.  */
365   enum target_stop_reason stop_reason;
366
367   threadref echo_nextthread;
368   threadref nextthread;
369   threadref resultthreadlist[MAXTHREADLISTRESULTS];
370
371   /* The state of remote notification.  */
372   struct remote_notif_state *notif_state;
373
374   /* The branch trace configuration.  */
375   struct btrace_config btrace_config;
376 };
377
378 /* Private data that we'll store in (struct thread_info)->private.  */
379 struct private_thread_info
380 {
381   char *extra;
382   int core;
383 };
384
385 static void
386 free_private_thread_info (struct private_thread_info *info)
387 {
388   xfree (info->extra);
389   xfree (info);
390 }
391
392 /* This data could be associated with a target, but we do not always
393    have access to the current target when we need it, so for now it is
394    static.  This will be fine for as long as only one target is in use
395    at a time.  */
396 static struct remote_state *remote_state;
397
398 static struct remote_state *
399 get_remote_state_raw (void)
400 {
401   return remote_state;
402 }
403
404 /* Allocate a new struct remote_state with xmalloc, initialize it, and
405    return it.  */
406
407 static struct remote_state *
408 new_remote_state (void)
409 {
410   struct remote_state *result = XCNEW (struct remote_state);
411
412   /* The default buffer size is unimportant; it will be expanded
413      whenever a larger buffer is needed. */
414   result->buf_size = 400;
415   result->buf = xmalloc (result->buf_size);
416   result->remote_traceframe_number = -1;
417   result->last_sent_signal = GDB_SIGNAL_0;
418
419   return result;
420 }
421
422 /* Description of the remote protocol for a given architecture.  */
423
424 struct packet_reg
425 {
426   long offset; /* Offset into G packet.  */
427   long regnum; /* GDB's internal register number.  */
428   LONGEST pnum; /* Remote protocol register number.  */
429   int in_g_packet; /* Always part of G packet.  */
430   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
431      at present.  */
432   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
433      at present.  */
434 };
435
436 struct remote_arch_state
437 {
438   /* Description of the remote protocol registers.  */
439   long sizeof_g_packet;
440
441   /* Description of the remote protocol registers indexed by REGNUM
442      (making an array gdbarch_num_regs in size).  */
443   struct packet_reg *regs;
444
445   /* This is the size (in chars) of the first response to the ``g''
446      packet.  It is used as a heuristic when determining the maximum
447      size of memory-read and memory-write packets.  A target will
448      typically only reserve a buffer large enough to hold the ``g''
449      packet.  The size does not include packet overhead (headers and
450      trailers).  */
451   long actual_register_packet_size;
452
453   /* This is the maximum size (in chars) of a non read/write packet.
454      It is also used as a cap on the size of read/write packets.  */
455   long remote_packet_size;
456 };
457
458 /* Utility: generate error from an incoming stub packet.  */
459 static void
460 trace_error (char *buf)
461 {
462   if (*buf++ != 'E')
463     return;                     /* not an error msg */
464   switch (*buf)
465     {
466     case '1':                   /* malformed packet error */
467       if (*++buf == '0')        /*   general case: */
468         error (_("remote.c: error in outgoing packet."));
469       else
470         error (_("remote.c: error in outgoing packet at field #%ld."),
471                strtol (buf, NULL, 16));
472     default:
473       error (_("Target returns error code '%s'."), buf);
474     }
475 }
476
477 /* Utility: wait for reply from stub, while accepting "O" packets.  */
478 static char *
479 remote_get_noisy_reply (char **buf_p,
480                         long *sizeof_buf)
481 {
482   do                            /* Loop on reply from remote stub.  */
483     {
484       char *buf;
485
486       QUIT;                     /* Allow user to bail out with ^C.  */
487       getpkt (buf_p, sizeof_buf, 0);
488       buf = *buf_p;
489       if (buf[0] == 'E')
490         trace_error (buf);
491       else if (startswith (buf, "qRelocInsn:"))
492         {
493           ULONGEST ul;
494           CORE_ADDR from, to, org_to;
495           char *p, *pp;
496           int adjusted_size = 0;
497           int relocated = 0;
498
499           p = buf + strlen ("qRelocInsn:");
500           pp = unpack_varlen_hex (p, &ul);
501           if (*pp != ';')
502             error (_("invalid qRelocInsn packet: %s"), buf);
503           from = ul;
504
505           p = pp + 1;
506           unpack_varlen_hex (p, &ul);
507           to = ul;
508
509           org_to = to;
510
511           TRY
512             {
513               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
514               relocated = 1;
515             }
516           CATCH (ex, RETURN_MASK_ALL)
517             {
518               if (ex.error == MEMORY_ERROR)
519                 {
520                   /* Propagate memory errors silently back to the
521                      target.  The stub may have limited the range of
522                      addresses we can write to, for example.  */
523                 }
524               else
525                 {
526                   /* Something unexpectedly bad happened.  Be verbose
527                      so we can tell what, and propagate the error back
528                      to the stub, so it doesn't get stuck waiting for
529                      a response.  */
530                   exception_fprintf (gdb_stderr, ex,
531                                      _("warning: relocating instruction: "));
532                 }
533               putpkt ("E01");
534             }
535           END_CATCH
536
537           if (relocated)
538             {
539               adjusted_size = to - org_to;
540
541               xsnprintf (buf, *sizeof_buf, "qRelocInsn:%x", adjusted_size);
542               putpkt (buf);
543             }
544         }
545       else if (buf[0] == 'O' && buf[1] != 'K')
546         remote_console_output (buf + 1);        /* 'O' message from stub */
547       else
548         return buf;             /* Here's the actual reply.  */
549     }
550   while (1);
551 }
552
553 /* Handle for retreving the remote protocol data from gdbarch.  */
554 static struct gdbarch_data *remote_gdbarch_data_handle;
555
556 static struct remote_arch_state *
557 get_remote_arch_state (void)
558 {
559   return gdbarch_data (target_gdbarch (), remote_gdbarch_data_handle);
560 }
561
562 /* Fetch the global remote target state.  */
563
564 static struct remote_state *
565 get_remote_state (void)
566 {
567   /* Make sure that the remote architecture state has been
568      initialized, because doing so might reallocate rs->buf.  Any
569      function which calls getpkt also needs to be mindful of changes
570      to rs->buf, but this call limits the number of places which run
571      into trouble.  */
572   get_remote_arch_state ();
573
574   return get_remote_state_raw ();
575 }
576
577 static int
578 compare_pnums (const void *lhs_, const void *rhs_)
579 {
580   const struct packet_reg * const *lhs = lhs_;
581   const struct packet_reg * const *rhs = rhs_;
582
583   if ((*lhs)->pnum < (*rhs)->pnum)
584     return -1;
585   else if ((*lhs)->pnum == (*rhs)->pnum)
586     return 0;
587   else
588     return 1;
589 }
590
591 static int
592 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
593 {
594   int regnum, num_remote_regs, offset;
595   struct packet_reg **remote_regs;
596
597   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
598     {
599       struct packet_reg *r = &regs[regnum];
600
601       if (register_size (gdbarch, regnum) == 0)
602         /* Do not try to fetch zero-sized (placeholder) registers.  */
603         r->pnum = -1;
604       else
605         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
606
607       r->regnum = regnum;
608     }
609
610   /* Define the g/G packet format as the contents of each register
611      with a remote protocol number, in order of ascending protocol
612      number.  */
613
614   remote_regs = alloca (gdbarch_num_regs (gdbarch)
615                         * sizeof (struct packet_reg *));
616   for (num_remote_regs = 0, regnum = 0;
617        regnum < gdbarch_num_regs (gdbarch);
618        regnum++)
619     if (regs[regnum].pnum != -1)
620       remote_regs[num_remote_regs++] = &regs[regnum];
621
622   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
623          compare_pnums);
624
625   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
626     {
627       remote_regs[regnum]->in_g_packet = 1;
628       remote_regs[regnum]->offset = offset;
629       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
630     }
631
632   return offset;
633 }
634
635 /* Given the architecture described by GDBARCH, return the remote
636    protocol register's number and the register's offset in the g/G
637    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
638    If the target does not have a mapping for REGNUM, return false,
639    otherwise, return true.  */
640
641 int
642 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
643                                    int *pnum, int *poffset)
644 {
645   int sizeof_g_packet;
646   struct packet_reg *regs;
647   struct cleanup *old_chain;
648
649   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
650
651   regs = xcalloc (gdbarch_num_regs (gdbarch), sizeof (struct packet_reg));
652   old_chain = make_cleanup (xfree, regs);
653
654   sizeof_g_packet = map_regcache_remote_table (gdbarch, regs);
655
656   *pnum = regs[regnum].pnum;
657   *poffset = regs[regnum].offset;
658
659   do_cleanups (old_chain);
660
661   return *pnum != -1;
662 }
663
664 static void *
665 init_remote_state (struct gdbarch *gdbarch)
666 {
667   struct remote_state *rs = get_remote_state_raw ();
668   struct remote_arch_state *rsa;
669
670   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
671
672   /* Use the architecture to build a regnum<->pnum table, which will be
673      1:1 unless a feature set specifies otherwise.  */
674   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
675                                       gdbarch_num_regs (gdbarch),
676                                       struct packet_reg);
677
678   /* Record the maximum possible size of the g packet - it may turn out
679      to be smaller.  */
680   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
681
682   /* Default maximum number of characters in a packet body.  Many
683      remote stubs have a hardwired buffer size of 400 bytes
684      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
685      as the maximum packet-size to ensure that the packet and an extra
686      NUL character can always fit in the buffer.  This stops GDB
687      trashing stubs that try to squeeze an extra NUL into what is
688      already a full buffer (As of 1999-12-04 that was most stubs).  */
689   rsa->remote_packet_size = 400 - 1;
690
691   /* This one is filled in when a ``g'' packet is received.  */
692   rsa->actual_register_packet_size = 0;
693
694   /* Should rsa->sizeof_g_packet needs more space than the
695      default, adjust the size accordingly.  Remember that each byte is
696      encoded as two characters.  32 is the overhead for the packet
697      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
698      (``$NN:G...#NN'') is a better guess, the below has been padded a
699      little.  */
700   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
701     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
702
703   /* Make sure that the packet buffer is plenty big enough for
704      this architecture.  */
705   if (rs->buf_size < rsa->remote_packet_size)
706     {
707       rs->buf_size = 2 * rsa->remote_packet_size;
708       rs->buf = xrealloc (rs->buf, rs->buf_size);
709     }
710
711   return rsa;
712 }
713
714 /* Return the current allowed size of a remote packet.  This is
715    inferred from the current architecture, and should be used to
716    limit the length of outgoing packets.  */
717 static long
718 get_remote_packet_size (void)
719 {
720   struct remote_state *rs = get_remote_state ();
721   struct remote_arch_state *rsa = get_remote_arch_state ();
722
723   if (rs->explicit_packet_size)
724     return rs->explicit_packet_size;
725
726   return rsa->remote_packet_size;
727 }
728
729 static struct packet_reg *
730 packet_reg_from_regnum (struct remote_arch_state *rsa, long regnum)
731 {
732   if (regnum < 0 && regnum >= gdbarch_num_regs (target_gdbarch ()))
733     return NULL;
734   else
735     {
736       struct packet_reg *r = &rsa->regs[regnum];
737
738       gdb_assert (r->regnum == regnum);
739       return r;
740     }
741 }
742
743 static struct packet_reg *
744 packet_reg_from_pnum (struct remote_arch_state *rsa, LONGEST pnum)
745 {
746   int i;
747
748   for (i = 0; i < gdbarch_num_regs (target_gdbarch ()); i++)
749     {
750       struct packet_reg *r = &rsa->regs[i];
751
752       if (r->pnum == pnum)
753         return r;
754     }
755   return NULL;
756 }
757
758 static struct target_ops remote_ops;
759
760 static struct target_ops extended_remote_ops;
761
762 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
763    ``forever'' still use the normal timeout mechanism.  This is
764    currently used by the ASYNC code to guarentee that target reads
765    during the initial connect always time-out.  Once getpkt has been
766    modified to return a timeout indication and, in turn
767    remote_wait()/wait_for_inferior() have gained a timeout parameter
768    this can go away.  */
769 static int wait_forever_enabled_p = 1;
770
771 /* Allow the user to specify what sequence to send to the remote
772    when he requests a program interruption: Although ^C is usually
773    what remote systems expect (this is the default, here), it is
774    sometimes preferable to send a break.  On other systems such
775    as the Linux kernel, a break followed by g, which is Magic SysRq g
776    is required in order to interrupt the execution.  */
777 const char interrupt_sequence_control_c[] = "Ctrl-C";
778 const char interrupt_sequence_break[] = "BREAK";
779 const char interrupt_sequence_break_g[] = "BREAK-g";
780 static const char *const interrupt_sequence_modes[] =
781   {
782     interrupt_sequence_control_c,
783     interrupt_sequence_break,
784     interrupt_sequence_break_g,
785     NULL
786   };
787 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
788
789 static void
790 show_interrupt_sequence (struct ui_file *file, int from_tty,
791                          struct cmd_list_element *c,
792                          const char *value)
793 {
794   if (interrupt_sequence_mode == interrupt_sequence_control_c)
795     fprintf_filtered (file,
796                       _("Send the ASCII ETX character (Ctrl-c) "
797                         "to the remote target to interrupt the "
798                         "execution of the program.\n"));
799   else if (interrupt_sequence_mode == interrupt_sequence_break)
800     fprintf_filtered (file,
801                       _("send a break signal to the remote target "
802                         "to interrupt the execution of the program.\n"));
803   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
804     fprintf_filtered (file,
805                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
806                         "the remote target to interrupt the execution "
807                         "of Linux kernel.\n"));
808   else
809     internal_error (__FILE__, __LINE__,
810                     _("Invalid value for interrupt_sequence_mode: %s."),
811                     interrupt_sequence_mode);
812 }
813
814 /* This boolean variable specifies whether interrupt_sequence is sent
815    to the remote target when gdb connects to it.
816    This is mostly needed when you debug the Linux kernel: The Linux kernel
817    expects BREAK g which is Magic SysRq g for connecting gdb.  */
818 static int interrupt_on_connect = 0;
819
820 /* This variable is used to implement the "set/show remotebreak" commands.
821    Since these commands are now deprecated in favor of "set/show remote
822    interrupt-sequence", it no longer has any effect on the code.  */
823 static int remote_break;
824
825 static void
826 set_remotebreak (char *args, int from_tty, struct cmd_list_element *c)
827 {
828   if (remote_break)
829     interrupt_sequence_mode = interrupt_sequence_break;
830   else
831     interrupt_sequence_mode = interrupt_sequence_control_c;
832 }
833
834 static void
835 show_remotebreak (struct ui_file *file, int from_tty,
836                   struct cmd_list_element *c,
837                   const char *value)
838 {
839 }
840
841 /* This variable sets the number of bits in an address that are to be
842    sent in a memory ("M" or "m") packet.  Normally, after stripping
843    leading zeros, the entire address would be sent.  This variable
844    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
845    initial implementation of remote.c restricted the address sent in
846    memory packets to ``host::sizeof long'' bytes - (typically 32
847    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
848    address was never sent.  Since fixing this bug may cause a break in
849    some remote targets this variable is principly provided to
850    facilitate backward compatibility.  */
851
852 static unsigned int remote_address_size;
853
854 /* Temporary to track who currently owns the terminal.  See
855    remote_terminal_* for more details.  */
856
857 static int remote_async_terminal_ours_p;
858
859 /* The executable file to use for "run" on the remote side.  */
860
861 static char *remote_exec_file = "";
862
863 \f
864 /* User configurable variables for the number of characters in a
865    memory read/write packet.  MIN (rsa->remote_packet_size,
866    rsa->sizeof_g_packet) is the default.  Some targets need smaller
867    values (fifo overruns, et.al.) and some users need larger values
868    (speed up transfers).  The variables ``preferred_*'' (the user
869    request), ``current_*'' (what was actually set) and ``forced_*''
870    (Positive - a soft limit, negative - a hard limit).  */
871
872 struct memory_packet_config
873 {
874   char *name;
875   long size;
876   int fixed_p;
877 };
878
879 /* Compute the current size of a read/write packet.  Since this makes
880    use of ``actual_register_packet_size'' the computation is dynamic.  */
881
882 static long
883 get_memory_packet_size (struct memory_packet_config *config)
884 {
885   struct remote_state *rs = get_remote_state ();
886   struct remote_arch_state *rsa = get_remote_arch_state ();
887
888   /* NOTE: The somewhat arbitrary 16k comes from the knowledge (folk
889      law?) that some hosts don't cope very well with large alloca()
890      calls.  Eventually the alloca() code will be replaced by calls to
891      xmalloc() and make_cleanups() allowing this restriction to either
892      be lifted or removed.  */
893 #ifndef MAX_REMOTE_PACKET_SIZE
894 #define MAX_REMOTE_PACKET_SIZE 16384
895 #endif
896   /* NOTE: 20 ensures we can write at least one byte.  */
897 #ifndef MIN_REMOTE_PACKET_SIZE
898 #define MIN_REMOTE_PACKET_SIZE 20
899 #endif
900   long what_they_get;
901   if (config->fixed_p)
902     {
903       if (config->size <= 0)
904         what_they_get = MAX_REMOTE_PACKET_SIZE;
905       else
906         what_they_get = config->size;
907     }
908   else
909     {
910       what_they_get = get_remote_packet_size ();
911       /* Limit the packet to the size specified by the user.  */
912       if (config->size > 0
913           && what_they_get > config->size)
914         what_they_get = config->size;
915
916       /* Limit it to the size of the targets ``g'' response unless we have
917          permission from the stub to use a larger packet size.  */
918       if (rs->explicit_packet_size == 0
919           && rsa->actual_register_packet_size > 0
920           && what_they_get > rsa->actual_register_packet_size)
921         what_they_get = rsa->actual_register_packet_size;
922     }
923   if (what_they_get > MAX_REMOTE_PACKET_SIZE)
924     what_they_get = MAX_REMOTE_PACKET_SIZE;
925   if (what_they_get < MIN_REMOTE_PACKET_SIZE)
926     what_they_get = MIN_REMOTE_PACKET_SIZE;
927
928   /* Make sure there is room in the global buffer for this packet
929      (including its trailing NUL byte).  */
930   if (rs->buf_size < what_they_get + 1)
931     {
932       rs->buf_size = 2 * what_they_get;
933       rs->buf = xrealloc (rs->buf, 2 * what_they_get);
934     }
935
936   return what_they_get;
937 }
938
939 /* Update the size of a read/write packet.  If they user wants
940    something really big then do a sanity check.  */
941
942 static void
943 set_memory_packet_size (char *args, struct memory_packet_config *config)
944 {
945   int fixed_p = config->fixed_p;
946   long size = config->size;
947
948   if (args == NULL)
949     error (_("Argument required (integer, `fixed' or `limited')."));
950   else if (strcmp (args, "hard") == 0
951       || strcmp (args, "fixed") == 0)
952     fixed_p = 1;
953   else if (strcmp (args, "soft") == 0
954            || strcmp (args, "limit") == 0)
955     fixed_p = 0;
956   else
957     {
958       char *end;
959
960       size = strtoul (args, &end, 0);
961       if (args == end)
962         error (_("Invalid %s (bad syntax)."), config->name);
963 #if 0
964       /* Instead of explicitly capping the size of a packet to
965          MAX_REMOTE_PACKET_SIZE or dissallowing it, the user is
966          instead allowed to set the size to something arbitrarily
967          large.  */
968       if (size > MAX_REMOTE_PACKET_SIZE)
969         error (_("Invalid %s (too large)."), config->name);
970 #endif
971     }
972   /* Extra checks?  */
973   if (fixed_p && !config->fixed_p)
974     {
975       if (! query (_("The target may not be able to correctly handle a %s\n"
976                    "of %ld bytes. Change the packet size? "),
977                    config->name, size))
978         error (_("Packet size not changed."));
979     }
980   /* Update the config.  */
981   config->fixed_p = fixed_p;
982   config->size = size;
983 }
984
985 static void
986 show_memory_packet_size (struct memory_packet_config *config)
987 {
988   printf_filtered (_("The %s is %ld. "), config->name, config->size);
989   if (config->fixed_p)
990     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
991                      get_memory_packet_size (config));
992   else
993     printf_filtered (_("Packets are limited to %ld bytes.\n"),
994                      get_memory_packet_size (config));
995 }
996
997 static struct memory_packet_config memory_write_packet_config =
998 {
999   "memory-write-packet-size",
1000 };
1001
1002 static void
1003 set_memory_write_packet_size (char *args, int from_tty)
1004 {
1005   set_memory_packet_size (args, &memory_write_packet_config);
1006 }
1007
1008 static void
1009 show_memory_write_packet_size (char *args, int from_tty)
1010 {
1011   show_memory_packet_size (&memory_write_packet_config);
1012 }
1013
1014 static long
1015 get_memory_write_packet_size (void)
1016 {
1017   return get_memory_packet_size (&memory_write_packet_config);
1018 }
1019
1020 static struct memory_packet_config memory_read_packet_config =
1021 {
1022   "memory-read-packet-size",
1023 };
1024
1025 static void
1026 set_memory_read_packet_size (char *args, int from_tty)
1027 {
1028   set_memory_packet_size (args, &memory_read_packet_config);
1029 }
1030
1031 static void
1032 show_memory_read_packet_size (char *args, int from_tty)
1033 {
1034   show_memory_packet_size (&memory_read_packet_config);
1035 }
1036
1037 static long
1038 get_memory_read_packet_size (void)
1039 {
1040   long size = get_memory_packet_size (&memory_read_packet_config);
1041
1042   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1043      extra buffer size argument before the memory read size can be
1044      increased beyond this.  */
1045   if (size > get_remote_packet_size ())
1046     size = get_remote_packet_size ();
1047   return size;
1048 }
1049
1050 \f
1051 /* Generic configuration support for packets the stub optionally
1052    supports.  Allows the user to specify the use of the packet as well
1053    as allowing GDB to auto-detect support in the remote stub.  */
1054
1055 enum packet_support
1056   {
1057     PACKET_SUPPORT_UNKNOWN = 0,
1058     PACKET_ENABLE,
1059     PACKET_DISABLE
1060   };
1061
1062 struct packet_config
1063   {
1064     const char *name;
1065     const char *title;
1066
1067     /* If auto, GDB auto-detects support for this packet or feature,
1068        either through qSupported, or by trying the packet and looking
1069        at the response.  If true, GDB assumes the target supports this
1070        packet.  If false, the packet is disabled.  Configs that don't
1071        have an associated command always have this set to auto.  */
1072     enum auto_boolean detect;
1073
1074     /* Does the target support this packet?  */
1075     enum packet_support support;
1076   };
1077
1078 /* Analyze a packet's return value and update the packet config
1079    accordingly.  */
1080
1081 enum packet_result
1082 {
1083   PACKET_ERROR,
1084   PACKET_OK,
1085   PACKET_UNKNOWN
1086 };
1087
1088 static enum packet_support packet_config_support (struct packet_config *config);
1089 static enum packet_support packet_support (int packet);
1090
1091 static void
1092 show_packet_config_cmd (struct packet_config *config)
1093 {
1094   char *support = "internal-error";
1095
1096   switch (packet_config_support (config))
1097     {
1098     case PACKET_ENABLE:
1099       support = "enabled";
1100       break;
1101     case PACKET_DISABLE:
1102       support = "disabled";
1103       break;
1104     case PACKET_SUPPORT_UNKNOWN:
1105       support = "unknown";
1106       break;
1107     }
1108   switch (config->detect)
1109     {
1110     case AUTO_BOOLEAN_AUTO:
1111       printf_filtered (_("Support for the `%s' packet "
1112                          "is auto-detected, currently %s.\n"),
1113                        config->name, support);
1114       break;
1115     case AUTO_BOOLEAN_TRUE:
1116     case AUTO_BOOLEAN_FALSE:
1117       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1118                        config->name, support);
1119       break;
1120     }
1121 }
1122
1123 static void
1124 add_packet_config_cmd (struct packet_config *config, const char *name,
1125                        const char *title, int legacy)
1126 {
1127   char *set_doc;
1128   char *show_doc;
1129   char *cmd_name;
1130
1131   config->name = name;
1132   config->title = title;
1133   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1134                         name, title);
1135   show_doc = xstrprintf ("Show current use of remote "
1136                          "protocol `%s' (%s) packet",
1137                          name, title);
1138   /* set/show TITLE-packet {auto,on,off} */
1139   cmd_name = xstrprintf ("%s-packet", title);
1140   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1141                                 &config->detect, set_doc,
1142                                 show_doc, NULL, /* help_doc */
1143                                 NULL,
1144                                 show_remote_protocol_packet_cmd,
1145                                 &remote_set_cmdlist, &remote_show_cmdlist);
1146   /* The command code copies the documentation strings.  */
1147   xfree (set_doc);
1148   xfree (show_doc);
1149   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1150   if (legacy)
1151     {
1152       char *legacy_name;
1153
1154       legacy_name = xstrprintf ("%s-packet", name);
1155       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1156                      &remote_set_cmdlist);
1157       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1158                      &remote_show_cmdlist);
1159     }
1160 }
1161
1162 static enum packet_result
1163 packet_check_result (const char *buf)
1164 {
1165   if (buf[0] != '\0')
1166     {
1167       /* The stub recognized the packet request.  Check that the
1168          operation succeeded.  */
1169       if (buf[0] == 'E'
1170           && isxdigit (buf[1]) && isxdigit (buf[2])
1171           && buf[3] == '\0')
1172         /* "Enn"  - definitly an error.  */
1173         return PACKET_ERROR;
1174
1175       /* Always treat "E." as an error.  This will be used for
1176          more verbose error messages, such as E.memtypes.  */
1177       if (buf[0] == 'E' && buf[1] == '.')
1178         return PACKET_ERROR;
1179
1180       /* The packet may or may not be OK.  Just assume it is.  */
1181       return PACKET_OK;
1182     }
1183   else
1184     /* The stub does not support the packet.  */
1185     return PACKET_UNKNOWN;
1186 }
1187
1188 static enum packet_result
1189 packet_ok (const char *buf, struct packet_config *config)
1190 {
1191   enum packet_result result;
1192
1193   if (config->detect != AUTO_BOOLEAN_TRUE
1194       && config->support == PACKET_DISABLE)
1195     internal_error (__FILE__, __LINE__,
1196                     _("packet_ok: attempt to use a disabled packet"));
1197
1198   result = packet_check_result (buf);
1199   switch (result)
1200     {
1201     case PACKET_OK:
1202     case PACKET_ERROR:
1203       /* The stub recognized the packet request.  */
1204       if (config->support == PACKET_SUPPORT_UNKNOWN)
1205         {
1206           if (remote_debug)
1207             fprintf_unfiltered (gdb_stdlog,
1208                                 "Packet %s (%s) is supported\n",
1209                                 config->name, config->title);
1210           config->support = PACKET_ENABLE;
1211         }
1212       break;
1213     case PACKET_UNKNOWN:
1214       /* The stub does not support the packet.  */
1215       if (config->detect == AUTO_BOOLEAN_AUTO
1216           && config->support == PACKET_ENABLE)
1217         {
1218           /* If the stub previously indicated that the packet was
1219              supported then there is a protocol error.  */
1220           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1221                  config->name, config->title);
1222         }
1223       else if (config->detect == AUTO_BOOLEAN_TRUE)
1224         {
1225           /* The user set it wrong.  */
1226           error (_("Enabled packet %s (%s) not recognized by stub"),
1227                  config->name, config->title);
1228         }
1229
1230       if (remote_debug)
1231         fprintf_unfiltered (gdb_stdlog,
1232                             "Packet %s (%s) is NOT supported\n",
1233                             config->name, config->title);
1234       config->support = PACKET_DISABLE;
1235       break;
1236     }
1237
1238   return result;
1239 }
1240
1241 enum {
1242   PACKET_vCont = 0,
1243   PACKET_X,
1244   PACKET_qSymbol,
1245   PACKET_P,
1246   PACKET_p,
1247   PACKET_Z0,
1248   PACKET_Z1,
1249   PACKET_Z2,
1250   PACKET_Z3,
1251   PACKET_Z4,
1252   PACKET_vFile_open,
1253   PACKET_vFile_pread,
1254   PACKET_vFile_pwrite,
1255   PACKET_vFile_close,
1256   PACKET_vFile_unlink,
1257   PACKET_vFile_readlink,
1258   PACKET_vFile_fstat,
1259   PACKET_qXfer_auxv,
1260   PACKET_qXfer_features,
1261   PACKET_qXfer_exec_file,
1262   PACKET_qXfer_libraries,
1263   PACKET_qXfer_libraries_svr4,
1264   PACKET_qXfer_memory_map,
1265   PACKET_qXfer_spu_read,
1266   PACKET_qXfer_spu_write,
1267   PACKET_qXfer_osdata,
1268   PACKET_qXfer_threads,
1269   PACKET_qXfer_statictrace_read,
1270   PACKET_qXfer_traceframe_info,
1271   PACKET_qXfer_uib,
1272   PACKET_qGetTIBAddr,
1273   PACKET_qGetTLSAddr,
1274   PACKET_qSupported,
1275   PACKET_qTStatus,
1276   PACKET_QPassSignals,
1277   PACKET_QProgramSignals,
1278   PACKET_qCRC,
1279   PACKET_qSearch_memory,
1280   PACKET_vAttach,
1281   PACKET_vRun,
1282   PACKET_QStartNoAckMode,
1283   PACKET_vKill,
1284   PACKET_qXfer_siginfo_read,
1285   PACKET_qXfer_siginfo_write,
1286   PACKET_qAttached,
1287
1288   /* Support for conditional tracepoints.  */
1289   PACKET_ConditionalTracepoints,
1290
1291   /* Support for target-side breakpoint conditions.  */
1292   PACKET_ConditionalBreakpoints,
1293
1294   /* Support for target-side breakpoint commands.  */
1295   PACKET_BreakpointCommands,
1296
1297   /* Support for fast tracepoints.  */
1298   PACKET_FastTracepoints,
1299
1300   /* Support for static tracepoints.  */
1301   PACKET_StaticTracepoints,
1302
1303   /* Support for installing tracepoints while a trace experiment is
1304      running.  */
1305   PACKET_InstallInTrace,
1306
1307   PACKET_bc,
1308   PACKET_bs,
1309   PACKET_TracepointSource,
1310   PACKET_QAllow,
1311   PACKET_qXfer_fdpic,
1312   PACKET_QDisableRandomization,
1313   PACKET_QAgent,
1314   PACKET_QTBuffer_size,
1315   PACKET_Qbtrace_off,
1316   PACKET_Qbtrace_bts,
1317   PACKET_qXfer_btrace,
1318
1319   /* Support for the QNonStop packet.  */
1320   PACKET_QNonStop,
1321
1322   /* Support for multi-process extensions.  */
1323   PACKET_multiprocess_feature,
1324
1325   /* Support for enabling and disabling tracepoints while a trace
1326      experiment is running.  */
1327   PACKET_EnableDisableTracepoints_feature,
1328
1329   /* Support for collecting strings using the tracenz bytecode.  */
1330   PACKET_tracenz_feature,
1331
1332   /* Support for continuing to run a trace experiment while GDB is
1333      disconnected.  */
1334   PACKET_DisconnectedTracing_feature,
1335
1336   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1337   PACKET_augmented_libraries_svr4_read_feature,
1338
1339   /* Support for the qXfer:btrace-conf:read packet.  */
1340   PACKET_qXfer_btrace_conf,
1341
1342   /* Support for the Qbtrace-conf:bts:size packet.  */
1343   PACKET_Qbtrace_conf_bts_size,
1344
1345   /* Support for swbreak+ feature.  */
1346   PACKET_swbreak_feature,
1347
1348   /* Support for hwbreak+ feature.  */
1349   PACKET_hwbreak_feature,
1350
1351   /* Support for fork events.  */
1352   PACKET_fork_event_feature,
1353
1354   /* Support for vfork events.  */
1355   PACKET_vfork_event_feature,
1356
1357   PACKET_MAX
1358 };
1359
1360 static struct packet_config remote_protocol_packets[PACKET_MAX];
1361
1362 /* Returns the packet's corresponding "set remote foo-packet" command
1363    state.  See struct packet_config for more details.  */
1364
1365 static enum auto_boolean
1366 packet_set_cmd_state (int packet)
1367 {
1368   return remote_protocol_packets[packet].detect;
1369 }
1370
1371 /* Returns whether a given packet or feature is supported.  This takes
1372    into account the state of the corresponding "set remote foo-packet"
1373    command, which may be used to bypass auto-detection.  */
1374
1375 static enum packet_support
1376 packet_config_support (struct packet_config *config)
1377 {
1378   switch (config->detect)
1379     {
1380     case AUTO_BOOLEAN_TRUE:
1381       return PACKET_ENABLE;
1382     case AUTO_BOOLEAN_FALSE:
1383       return PACKET_DISABLE;
1384     case AUTO_BOOLEAN_AUTO:
1385       return config->support;
1386     default:
1387       gdb_assert_not_reached (_("bad switch"));
1388     }
1389 }
1390
1391 /* Same as packet_config_support, but takes the packet's enum value as
1392    argument.  */
1393
1394 static enum packet_support
1395 packet_support (int packet)
1396 {
1397   struct packet_config *config = &remote_protocol_packets[packet];
1398
1399   return packet_config_support (config);
1400 }
1401
1402 static void
1403 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1404                                  struct cmd_list_element *c,
1405                                  const char *value)
1406 {
1407   struct packet_config *packet;
1408
1409   for (packet = remote_protocol_packets;
1410        packet < &remote_protocol_packets[PACKET_MAX];
1411        packet++)
1412     {
1413       if (&packet->detect == c->var)
1414         {
1415           show_packet_config_cmd (packet);
1416           return;
1417         }
1418     }
1419   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1420                   c->name);
1421 }
1422
1423 /* Should we try one of the 'Z' requests?  */
1424
1425 enum Z_packet_type
1426 {
1427   Z_PACKET_SOFTWARE_BP,
1428   Z_PACKET_HARDWARE_BP,
1429   Z_PACKET_WRITE_WP,
1430   Z_PACKET_READ_WP,
1431   Z_PACKET_ACCESS_WP,
1432   NR_Z_PACKET_TYPES
1433 };
1434
1435 /* For compatibility with older distributions.  Provide a ``set remote
1436    Z-packet ...'' command that updates all the Z packet types.  */
1437
1438 static enum auto_boolean remote_Z_packet_detect;
1439
1440 static void
1441 set_remote_protocol_Z_packet_cmd (char *args, int from_tty,
1442                                   struct cmd_list_element *c)
1443 {
1444   int i;
1445
1446   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1447     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1448 }
1449
1450 static void
1451 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1452                                    struct cmd_list_element *c,
1453                                    const char *value)
1454 {
1455   int i;
1456
1457   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1458     {
1459       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1460     }
1461 }
1462
1463 /* Returns true if the multi-process extensions are in effect.  */
1464
1465 static int
1466 remote_multi_process_p (struct remote_state *rs)
1467 {
1468   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1469 }
1470
1471 /* Returns true if fork events are supported.  */
1472
1473 static int
1474 remote_fork_event_p (struct remote_state *rs)
1475 {
1476   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1477 }
1478
1479 /* Returns true if vfork events are supported.  */
1480
1481 static int
1482 remote_vfork_event_p (struct remote_state *rs)
1483 {
1484   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1485 }
1486
1487 /* Insert fork catchpoint target routine.  If fork events are enabled
1488    then return success, nothing more to do.  */
1489
1490 static int
1491 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1492 {
1493   struct remote_state *rs = get_remote_state ();
1494
1495   return !remote_fork_event_p (rs);
1496 }
1497
1498 /* Remove fork catchpoint target routine.  Nothing to do, just
1499    return success.  */
1500
1501 static int
1502 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1503 {
1504   return 0;
1505 }
1506
1507 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1508    then return success, nothing more to do.  */
1509
1510 static int
1511 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1512 {
1513   struct remote_state *rs = get_remote_state ();
1514
1515   return !remote_vfork_event_p (rs);
1516 }
1517
1518 /* Remove vfork catchpoint target routine.  Nothing to do, just
1519    return success.  */
1520
1521 static int
1522 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1523 {
1524   return 0;
1525 }
1526
1527 /* Tokens for use by the asynchronous signal handlers for SIGINT.  */
1528 static struct async_signal_handler *async_sigint_remote_twice_token;
1529 static struct async_signal_handler *async_sigint_remote_token;
1530
1531 \f
1532 /* Asynchronous signal handle registered as event loop source for
1533    when we have pending events ready to be passed to the core.  */
1534
1535 static struct async_event_handler *remote_async_inferior_event_token;
1536
1537 \f
1538
1539 static ptid_t magic_null_ptid;
1540 static ptid_t not_sent_ptid;
1541 static ptid_t any_thread_ptid;
1542
1543 /* Find out if the stub attached to PID (and hence GDB should offer to
1544    detach instead of killing it when bailing out).  */
1545
1546 static int
1547 remote_query_attached (int pid)
1548 {
1549   struct remote_state *rs = get_remote_state ();
1550   size_t size = get_remote_packet_size ();
1551
1552   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1553     return 0;
1554
1555   if (remote_multi_process_p (rs))
1556     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1557   else
1558     xsnprintf (rs->buf, size, "qAttached");
1559
1560   putpkt (rs->buf);
1561   getpkt (&rs->buf, &rs->buf_size, 0);
1562
1563   switch (packet_ok (rs->buf,
1564                      &remote_protocol_packets[PACKET_qAttached]))
1565     {
1566     case PACKET_OK:
1567       if (strcmp (rs->buf, "1") == 0)
1568         return 1;
1569       break;
1570     case PACKET_ERROR:
1571       warning (_("Remote failure reply: %s"), rs->buf);
1572       break;
1573     case PACKET_UNKNOWN:
1574       break;
1575     }
1576
1577   return 0;
1578 }
1579
1580 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1581    has been invented by GDB, instead of reported by the target.  Since
1582    we can be connected to a remote system before before knowing about
1583    any inferior, mark the target with execution when we find the first
1584    inferior.  If ATTACHED is 1, then we had just attached to this
1585    inferior.  If it is 0, then we just created this inferior.  If it
1586    is -1, then try querying the remote stub to find out if it had
1587    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1588    attempt to open this inferior's executable as the main executable
1589    if no main executable is open already.  */
1590
1591 static struct inferior *
1592 remote_add_inferior (int fake_pid_p, int pid, int attached,
1593                      int try_open_exec)
1594 {
1595   struct inferior *inf;
1596
1597   /* Check whether this process we're learning about is to be
1598      considered attached, or if is to be considered to have been
1599      spawned by the stub.  */
1600   if (attached == -1)
1601     attached = remote_query_attached (pid);
1602
1603   if (gdbarch_has_global_solist (target_gdbarch ()))
1604     {
1605       /* If the target shares code across all inferiors, then every
1606          attach adds a new inferior.  */
1607       inf = add_inferior (pid);
1608
1609       /* ... and every inferior is bound to the same program space.
1610          However, each inferior may still have its own address
1611          space.  */
1612       inf->aspace = maybe_new_address_space ();
1613       inf->pspace = current_program_space;
1614     }
1615   else
1616     {
1617       /* In the traditional debugging scenario, there's a 1-1 match
1618          between program/address spaces.  We simply bind the inferior
1619          to the program space's address space.  */
1620       inf = current_inferior ();
1621       inferior_appeared (inf, pid);
1622     }
1623
1624   inf->attach_flag = attached;
1625   inf->fake_pid_p = fake_pid_p;
1626
1627   /* If no main executable is currently open then attempt to
1628      open the file that was executed to create this inferior.  */
1629   if (try_open_exec && get_exec_file (0) == NULL)
1630     exec_file_locate_attach (pid, 1);
1631
1632   return inf;
1633 }
1634
1635 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1636    according to RUNNING.  */
1637
1638 static void
1639 remote_add_thread (ptid_t ptid, int running)
1640 {
1641   struct remote_state *rs = get_remote_state ();
1642
1643   /* GDB historically didn't pull threads in the initial connection
1644      setup.  If the remote target doesn't even have a concept of
1645      threads (e.g., a bare-metal target), even if internally we
1646      consider that a single-threaded target, mentioning a new thread
1647      might be confusing to the user.  Be silent then, preserving the
1648      age old behavior.  */
1649   if (rs->starting_up)
1650     add_thread_silent (ptid);
1651   else
1652     add_thread (ptid);
1653
1654   set_executing (ptid, running);
1655   set_running (ptid, running);
1656 }
1657
1658 /* Come here when we learn about a thread id from the remote target.
1659    It may be the first time we hear about such thread, so take the
1660    opportunity to add it to GDB's thread list.  In case this is the
1661    first time we're noticing its corresponding inferior, add it to
1662    GDB's inferior list as well.  */
1663
1664 static void
1665 remote_notice_new_inferior (ptid_t currthread, int running)
1666 {
1667   /* If this is a new thread, add it to GDB's thread list.
1668      If we leave it up to WFI to do this, bad things will happen.  */
1669
1670   if (in_thread_list (currthread) && is_exited (currthread))
1671     {
1672       /* We're seeing an event on a thread id we knew had exited.
1673          This has to be a new thread reusing the old id.  Add it.  */
1674       remote_add_thread (currthread, running);
1675       return;
1676     }
1677
1678   if (!in_thread_list (currthread))
1679     {
1680       struct inferior *inf = NULL;
1681       int pid = ptid_get_pid (currthread);
1682
1683       if (ptid_is_pid (inferior_ptid)
1684           && pid == ptid_get_pid (inferior_ptid))
1685         {
1686           /* inferior_ptid has no thread member yet.  This can happen
1687              with the vAttach -> remote_wait,"TAAthread:" path if the
1688              stub doesn't support qC.  This is the first stop reported
1689              after an attach, so this is the main thread.  Update the
1690              ptid in the thread list.  */
1691           if (in_thread_list (pid_to_ptid (pid)))
1692             thread_change_ptid (inferior_ptid, currthread);
1693           else
1694             {
1695               remote_add_thread (currthread, running);
1696               inferior_ptid = currthread;
1697             }
1698           return;
1699         }
1700
1701       if (ptid_equal (magic_null_ptid, inferior_ptid))
1702         {
1703           /* inferior_ptid is not set yet.  This can happen with the
1704              vRun -> remote_wait,"TAAthread:" path if the stub
1705              doesn't support qC.  This is the first stop reported
1706              after an attach, so this is the main thread.  Update the
1707              ptid in the thread list.  */
1708           thread_change_ptid (inferior_ptid, currthread);
1709           return;
1710         }
1711
1712       /* When connecting to a target remote, or to a target
1713          extended-remote which already was debugging an inferior, we
1714          may not know about it yet.  Add it before adding its child
1715          thread, so notifications are emitted in a sensible order.  */
1716       if (!in_inferior_list (ptid_get_pid (currthread)))
1717         {
1718           struct remote_state *rs = get_remote_state ();
1719           int fake_pid_p = !remote_multi_process_p (rs);
1720
1721           inf = remote_add_inferior (fake_pid_p,
1722                                      ptid_get_pid (currthread), -1, 1);
1723         }
1724
1725       /* This is really a new thread.  Add it.  */
1726       remote_add_thread (currthread, running);
1727
1728       /* If we found a new inferior, let the common code do whatever
1729          it needs to with it (e.g., read shared libraries, insert
1730          breakpoints), unless we're just setting up an all-stop
1731          connection.  */
1732       if (inf != NULL)
1733         {
1734           struct remote_state *rs = get_remote_state ();
1735
1736           if (non_stop || !rs->starting_up)
1737             notice_new_inferior (currthread, running, 0);
1738         }
1739     }
1740 }
1741
1742 /* Return the private thread data, creating it if necessary.  */
1743
1744 static struct private_thread_info *
1745 demand_private_info (ptid_t ptid)
1746 {
1747   struct thread_info *info = find_thread_ptid (ptid);
1748
1749   gdb_assert (info);
1750
1751   if (!info->priv)
1752     {
1753       info->priv = xmalloc (sizeof (*(info->priv)));
1754       info->private_dtor = free_private_thread_info;
1755       info->priv->core = -1;
1756       info->priv->extra = 0;
1757     }
1758
1759   return info->priv;
1760 }
1761
1762 /* Call this function as a result of
1763    1) A halt indication (T packet) containing a thread id
1764    2) A direct query of currthread
1765    3) Successful execution of set thread */
1766
1767 static void
1768 record_currthread (struct remote_state *rs, ptid_t currthread)
1769 {
1770   rs->general_thread = currthread;
1771 }
1772
1773 /* If 'QPassSignals' is supported, tell the remote stub what signals
1774    it can simply pass through to the inferior without reporting.  */
1775
1776 static void
1777 remote_pass_signals (struct target_ops *self,
1778                      int numsigs, unsigned char *pass_signals)
1779 {
1780   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1781     {
1782       char *pass_packet, *p;
1783       int count = 0, i;
1784       struct remote_state *rs = get_remote_state ();
1785
1786       gdb_assert (numsigs < 256);
1787       for (i = 0; i < numsigs; i++)
1788         {
1789           if (pass_signals[i])
1790             count++;
1791         }
1792       pass_packet = xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1793       strcpy (pass_packet, "QPassSignals:");
1794       p = pass_packet + strlen (pass_packet);
1795       for (i = 0; i < numsigs; i++)
1796         {
1797           if (pass_signals[i])
1798             {
1799               if (i >= 16)
1800                 *p++ = tohex (i >> 4);
1801               *p++ = tohex (i & 15);
1802               if (count)
1803                 *p++ = ';';
1804               else
1805                 break;
1806               count--;
1807             }
1808         }
1809       *p = 0;
1810       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
1811         {
1812           putpkt (pass_packet);
1813           getpkt (&rs->buf, &rs->buf_size, 0);
1814           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
1815           if (rs->last_pass_packet)
1816             xfree (rs->last_pass_packet);
1817           rs->last_pass_packet = pass_packet;
1818         }
1819       else
1820         xfree (pass_packet);
1821     }
1822 }
1823
1824 /* If 'QProgramSignals' is supported, tell the remote stub what
1825    signals it should pass through to the inferior when detaching.  */
1826
1827 static void
1828 remote_program_signals (struct target_ops *self,
1829                         int numsigs, unsigned char *signals)
1830 {
1831   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
1832     {
1833       char *packet, *p;
1834       int count = 0, i;
1835       struct remote_state *rs = get_remote_state ();
1836
1837       gdb_assert (numsigs < 256);
1838       for (i = 0; i < numsigs; i++)
1839         {
1840           if (signals[i])
1841             count++;
1842         }
1843       packet = xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
1844       strcpy (packet, "QProgramSignals:");
1845       p = packet + strlen (packet);
1846       for (i = 0; i < numsigs; i++)
1847         {
1848           if (signal_pass_state (i))
1849             {
1850               if (i >= 16)
1851                 *p++ = tohex (i >> 4);
1852               *p++ = tohex (i & 15);
1853               if (count)
1854                 *p++ = ';';
1855               else
1856                 break;
1857               count--;
1858             }
1859         }
1860       *p = 0;
1861       if (!rs->last_program_signals_packet
1862           || strcmp (rs->last_program_signals_packet, packet) != 0)
1863         {
1864           putpkt (packet);
1865           getpkt (&rs->buf, &rs->buf_size, 0);
1866           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
1867           xfree (rs->last_program_signals_packet);
1868           rs->last_program_signals_packet = packet;
1869         }
1870       else
1871         xfree (packet);
1872     }
1873 }
1874
1875 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
1876    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
1877    thread.  If GEN is set, set the general thread, if not, then set
1878    the step/continue thread.  */
1879 static void
1880 set_thread (struct ptid ptid, int gen)
1881 {
1882   struct remote_state *rs = get_remote_state ();
1883   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
1884   char *buf = rs->buf;
1885   char *endbuf = rs->buf + get_remote_packet_size ();
1886
1887   if (ptid_equal (state, ptid))
1888     return;
1889
1890   *buf++ = 'H';
1891   *buf++ = gen ? 'g' : 'c';
1892   if (ptid_equal (ptid, magic_null_ptid))
1893     xsnprintf (buf, endbuf - buf, "0");
1894   else if (ptid_equal (ptid, any_thread_ptid))
1895     xsnprintf (buf, endbuf - buf, "0");
1896   else if (ptid_equal (ptid, minus_one_ptid))
1897     xsnprintf (buf, endbuf - buf, "-1");
1898   else
1899     write_ptid (buf, endbuf, ptid);
1900   putpkt (rs->buf);
1901   getpkt (&rs->buf, &rs->buf_size, 0);
1902   if (gen)
1903     rs->general_thread = ptid;
1904   else
1905     rs->continue_thread = ptid;
1906 }
1907
1908 static void
1909 set_general_thread (struct ptid ptid)
1910 {
1911   set_thread (ptid, 1);
1912 }
1913
1914 static void
1915 set_continue_thread (struct ptid ptid)
1916 {
1917   set_thread (ptid, 0);
1918 }
1919
1920 /* Change the remote current process.  Which thread within the process
1921    ends up selected isn't important, as long as it is the same process
1922    as what INFERIOR_PTID points to.
1923
1924    This comes from that fact that there is no explicit notion of
1925    "selected process" in the protocol.  The selected process for
1926    general operations is the process the selected general thread
1927    belongs to.  */
1928
1929 static void
1930 set_general_process (void)
1931 {
1932   struct remote_state *rs = get_remote_state ();
1933
1934   /* If the remote can't handle multiple processes, don't bother.  */
1935   if (!rs->extended || !remote_multi_process_p (rs))
1936     return;
1937
1938   /* We only need to change the remote current thread if it's pointing
1939      at some other process.  */
1940   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
1941     set_general_thread (inferior_ptid);
1942 }
1943
1944 \f
1945 /* Return nonzero if this is the main thread that we made up ourselves
1946    to model non-threaded targets as single-threaded.  */
1947
1948 static int
1949 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
1950 {
1951   struct remote_state *rs = get_remote_state ();
1952   char *p, *endp;
1953
1954   if (ptid_equal (ptid, magic_null_ptid))
1955     /* The main thread is always alive.  */
1956     return 1;
1957
1958   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
1959     /* The main thread is always alive.  This can happen after a
1960        vAttach, if the remote side doesn't support
1961        multi-threading.  */
1962     return 1;
1963
1964   return 0;
1965 }
1966
1967 /* Return nonzero if the thread PTID is still alive on the remote
1968    system.  */
1969
1970 static int
1971 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
1972 {
1973   struct remote_state *rs = get_remote_state ();
1974   char *p, *endp;
1975
1976   /* Check if this is a thread that we made up ourselves to model
1977      non-threaded targets as single-threaded.  */
1978   if (remote_thread_always_alive (ops, ptid))
1979     return 1;
1980
1981   p = rs->buf;
1982   endp = rs->buf + get_remote_packet_size ();
1983
1984   *p++ = 'T';
1985   write_ptid (p, endp, ptid);
1986
1987   putpkt (rs->buf);
1988   getpkt (&rs->buf, &rs->buf_size, 0);
1989   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
1990 }
1991
1992 /* About these extended threadlist and threadinfo packets.  They are
1993    variable length packets but, the fields within them are often fixed
1994    length.  They are redundent enough to send over UDP as is the
1995    remote protocol in general.  There is a matching unit test module
1996    in libstub.  */
1997
1998 /* WARNING: This threadref data structure comes from the remote O.S.,
1999    libstub protocol encoding, and remote.c.  It is not particularly
2000    changable.  */
2001
2002 /* Right now, the internal structure is int. We want it to be bigger.
2003    Plan to fix this.  */
2004
2005 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2006
2007 /* gdb_ext_thread_info is an internal GDB data structure which is
2008    equivalent to the reply of the remote threadinfo packet.  */
2009
2010 struct gdb_ext_thread_info
2011   {
2012     threadref threadid;         /* External form of thread reference.  */
2013     int active;                 /* Has state interesting to GDB?
2014                                    regs, stack.  */
2015     char display[256];          /* Brief state display, name,
2016                                    blocked/suspended.  */
2017     char shortname[32];         /* To be used to name threads.  */
2018     char more_display[256];     /* Long info, statistics, queue depth,
2019                                    whatever.  */
2020   };
2021
2022 /* The volume of remote transfers can be limited by submitting
2023    a mask containing bits specifying the desired information.
2024    Use a union of these values as the 'selection' parameter to
2025    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2026
2027 #define TAG_THREADID 1
2028 #define TAG_EXISTS 2
2029 #define TAG_DISPLAY 4
2030 #define TAG_THREADNAME 8
2031 #define TAG_MOREDISPLAY 16
2032
2033 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2034
2035 static char *unpack_nibble (char *buf, int *val);
2036
2037 static char *unpack_byte (char *buf, int *value);
2038
2039 static char *pack_int (char *buf, int value);
2040
2041 static char *unpack_int (char *buf, int *value);
2042
2043 static char *unpack_string (char *src, char *dest, int length);
2044
2045 static char *pack_threadid (char *pkt, threadref *id);
2046
2047 static char *unpack_threadid (char *inbuf, threadref *id);
2048
2049 void int_to_threadref (threadref *id, int value);
2050
2051 static int threadref_to_int (threadref *ref);
2052
2053 static void copy_threadref (threadref *dest, threadref *src);
2054
2055 static int threadmatch (threadref *dest, threadref *src);
2056
2057 static char *pack_threadinfo_request (char *pkt, int mode,
2058                                       threadref *id);
2059
2060 static int remote_unpack_thread_info_response (char *pkt,
2061                                                threadref *expectedref,
2062                                                struct gdb_ext_thread_info
2063                                                *info);
2064
2065
2066 static int remote_get_threadinfo (threadref *threadid,
2067                                   int fieldset, /*TAG mask */
2068                                   struct gdb_ext_thread_info *info);
2069
2070 static char *pack_threadlist_request (char *pkt, int startflag,
2071                                       int threadcount,
2072                                       threadref *nextthread);
2073
2074 static int parse_threadlist_response (char *pkt,
2075                                       int result_limit,
2076                                       threadref *original_echo,
2077                                       threadref *resultlist,
2078                                       int *doneflag);
2079
2080 static int remote_get_threadlist (int startflag,
2081                                   threadref *nextthread,
2082                                   int result_limit,
2083                                   int *done,
2084                                   int *result_count,
2085                                   threadref *threadlist);
2086
2087 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2088
2089 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2090                                        void *context, int looplimit);
2091
2092 static int remote_newthread_step (threadref *ref, void *context);
2093
2094
2095 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2096    buffer we're allowed to write to.  Returns
2097    BUF+CHARACTERS_WRITTEN.  */
2098
2099 static char *
2100 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2101 {
2102   int pid, tid;
2103   struct remote_state *rs = get_remote_state ();
2104
2105   if (remote_multi_process_p (rs))
2106     {
2107       pid = ptid_get_pid (ptid);
2108       if (pid < 0)
2109         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2110       else
2111         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2112     }
2113   tid = ptid_get_lwp (ptid);
2114   if (tid < 0)
2115     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2116   else
2117     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2118
2119   return buf;
2120 }
2121
2122 /* Extract a PTID from BUF.  If non-null, OBUF is set to the to one
2123    passed the last parsed char.  Returns null_ptid on error.  */
2124
2125 static ptid_t
2126 read_ptid (char *buf, char **obuf)
2127 {
2128   char *p = buf;
2129   char *pp;
2130   ULONGEST pid = 0, tid = 0;
2131
2132   if (*p == 'p')
2133     {
2134       /* Multi-process ptid.  */
2135       pp = unpack_varlen_hex (p + 1, &pid);
2136       if (*pp != '.')
2137         error (_("invalid remote ptid: %s"), p);
2138
2139       p = pp;
2140       pp = unpack_varlen_hex (p + 1, &tid);
2141       if (obuf)
2142         *obuf = pp;
2143       return ptid_build (pid, tid, 0);
2144     }
2145
2146   /* No multi-process.  Just a tid.  */
2147   pp = unpack_varlen_hex (p, &tid);
2148
2149   /* Since the stub is not sending a process id, then default to
2150      what's in inferior_ptid, unless it's null at this point.  If so,
2151      then since there's no way to know the pid of the reported
2152      threads, use the magic number.  */
2153   if (ptid_equal (inferior_ptid, null_ptid))
2154     pid = ptid_get_pid (magic_null_ptid);
2155   else
2156     pid = ptid_get_pid (inferior_ptid);
2157
2158   if (obuf)
2159     *obuf = pp;
2160   return ptid_build (pid, tid, 0);
2161 }
2162
2163 static int
2164 stubhex (int ch)
2165 {
2166   if (ch >= 'a' && ch <= 'f')
2167     return ch - 'a' + 10;
2168   if (ch >= '0' && ch <= '9')
2169     return ch - '0';
2170   if (ch >= 'A' && ch <= 'F')
2171     return ch - 'A' + 10;
2172   return -1;
2173 }
2174
2175 static int
2176 stub_unpack_int (char *buff, int fieldlength)
2177 {
2178   int nibble;
2179   int retval = 0;
2180
2181   while (fieldlength)
2182     {
2183       nibble = stubhex (*buff++);
2184       retval |= nibble;
2185       fieldlength--;
2186       if (fieldlength)
2187         retval = retval << 4;
2188     }
2189   return retval;
2190 }
2191
2192 static char *
2193 unpack_nibble (char *buf, int *val)
2194 {
2195   *val = fromhex (*buf++);
2196   return buf;
2197 }
2198
2199 static char *
2200 unpack_byte (char *buf, int *value)
2201 {
2202   *value = stub_unpack_int (buf, 2);
2203   return buf + 2;
2204 }
2205
2206 static char *
2207 pack_int (char *buf, int value)
2208 {
2209   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2210   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2211   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2212   buf = pack_hex_byte (buf, (value & 0xff));
2213   return buf;
2214 }
2215
2216 static char *
2217 unpack_int (char *buf, int *value)
2218 {
2219   *value = stub_unpack_int (buf, 8);
2220   return buf + 8;
2221 }
2222
2223 #if 0                   /* Currently unused, uncomment when needed.  */
2224 static char *pack_string (char *pkt, char *string);
2225
2226 static char *
2227 pack_string (char *pkt, char *string)
2228 {
2229   char ch;
2230   int len;
2231
2232   len = strlen (string);
2233   if (len > 200)
2234     len = 200;          /* Bigger than most GDB packets, junk???  */
2235   pkt = pack_hex_byte (pkt, len);
2236   while (len-- > 0)
2237     {
2238       ch = *string++;
2239       if ((ch == '\0') || (ch == '#'))
2240         ch = '*';               /* Protect encapsulation.  */
2241       *pkt++ = ch;
2242     }
2243   return pkt;
2244 }
2245 #endif /* 0 (unused) */
2246
2247 static char *
2248 unpack_string (char *src, char *dest, int length)
2249 {
2250   while (length--)
2251     *dest++ = *src++;
2252   *dest = '\0';
2253   return src;
2254 }
2255
2256 static char *
2257 pack_threadid (char *pkt, threadref *id)
2258 {
2259   char *limit;
2260   unsigned char *altid;
2261
2262   altid = (unsigned char *) id;
2263   limit = pkt + BUF_THREAD_ID_SIZE;
2264   while (pkt < limit)
2265     pkt = pack_hex_byte (pkt, *altid++);
2266   return pkt;
2267 }
2268
2269
2270 static char *
2271 unpack_threadid (char *inbuf, threadref *id)
2272 {
2273   char *altref;
2274   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2275   int x, y;
2276
2277   altref = (char *) id;
2278
2279   while (inbuf < limit)
2280     {
2281       x = stubhex (*inbuf++);
2282       y = stubhex (*inbuf++);
2283       *altref++ = (x << 4) | y;
2284     }
2285   return inbuf;
2286 }
2287
2288 /* Externally, threadrefs are 64 bits but internally, they are still
2289    ints.  This is due to a mismatch of specifications.  We would like
2290    to use 64bit thread references internally.  This is an adapter
2291    function.  */
2292
2293 void
2294 int_to_threadref (threadref *id, int value)
2295 {
2296   unsigned char *scan;
2297
2298   scan = (unsigned char *) id;
2299   {
2300     int i = 4;
2301     while (i--)
2302       *scan++ = 0;
2303   }
2304   *scan++ = (value >> 24) & 0xff;
2305   *scan++ = (value >> 16) & 0xff;
2306   *scan++ = (value >> 8) & 0xff;
2307   *scan++ = (value & 0xff);
2308 }
2309
2310 static int
2311 threadref_to_int (threadref *ref)
2312 {
2313   int i, value = 0;
2314   unsigned char *scan;
2315
2316   scan = *ref;
2317   scan += 4;
2318   i = 4;
2319   while (i-- > 0)
2320     value = (value << 8) | ((*scan++) & 0xff);
2321   return value;
2322 }
2323
2324 static void
2325 copy_threadref (threadref *dest, threadref *src)
2326 {
2327   int i;
2328   unsigned char *csrc, *cdest;
2329
2330   csrc = (unsigned char *) src;
2331   cdest = (unsigned char *) dest;
2332   i = 8;
2333   while (i--)
2334     *cdest++ = *csrc++;
2335 }
2336
2337 static int
2338 threadmatch (threadref *dest, threadref *src)
2339 {
2340   /* Things are broken right now, so just assume we got a match.  */
2341 #if 0
2342   unsigned char *srcp, *destp;
2343   int i, result;
2344   srcp = (char *) src;
2345   destp = (char *) dest;
2346
2347   result = 1;
2348   while (i-- > 0)
2349     result &= (*srcp++ == *destp++) ? 1 : 0;
2350   return result;
2351 #endif
2352   return 1;
2353 }
2354
2355 /*
2356    threadid:1,        # always request threadid
2357    context_exists:2,
2358    display:4,
2359    unique_name:8,
2360    more_display:16
2361  */
2362
2363 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2364
2365 static char *
2366 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2367 {
2368   *pkt++ = 'q';                         /* Info Query */
2369   *pkt++ = 'P';                         /* process or thread info */
2370   pkt = pack_int (pkt, mode);           /* mode */
2371   pkt = pack_threadid (pkt, id);        /* threadid */
2372   *pkt = '\0';                          /* terminate */
2373   return pkt;
2374 }
2375
2376 /* These values tag the fields in a thread info response packet.  */
2377 /* Tagging the fields allows us to request specific fields and to
2378    add more fields as time goes by.  */
2379
2380 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2381 #define TAG_EXISTS 2            /* Is this process defined enough to
2382                                    fetch registers and its stack?  */
2383 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2384 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2385 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2386                                    the process.  */
2387
2388 static int
2389 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2390                                     struct gdb_ext_thread_info *info)
2391 {
2392   struct remote_state *rs = get_remote_state ();
2393   int mask, length;
2394   int tag;
2395   threadref ref;
2396   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2397   int retval = 1;
2398
2399   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2400   info->active = 0;
2401   info->display[0] = '\0';
2402   info->shortname[0] = '\0';
2403   info->more_display[0] = '\0';
2404
2405   /* Assume the characters indicating the packet type have been
2406      stripped.  */
2407   pkt = unpack_int (pkt, &mask);        /* arg mask */
2408   pkt = unpack_threadid (pkt, &ref);
2409
2410   if (mask == 0)
2411     warning (_("Incomplete response to threadinfo request."));
2412   if (!threadmatch (&ref, expectedref))
2413     {                   /* This is an answer to a different request.  */
2414       warning (_("ERROR RMT Thread info mismatch."));
2415       return 0;
2416     }
2417   copy_threadref (&info->threadid, &ref);
2418
2419   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2420
2421   /* Packets are terminated with nulls.  */
2422   while ((pkt < limit) && mask && *pkt)
2423     {
2424       pkt = unpack_int (pkt, &tag);     /* tag */
2425       pkt = unpack_byte (pkt, &length); /* length */
2426       if (!(tag & mask))                /* Tags out of synch with mask.  */
2427         {
2428           warning (_("ERROR RMT: threadinfo tag mismatch."));
2429           retval = 0;
2430           break;
2431         }
2432       if (tag == TAG_THREADID)
2433         {
2434           if (length != 16)
2435             {
2436               warning (_("ERROR RMT: length of threadid is not 16."));
2437               retval = 0;
2438               break;
2439             }
2440           pkt = unpack_threadid (pkt, &ref);
2441           mask = mask & ~TAG_THREADID;
2442           continue;
2443         }
2444       if (tag == TAG_EXISTS)
2445         {
2446           info->active = stub_unpack_int (pkt, length);
2447           pkt += length;
2448           mask = mask & ~(TAG_EXISTS);
2449           if (length > 8)
2450             {
2451               warning (_("ERROR RMT: 'exists' length too long."));
2452               retval = 0;
2453               break;
2454             }
2455           continue;
2456         }
2457       if (tag == TAG_THREADNAME)
2458         {
2459           pkt = unpack_string (pkt, &info->shortname[0], length);
2460           mask = mask & ~TAG_THREADNAME;
2461           continue;
2462         }
2463       if (tag == TAG_DISPLAY)
2464         {
2465           pkt = unpack_string (pkt, &info->display[0], length);
2466           mask = mask & ~TAG_DISPLAY;
2467           continue;
2468         }
2469       if (tag == TAG_MOREDISPLAY)
2470         {
2471           pkt = unpack_string (pkt, &info->more_display[0], length);
2472           mask = mask & ~TAG_MOREDISPLAY;
2473           continue;
2474         }
2475       warning (_("ERROR RMT: unknown thread info tag."));
2476       break;                    /* Not a tag we know about.  */
2477     }
2478   return retval;
2479 }
2480
2481 static int
2482 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2483                        struct gdb_ext_thread_info *info)
2484 {
2485   struct remote_state *rs = get_remote_state ();
2486   int result;
2487
2488   pack_threadinfo_request (rs->buf, fieldset, threadid);
2489   putpkt (rs->buf);
2490   getpkt (&rs->buf, &rs->buf_size, 0);
2491
2492   if (rs->buf[0] == '\0')
2493     return 0;
2494
2495   result = remote_unpack_thread_info_response (rs->buf + 2,
2496                                                threadid, info);
2497   return result;
2498 }
2499
2500 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2501
2502 static char *
2503 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2504                          threadref *nextthread)
2505 {
2506   *pkt++ = 'q';                 /* info query packet */
2507   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2508   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2509   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2510   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2511   *pkt = '\0';
2512   return pkt;
2513 }
2514
2515 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2516
2517 static int
2518 parse_threadlist_response (char *pkt, int result_limit,
2519                            threadref *original_echo, threadref *resultlist,
2520                            int *doneflag)
2521 {
2522   struct remote_state *rs = get_remote_state ();
2523   char *limit;
2524   int count, resultcount, done;
2525
2526   resultcount = 0;
2527   /* Assume the 'q' and 'M chars have been stripped.  */
2528   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2529   /* done parse past here */
2530   pkt = unpack_byte (pkt, &count);      /* count field */
2531   pkt = unpack_nibble (pkt, &done);
2532   /* The first threadid is the argument threadid.  */
2533   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2534   while ((count-- > 0) && (pkt < limit))
2535     {
2536       pkt = unpack_threadid (pkt, resultlist++);
2537       if (resultcount++ >= result_limit)
2538         break;
2539     }
2540   if (doneflag)
2541     *doneflag = done;
2542   return resultcount;
2543 }
2544
2545 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2546    qL packet is not supported, 0 on error and 1 on success.  */
2547
2548 static int
2549 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2550                        int *done, int *result_count, threadref *threadlist)
2551 {
2552   struct remote_state *rs = get_remote_state ();
2553   int result = 1;
2554
2555   /* Trancate result limit to be smaller than the packet size.  */
2556   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2557       >= get_remote_packet_size ())
2558     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2559
2560   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2561   putpkt (rs->buf);
2562   getpkt (&rs->buf, &rs->buf_size, 0);
2563   if (*rs->buf == '\0')
2564     {
2565       /* Packet not supported.  */
2566       return -1;
2567     }
2568
2569   *result_count =
2570     parse_threadlist_response (rs->buf + 2, result_limit,
2571                                &rs->echo_nextthread, threadlist, done);
2572
2573   if (!threadmatch (&rs->echo_nextthread, nextthread))
2574     {
2575       /* FIXME: This is a good reason to drop the packet.  */
2576       /* Possably, there is a duplicate response.  */
2577       /* Possabilities :
2578          retransmit immediatly - race conditions
2579          retransmit after timeout - yes
2580          exit
2581          wait for packet, then exit
2582        */
2583       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2584       return 0;                 /* I choose simply exiting.  */
2585     }
2586   if (*result_count <= 0)
2587     {
2588       if (*done != 1)
2589         {
2590           warning (_("RMT ERROR : failed to get remote thread list."));
2591           result = 0;
2592         }
2593       return result;            /* break; */
2594     }
2595   if (*result_count > result_limit)
2596     {
2597       *result_count = 0;
2598       warning (_("RMT ERROR: threadlist response longer than requested."));
2599       return 0;
2600     }
2601   return result;
2602 }
2603
2604 /* Fetch the list of remote threads, with the qL packet, and call
2605    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2606    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2607    STEPFUNCTION returns false.  If the packet is not supported,
2608    returns -1.  */
2609
2610 static int
2611 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2612                             int looplimit)
2613 {
2614   struct remote_state *rs = get_remote_state ();
2615   int done, i, result_count;
2616   int startflag = 1;
2617   int result = 1;
2618   int loopcount = 0;
2619
2620   done = 0;
2621   while (!done)
2622     {
2623       if (loopcount++ > looplimit)
2624         {
2625           result = 0;
2626           warning (_("Remote fetch threadlist -infinite loop-."));
2627           break;
2628         }
2629       result = remote_get_threadlist (startflag, &rs->nextthread,
2630                                       MAXTHREADLISTRESULTS,
2631                                       &done, &result_count,
2632                                       rs->resultthreadlist);
2633       if (result <= 0)
2634         break;
2635       /* Clear for later iterations.  */
2636       startflag = 0;
2637       /* Setup to resume next batch of thread references, set nextthread.  */
2638       if (result_count >= 1)
2639         copy_threadref (&rs->nextthread,
2640                         &rs->resultthreadlist[result_count - 1]);
2641       i = 0;
2642       while (result_count--)
2643         {
2644           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2645             {
2646               result = 0;
2647               break;
2648             }
2649         }
2650     }
2651   return result;
2652 }
2653
2654 /* A thread found on the remote target.  */
2655
2656 typedef struct thread_item
2657 {
2658   /* The thread's PTID.  */
2659   ptid_t ptid;
2660
2661   /* The thread's extra info.  May be NULL.  */
2662   char *extra;
2663
2664   /* The core the thread was running on.  -1 if not known.  */
2665   int core;
2666 } thread_item_t;
2667 DEF_VEC_O(thread_item_t);
2668
2669 /* Context passed around to the various methods listing remote
2670    threads.  As new threads are found, they're added to the ITEMS
2671    vector.  */
2672
2673 struct threads_listing_context
2674 {
2675   /* The threads found on the remote target.  */
2676   VEC (thread_item_t) *items;
2677 };
2678
2679 /* Discard the contents of the constructed thread listing context.  */
2680
2681 static void
2682 clear_threads_listing_context (void *p)
2683 {
2684   struct threads_listing_context *context = p;
2685   int i;
2686   struct thread_item *item;
2687
2688   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2689     xfree (item->extra);
2690
2691   VEC_free (thread_item_t, context->items);
2692 }
2693
2694 /* Remove the thread specified as the related_pid field of WS
2695    from the CONTEXT list.  */
2696
2697 static void
2698 threads_listing_context_remove (struct target_waitstatus *ws,
2699                                 struct threads_listing_context *context)
2700 {
2701   struct thread_item *item;
2702   int i;
2703   ptid_t child_ptid = ws->value.related_pid;
2704
2705   for (i = 0; VEC_iterate (thread_item_t, context->items, i, item); ++i)
2706     {
2707       if (ptid_equal (item->ptid, child_ptid))
2708         {
2709           VEC_ordered_remove (thread_item_t, context->items, i);
2710           break;
2711         }
2712     }
2713 }
2714
2715 static int
2716 remote_newthread_step (threadref *ref, void *data)
2717 {
2718   struct threads_listing_context *context = data;
2719   struct thread_item item;
2720   int pid = ptid_get_pid (inferior_ptid);
2721
2722   item.ptid = ptid_build (pid, threadref_to_int (ref), 0);
2723   item.core = -1;
2724   item.extra = NULL;
2725
2726   VEC_safe_push (thread_item_t, context->items, &item);
2727
2728   return 1;                     /* continue iterator */
2729 }
2730
2731 #define CRAZY_MAX_THREADS 1000
2732
2733 static ptid_t
2734 remote_current_thread (ptid_t oldpid)
2735 {
2736   struct remote_state *rs = get_remote_state ();
2737
2738   putpkt ("qC");
2739   getpkt (&rs->buf, &rs->buf_size, 0);
2740   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
2741     return read_ptid (&rs->buf[2], NULL);
2742   else
2743     return oldpid;
2744 }
2745
2746 /* List remote threads using the deprecated qL packet.  */
2747
2748 static int
2749 remote_get_threads_with_ql (struct target_ops *ops,
2750                             struct threads_listing_context *context)
2751 {
2752   if (remote_threadlist_iterator (remote_newthread_step, context,
2753                                   CRAZY_MAX_THREADS) >= 0)
2754     return 1;
2755
2756   return 0;
2757 }
2758
2759 #if defined(HAVE_LIBEXPAT)
2760
2761 static void
2762 start_thread (struct gdb_xml_parser *parser,
2763               const struct gdb_xml_element *element,
2764               void *user_data, VEC(gdb_xml_value_s) *attributes)
2765 {
2766   struct threads_listing_context *data = user_data;
2767
2768   struct thread_item item;
2769   char *id;
2770   struct gdb_xml_value *attr;
2771
2772   id = xml_find_attribute (attributes, "id")->value;
2773   item.ptid = read_ptid (id, NULL);
2774
2775   attr = xml_find_attribute (attributes, "core");
2776   if (attr != NULL)
2777     item.core = *(ULONGEST *) attr->value;
2778   else
2779     item.core = -1;
2780
2781   item.extra = 0;
2782
2783   VEC_safe_push (thread_item_t, data->items, &item);
2784 }
2785
2786 static void
2787 end_thread (struct gdb_xml_parser *parser,
2788             const struct gdb_xml_element *element,
2789             void *user_data, const char *body_text)
2790 {
2791   struct threads_listing_context *data = user_data;
2792
2793   if (body_text && *body_text)
2794     VEC_last (thread_item_t, data->items)->extra = xstrdup (body_text);
2795 }
2796
2797 const struct gdb_xml_attribute thread_attributes[] = {
2798   { "id", GDB_XML_AF_NONE, NULL, NULL },
2799   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
2800   { NULL, GDB_XML_AF_NONE, NULL, NULL }
2801 };
2802
2803 const struct gdb_xml_element thread_children[] = {
2804   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2805 };
2806
2807 const struct gdb_xml_element threads_children[] = {
2808   { "thread", thread_attributes, thread_children,
2809     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
2810     start_thread, end_thread },
2811   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2812 };
2813
2814 const struct gdb_xml_element threads_elements[] = {
2815   { "threads", NULL, threads_children,
2816     GDB_XML_EF_NONE, NULL, NULL },
2817   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
2818 };
2819
2820 #endif
2821
2822 /* List remote threads using qXfer:threads:read.  */
2823
2824 static int
2825 remote_get_threads_with_qxfer (struct target_ops *ops,
2826                                struct threads_listing_context *context)
2827 {
2828 #if defined(HAVE_LIBEXPAT)
2829   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
2830     {
2831       char *xml = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
2832       struct cleanup *back_to = make_cleanup (xfree, xml);
2833
2834       if (xml != NULL && *xml != '\0')
2835         {
2836           gdb_xml_parse_quick (_("threads"), "threads.dtd",
2837                                threads_elements, xml, context);
2838         }
2839
2840       do_cleanups (back_to);
2841       return 1;
2842     }
2843 #endif
2844
2845   return 0;
2846 }
2847
2848 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
2849
2850 static int
2851 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
2852                                      struct threads_listing_context *context)
2853 {
2854   struct remote_state *rs = get_remote_state ();
2855
2856   if (rs->use_threadinfo_query)
2857     {
2858       char *bufp;
2859
2860       putpkt ("qfThreadInfo");
2861       getpkt (&rs->buf, &rs->buf_size, 0);
2862       bufp = rs->buf;
2863       if (bufp[0] != '\0')              /* q packet recognized */
2864         {
2865           while (*bufp++ == 'm')        /* reply contains one or more TID */
2866             {
2867               do
2868                 {
2869                   struct thread_item item;
2870
2871                   item.ptid = read_ptid (bufp, &bufp);
2872                   item.core = -1;
2873                   item.extra = NULL;
2874
2875                   VEC_safe_push (thread_item_t, context->items, &item);
2876                 }
2877               while (*bufp++ == ',');   /* comma-separated list */
2878               putpkt ("qsThreadInfo");
2879               getpkt (&rs->buf, &rs->buf_size, 0);
2880               bufp = rs->buf;
2881             }
2882           return 1;
2883         }
2884       else
2885         {
2886           /* Packet not recognized.  */
2887           rs->use_threadinfo_query = 0;
2888         }
2889     }
2890
2891   return 0;
2892 }
2893
2894 /* Implement the to_update_thread_list function for the remote
2895    targets.  */
2896
2897 static void
2898 remote_update_thread_list (struct target_ops *ops)
2899 {
2900   struct remote_state *rs = get_remote_state ();
2901   struct threads_listing_context context;
2902   struct cleanup *old_chain;
2903   int got_list = 0;
2904
2905   context.items = NULL;
2906   old_chain = make_cleanup (clear_threads_listing_context, &context);
2907
2908   /* We have a few different mechanisms to fetch the thread list.  Try
2909      them all, starting with the most preferred one first, falling
2910      back to older methods.  */
2911   if (remote_get_threads_with_qxfer (ops, &context)
2912       || remote_get_threads_with_qthreadinfo (ops, &context)
2913       || remote_get_threads_with_ql (ops, &context))
2914     {
2915       int i;
2916       struct thread_item *item;
2917       struct thread_info *tp, *tmp;
2918
2919       got_list = 1;
2920
2921       if (VEC_empty (thread_item_t, context.items)
2922           && remote_thread_always_alive (ops, inferior_ptid))
2923         {
2924           /* Some targets don't really support threads, but still
2925              reply an (empty) thread list in response to the thread
2926              listing packets, instead of replying "packet not
2927              supported".  Exit early so we don't delete the main
2928              thread.  */
2929           do_cleanups (old_chain);
2930           return;
2931         }
2932
2933       /* CONTEXT now holds the current thread list on the remote
2934          target end.  Delete GDB-side threads no longer found on the
2935          target.  */
2936       ALL_THREADS_SAFE (tp, tmp)
2937         {
2938           for (i = 0;
2939                VEC_iterate (thread_item_t, context.items, i, item);
2940                ++i)
2941             {
2942               if (ptid_equal (item->ptid, tp->ptid))
2943                 break;
2944             }
2945
2946           if (i == VEC_length (thread_item_t, context.items))
2947             {
2948               /* Not found.  */
2949               delete_thread (tp->ptid);
2950             }
2951         }
2952
2953       /* Remove any unreported fork child threads from CONTEXT so
2954          that we don't interfere with follow fork, which is where
2955          creation of such threads is handled.  */
2956       remove_new_fork_children (&context);
2957
2958       /* And now add threads we don't know about yet to our list.  */
2959       for (i = 0;
2960            VEC_iterate (thread_item_t, context.items, i, item);
2961            ++i)
2962         {
2963           if (!ptid_equal (item->ptid, null_ptid))
2964             {
2965               struct private_thread_info *info;
2966               /* In non-stop mode, we assume new found threads are
2967                  running until proven otherwise with a stop reply.  In
2968                  all-stop, we can only get here if all threads are
2969                  stopped.  */
2970               int running = non_stop ? 1 : 0;
2971
2972               remote_notice_new_inferior (item->ptid, running);
2973
2974               info = demand_private_info (item->ptid);
2975               info->core = item->core;
2976               info->extra = item->extra;
2977               item->extra = NULL;
2978             }
2979         }
2980     }
2981
2982   if (!got_list)
2983     {
2984       /* If no thread listing method is supported, then query whether
2985          each known thread is alive, one by one, with the T packet.
2986          If the target doesn't support threads at all, then this is a
2987          no-op.  See remote_thread_alive.  */
2988       prune_threads ();
2989     }
2990
2991   do_cleanups (old_chain);
2992 }
2993
2994 /*
2995  * Collect a descriptive string about the given thread.
2996  * The target may say anything it wants to about the thread
2997  * (typically info about its blocked / runnable state, name, etc.).
2998  * This string will appear in the info threads display.
2999  *
3000  * Optional: targets are not required to implement this function.
3001  */
3002
3003 static char *
3004 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3005 {
3006   struct remote_state *rs = get_remote_state ();
3007   int result;
3008   int set;
3009   threadref id;
3010   struct gdb_ext_thread_info threadinfo;
3011   static char display_buf[100]; /* arbitrary...  */
3012   int n = 0;                    /* position in display_buf */
3013
3014   if (rs->remote_desc == 0)             /* paranoia */
3015     internal_error (__FILE__, __LINE__,
3016                     _("remote_threads_extra_info"));
3017
3018   if (ptid_equal (tp->ptid, magic_null_ptid)
3019       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3020     /* This is the main thread which was added by GDB.  The remote
3021        server doesn't know about it.  */
3022     return NULL;
3023
3024   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3025     {
3026       struct thread_info *info = find_thread_ptid (tp->ptid);
3027
3028       if (info && info->priv)
3029         return info->priv->extra;
3030       else
3031         return NULL;
3032     }
3033
3034   if (rs->use_threadextra_query)
3035     {
3036       char *b = rs->buf;
3037       char *endb = rs->buf + get_remote_packet_size ();
3038
3039       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3040       b += strlen (b);
3041       write_ptid (b, endb, tp->ptid);
3042
3043       putpkt (rs->buf);
3044       getpkt (&rs->buf, &rs->buf_size, 0);
3045       if (rs->buf[0] != 0)
3046         {
3047           n = min (strlen (rs->buf) / 2, sizeof (display_buf));
3048           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3049           display_buf [result] = '\0';
3050           return display_buf;
3051         }
3052     }
3053
3054   /* If the above query fails, fall back to the old method.  */
3055   rs->use_threadextra_query = 0;
3056   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3057     | TAG_MOREDISPLAY | TAG_DISPLAY;
3058   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3059   if (remote_get_threadinfo (&id, set, &threadinfo))
3060     if (threadinfo.active)
3061       {
3062         if (*threadinfo.shortname)
3063           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3064                           " Name: %s,", threadinfo.shortname);
3065         if (*threadinfo.display)
3066           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3067                           " State: %s,", threadinfo.display);
3068         if (*threadinfo.more_display)
3069           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3070                           " Priority: %s", threadinfo.more_display);
3071
3072         if (n > 0)
3073           {
3074             /* For purely cosmetic reasons, clear up trailing commas.  */
3075             if (',' == display_buf[n-1])
3076               display_buf[n-1] = ' ';
3077             return display_buf;
3078           }
3079       }
3080   return NULL;
3081 }
3082 \f
3083
3084 static int
3085 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3086                                     struct static_tracepoint_marker *marker)
3087 {
3088   struct remote_state *rs = get_remote_state ();
3089   char *p = rs->buf;
3090
3091   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3092   p += strlen (p);
3093   p += hexnumstr (p, addr);
3094   putpkt (rs->buf);
3095   getpkt (&rs->buf, &rs->buf_size, 0);
3096   p = rs->buf;
3097
3098   if (*p == 'E')
3099     error (_("Remote failure reply: %s"), p);
3100
3101   if (*p++ == 'm')
3102     {
3103       parse_static_tracepoint_marker_definition (p, &p, marker);
3104       return 1;
3105     }
3106
3107   return 0;
3108 }
3109
3110 static VEC(static_tracepoint_marker_p) *
3111 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3112                                            const char *strid)
3113 {
3114   struct remote_state *rs = get_remote_state ();
3115   VEC(static_tracepoint_marker_p) *markers = NULL;
3116   struct static_tracepoint_marker *marker = NULL;
3117   struct cleanup *old_chain;
3118   char *p;
3119
3120   /* Ask for a first packet of static tracepoint marker
3121      definition.  */
3122   putpkt ("qTfSTM");
3123   getpkt (&rs->buf, &rs->buf_size, 0);
3124   p = rs->buf;
3125   if (*p == 'E')
3126     error (_("Remote failure reply: %s"), p);
3127
3128   old_chain = make_cleanup (free_current_marker, &marker);
3129
3130   while (*p++ == 'm')
3131     {
3132       if (marker == NULL)
3133         marker = XCNEW (struct static_tracepoint_marker);
3134
3135       do
3136         {
3137           parse_static_tracepoint_marker_definition (p, &p, marker);
3138
3139           if (strid == NULL || strcmp (strid, marker->str_id) == 0)
3140             {
3141               VEC_safe_push (static_tracepoint_marker_p,
3142                              markers, marker);
3143               marker = NULL;
3144             }
3145           else
3146             {
3147               release_static_tracepoint_marker (marker);
3148               memset (marker, 0, sizeof (*marker));
3149             }
3150         }
3151       while (*p++ == ',');      /* comma-separated list */
3152       /* Ask for another packet of static tracepoint definition.  */
3153       putpkt ("qTsSTM");
3154       getpkt (&rs->buf, &rs->buf_size, 0);
3155       p = rs->buf;
3156     }
3157
3158   do_cleanups (old_chain);
3159   return markers;
3160 }
3161
3162 \f
3163 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3164
3165 static ptid_t
3166 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3167 {
3168   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3169 }
3170 \f
3171
3172 /* Restart the remote side; this is an extended protocol operation.  */
3173
3174 static void
3175 extended_remote_restart (void)
3176 {
3177   struct remote_state *rs = get_remote_state ();
3178
3179   /* Send the restart command; for reasons I don't understand the
3180      remote side really expects a number after the "R".  */
3181   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3182   putpkt (rs->buf);
3183
3184   remote_fileio_reset ();
3185 }
3186 \f
3187 /* Clean up connection to a remote debugger.  */
3188
3189 static void
3190 remote_close (struct target_ops *self)
3191 {
3192   struct remote_state *rs = get_remote_state ();
3193
3194   if (rs->remote_desc == NULL)
3195     return; /* already closed */
3196
3197   /* Make sure we leave stdin registered in the event loop, and we
3198      don't leave the async SIGINT signal handler installed.  */
3199   remote_terminal_ours (self);
3200
3201   serial_close (rs->remote_desc);
3202   rs->remote_desc = NULL;
3203
3204   /* We don't have a connection to the remote stub anymore.  Get rid
3205      of all the inferiors and their threads we were controlling.
3206      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3207      will be unable to find the thread corresponding to (pid, 0, 0).  */
3208   inferior_ptid = null_ptid;
3209   discard_all_inferiors ();
3210
3211   /* We are closing the remote target, so we should discard
3212      everything of this target.  */
3213   discard_pending_stop_replies_in_queue (rs);
3214
3215   if (remote_async_inferior_event_token)
3216     delete_async_event_handler (&remote_async_inferior_event_token);
3217
3218   remote_notif_state_xfree (rs->notif_state);
3219
3220   trace_reset_local_state ();
3221 }
3222
3223 /* Query the remote side for the text, data and bss offsets.  */
3224
3225 static void
3226 get_offsets (void)
3227 {
3228   struct remote_state *rs = get_remote_state ();
3229   char *buf;
3230   char *ptr;
3231   int lose, num_segments = 0, do_sections, do_segments;
3232   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3233   struct section_offsets *offs;
3234   struct symfile_segment_data *data;
3235
3236   if (symfile_objfile == NULL)
3237     return;
3238
3239   putpkt ("qOffsets");
3240   getpkt (&rs->buf, &rs->buf_size, 0);
3241   buf = rs->buf;
3242
3243   if (buf[0] == '\000')
3244     return;                     /* Return silently.  Stub doesn't support
3245                                    this command.  */
3246   if (buf[0] == 'E')
3247     {
3248       warning (_("Remote failure reply: %s"), buf);
3249       return;
3250     }
3251
3252   /* Pick up each field in turn.  This used to be done with scanf, but
3253      scanf will make trouble if CORE_ADDR size doesn't match
3254      conversion directives correctly.  The following code will work
3255      with any size of CORE_ADDR.  */
3256   text_addr = data_addr = bss_addr = 0;
3257   ptr = buf;
3258   lose = 0;
3259
3260   if (startswith (ptr, "Text="))
3261     {
3262       ptr += 5;
3263       /* Don't use strtol, could lose on big values.  */
3264       while (*ptr && *ptr != ';')
3265         text_addr = (text_addr << 4) + fromhex (*ptr++);
3266
3267       if (startswith (ptr, ";Data="))
3268         {
3269           ptr += 6;
3270           while (*ptr && *ptr != ';')
3271             data_addr = (data_addr << 4) + fromhex (*ptr++);
3272         }
3273       else
3274         lose = 1;
3275
3276       if (!lose && startswith (ptr, ";Bss="))
3277         {
3278           ptr += 5;
3279           while (*ptr && *ptr != ';')
3280             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3281
3282           if (bss_addr != data_addr)
3283             warning (_("Target reported unsupported offsets: %s"), buf);
3284         }
3285       else
3286         lose = 1;
3287     }
3288   else if (startswith (ptr, "TextSeg="))
3289     {
3290       ptr += 8;
3291       /* Don't use strtol, could lose on big values.  */
3292       while (*ptr && *ptr != ';')
3293         text_addr = (text_addr << 4) + fromhex (*ptr++);
3294       num_segments = 1;
3295
3296       if (startswith (ptr, ";DataSeg="))
3297         {
3298           ptr += 9;
3299           while (*ptr && *ptr != ';')
3300             data_addr = (data_addr << 4) + fromhex (*ptr++);
3301           num_segments++;
3302         }
3303     }
3304   else
3305     lose = 1;
3306
3307   if (lose)
3308     error (_("Malformed response to offset query, %s"), buf);
3309   else if (*ptr != '\0')
3310     warning (_("Target reported unsupported offsets: %s"), buf);
3311
3312   offs = ((struct section_offsets *)
3313           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3314   memcpy (offs, symfile_objfile->section_offsets,
3315           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3316
3317   data = get_symfile_segment_data (symfile_objfile->obfd);
3318   do_segments = (data != NULL);
3319   do_sections = num_segments == 0;
3320
3321   if (num_segments > 0)
3322     {
3323       segments[0] = text_addr;
3324       segments[1] = data_addr;
3325     }
3326   /* If we have two segments, we can still try to relocate everything
3327      by assuming that the .text and .data offsets apply to the whole
3328      text and data segments.  Convert the offsets given in the packet
3329      to base addresses for symfile_map_offsets_to_segments.  */
3330   else if (data && data->num_segments == 2)
3331     {
3332       segments[0] = data->segment_bases[0] + text_addr;
3333       segments[1] = data->segment_bases[1] + data_addr;
3334       num_segments = 2;
3335     }
3336   /* If the object file has only one segment, assume that it is text
3337      rather than data; main programs with no writable data are rare,
3338      but programs with no code are useless.  Of course the code might
3339      have ended up in the data segment... to detect that we would need
3340      the permissions here.  */
3341   else if (data && data->num_segments == 1)
3342     {
3343       segments[0] = data->segment_bases[0] + text_addr;
3344       num_segments = 1;
3345     }
3346   /* There's no way to relocate by segment.  */
3347   else
3348     do_segments = 0;
3349
3350   if (do_segments)
3351     {
3352       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3353                                                  offs, num_segments, segments);
3354
3355       if (ret == 0 && !do_sections)
3356         error (_("Can not handle qOffsets TextSeg "
3357                  "response with this symbol file"));
3358
3359       if (ret > 0)
3360         do_sections = 0;
3361     }
3362
3363   if (data)
3364     free_symfile_segment_data (data);
3365
3366   if (do_sections)
3367     {
3368       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3369
3370       /* This is a temporary kludge to force data and bss to use the
3371          same offsets because that's what nlmconv does now.  The real
3372          solution requires changes to the stub and remote.c that I
3373          don't have time to do right now.  */
3374
3375       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3376       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3377     }
3378
3379   objfile_relocate (symfile_objfile, offs);
3380 }
3381
3382 /* Callback for iterate_over_threads.  Set the STOP_REQUESTED flags in
3383    threads we know are stopped already.  This is used during the
3384    initial remote connection in non-stop mode --- threads that are
3385    reported as already being stopped are left stopped.  */
3386
3387 static int
3388 set_stop_requested_callback (struct thread_info *thread, void *data)
3389 {
3390   /* If we have a stop reply for this thread, it must be stopped.  */
3391   if (peek_stop_reply (thread->ptid))
3392     set_stop_requested (thread->ptid, 1);
3393
3394   return 0;
3395 }
3396
3397 /* Send interrupt_sequence to remote target.  */
3398 static void
3399 send_interrupt_sequence (void)
3400 {
3401   struct remote_state *rs = get_remote_state ();
3402
3403   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3404     remote_serial_write ("\x03", 1);
3405   else if (interrupt_sequence_mode == interrupt_sequence_break)
3406     serial_send_break (rs->remote_desc);
3407   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3408     {
3409       serial_send_break (rs->remote_desc);
3410       remote_serial_write ("g", 1);
3411     }
3412   else
3413     internal_error (__FILE__, __LINE__,
3414                     _("Invalid value for interrupt_sequence_mode: %s."),
3415                     interrupt_sequence_mode);
3416 }
3417
3418
3419 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3420    and extract the PTID.  Returns NULL_PTID if not found.  */
3421
3422 static ptid_t
3423 stop_reply_extract_thread (char *stop_reply)
3424 {
3425   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3426     {
3427       char *p;
3428
3429       /* Txx r:val ; r:val (...)  */
3430       p = &stop_reply[3];
3431
3432       /* Look for "register" named "thread".  */
3433       while (*p != '\0')
3434         {
3435           char *p1;
3436
3437           p1 = strchr (p, ':');
3438           if (p1 == NULL)
3439             return null_ptid;
3440
3441           if (strncmp (p, "thread", p1 - p) == 0)
3442             return read_ptid (++p1, &p);
3443
3444           p1 = strchr (p, ';');
3445           if (p1 == NULL)
3446             return null_ptid;
3447           p1++;
3448
3449           p = p1;
3450         }
3451     }
3452
3453   return null_ptid;
3454 }
3455
3456 /* Determine the remote side's current thread.  If we have a stop
3457    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3458    "thread" register we can extract the current thread from.  If not,
3459    ask the remote which is the current thread with qC.  The former
3460    method avoids a roundtrip.  */
3461
3462 static ptid_t
3463 get_current_thread (char *wait_status)
3464 {
3465   ptid_t ptid;
3466
3467   /* Note we don't use remote_parse_stop_reply as that makes use of
3468      the target architecture, which we haven't yet fully determined at
3469      this point.  */
3470   if (wait_status != NULL)
3471     ptid = stop_reply_extract_thread (wait_status);
3472   if (ptid_equal (ptid, null_ptid))
3473     ptid = remote_current_thread (inferior_ptid);
3474
3475   return ptid;
3476 }
3477
3478 /* Query the remote target for which is the current thread/process,
3479    add it to our tables, and update INFERIOR_PTID.  The caller is
3480    responsible for setting the state such that the remote end is ready
3481    to return the current thread.
3482
3483    This function is called after handling the '?' or 'vRun' packets,
3484    whose response is a stop reply from which we can also try
3485    extracting the thread.  If the target doesn't support the explicit
3486    qC query, we infer the current thread from that stop reply, passed
3487    in in WAIT_STATUS, which may be NULL.  */
3488
3489 static void
3490 add_current_inferior_and_thread (char *wait_status)
3491 {
3492   struct remote_state *rs = get_remote_state ();
3493   int fake_pid_p = 0;
3494   ptid_t ptid = null_ptid;
3495
3496   inferior_ptid = null_ptid;
3497
3498   /* Now, if we have thread information, update inferior_ptid.  */
3499   ptid = get_current_thread (wait_status);
3500
3501   if (!ptid_equal (ptid, null_ptid))
3502     {
3503       if (!remote_multi_process_p (rs))
3504         fake_pid_p = 1;
3505
3506       inferior_ptid = ptid;
3507     }
3508   else
3509     {
3510       /* Without this, some commands which require an active target
3511          (such as kill) won't work.  This variable serves (at least)
3512          double duty as both the pid of the target process (if it has
3513          such), and as a flag indicating that a target is active.  */
3514       inferior_ptid = magic_null_ptid;
3515       fake_pid_p = 1;
3516     }
3517
3518   remote_add_inferior (fake_pid_p, ptid_get_pid (inferior_ptid), -1, 1);
3519
3520   /* Add the main thread.  */
3521   add_thread_silent (inferior_ptid);
3522 }
3523
3524 static void
3525 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3526 {
3527   struct remote_state *rs = get_remote_state ();
3528   struct packet_config *noack_config;
3529   char *wait_status = NULL;
3530
3531   immediate_quit++;             /* Allow user to interrupt it.  */
3532   QUIT;
3533
3534   if (interrupt_on_connect)
3535     send_interrupt_sequence ();
3536
3537   /* Ack any packet which the remote side has already sent.  */
3538   serial_write (rs->remote_desc, "+", 1);
3539
3540   /* Signal other parts that we're going through the initial setup,
3541      and so things may not be stable yet.  */
3542   rs->starting_up = 1;
3543
3544   /* The first packet we send to the target is the optional "supported
3545      packets" request.  If the target can answer this, it will tell us
3546      which later probes to skip.  */
3547   remote_query_supported ();
3548
3549   /* If the stub wants to get a QAllow, compose one and send it.  */
3550   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
3551     remote_set_permissions (target);
3552
3553   /* Next, we possibly activate noack mode.
3554
3555      If the QStartNoAckMode packet configuration is set to AUTO,
3556      enable noack mode if the stub reported a wish for it with
3557      qSupported.
3558
3559      If set to TRUE, then enable noack mode even if the stub didn't
3560      report it in qSupported.  If the stub doesn't reply OK, the
3561      session ends with an error.
3562
3563      If FALSE, then don't activate noack mode, regardless of what the
3564      stub claimed should be the default with qSupported.  */
3565
3566   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
3567   if (packet_config_support (noack_config) != PACKET_DISABLE)
3568     {
3569       putpkt ("QStartNoAckMode");
3570       getpkt (&rs->buf, &rs->buf_size, 0);
3571       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
3572         rs->noack_mode = 1;
3573     }
3574
3575   if (extended_p)
3576     {
3577       /* Tell the remote that we are using the extended protocol.  */
3578       putpkt ("!");
3579       getpkt (&rs->buf, &rs->buf_size, 0);
3580     }
3581
3582   /* Let the target know which signals it is allowed to pass down to
3583      the program.  */
3584   update_signals_program_target ();
3585
3586   /* Next, if the target can specify a description, read it.  We do
3587      this before anything involving memory or registers.  */
3588   target_find_description ();
3589
3590   /* Next, now that we know something about the target, update the
3591      address spaces in the program spaces.  */
3592   update_address_spaces ();
3593
3594   /* On OSs where the list of libraries is global to all
3595      processes, we fetch them early.  */
3596   if (gdbarch_has_global_solist (target_gdbarch ()))
3597     solib_add (NULL, from_tty, target, auto_solib_add);
3598
3599   if (non_stop)
3600     {
3601       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
3602         error (_("Non-stop mode requested, but remote "
3603                  "does not support non-stop"));
3604
3605       putpkt ("QNonStop:1");
3606       getpkt (&rs->buf, &rs->buf_size, 0);
3607
3608       if (strcmp (rs->buf, "OK") != 0)
3609         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
3610
3611       /* Find about threads and processes the stub is already
3612          controlling.  We default to adding them in the running state.
3613          The '?' query below will then tell us about which threads are
3614          stopped.  */
3615       remote_update_thread_list (target);
3616     }
3617   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
3618     {
3619       /* Don't assume that the stub can operate in all-stop mode.
3620          Request it explicitly.  */
3621       putpkt ("QNonStop:0");
3622       getpkt (&rs->buf, &rs->buf_size, 0);
3623
3624       if (strcmp (rs->buf, "OK") != 0)
3625         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
3626     }
3627
3628   /* Upload TSVs regardless of whether the target is running or not.  The
3629      remote stub, such as GDBserver, may have some predefined or builtin
3630      TSVs, even if the target is not running.  */
3631   if (remote_get_trace_status (target, current_trace_status ()) != -1)
3632     {
3633       struct uploaded_tsv *uploaded_tsvs = NULL;
3634
3635       remote_upload_trace_state_variables (target, &uploaded_tsvs);
3636       merge_uploaded_trace_state_variables (&uploaded_tsvs);
3637     }
3638
3639   /* Check whether the target is running now.  */
3640   putpkt ("?");
3641   getpkt (&rs->buf, &rs->buf_size, 0);
3642
3643   if (!non_stop)
3644     {
3645       ptid_t ptid;
3646       int fake_pid_p = 0;
3647       struct inferior *inf;
3648
3649       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
3650         {
3651           if (!extended_p)
3652             error (_("The target is not running (try extended-remote?)"));
3653
3654           /* We're connected, but not running.  Drop out before we
3655              call start_remote.  */
3656           rs->starting_up = 0;
3657           return;
3658         }
3659       else
3660         {
3661           /* Save the reply for later.  */
3662           wait_status = alloca (strlen (rs->buf) + 1);
3663           strcpy (wait_status, rs->buf);
3664         }
3665
3666       /* Fetch thread list.  */
3667       target_update_thread_list ();
3668
3669       /* Let the stub know that we want it to return the thread.  */
3670       set_continue_thread (minus_one_ptid);
3671
3672       if (thread_count () == 0)
3673         {
3674           /* Target has no concept of threads at all.  GDB treats
3675              non-threaded target as single-threaded; add a main
3676              thread.  */
3677           add_current_inferior_and_thread (wait_status);
3678         }
3679       else
3680         {
3681           /* We have thread information; select the thread the target
3682              says should be current.  If we're reconnecting to a
3683              multi-threaded program, this will ideally be the thread
3684              that last reported an event before GDB disconnected.  */
3685           inferior_ptid = get_current_thread (wait_status);
3686           if (ptid_equal (inferior_ptid, null_ptid))
3687             {
3688               /* Odd... The target was able to list threads, but not
3689                  tell us which thread was current (no "thread"
3690                  register in T stop reply?).  Just pick the first
3691                  thread in the thread list then.  */
3692               inferior_ptid = thread_list->ptid;
3693             }
3694         }
3695
3696       /* init_wait_for_inferior should be called before get_offsets in order
3697          to manage `inserted' flag in bp loc in a correct state.
3698          breakpoint_init_inferior, called from init_wait_for_inferior, set
3699          `inserted' flag to 0, while before breakpoint_re_set, called from
3700          start_remote, set `inserted' flag to 1.  In the initialization of
3701          inferior, breakpoint_init_inferior should be called first, and then
3702          breakpoint_re_set can be called.  If this order is broken, state of
3703          `inserted' flag is wrong, and cause some problems on breakpoint
3704          manipulation.  */
3705       init_wait_for_inferior ();
3706
3707       get_offsets ();           /* Get text, data & bss offsets.  */
3708
3709       /* If we could not find a description using qXfer, and we know
3710          how to do it some other way, try again.  This is not
3711          supported for non-stop; it could be, but it is tricky if
3712          there are no stopped threads when we connect.  */
3713       if (remote_read_description_p (target)
3714           && gdbarch_target_desc (target_gdbarch ()) == NULL)
3715         {
3716           target_clear_description ();
3717           target_find_description ();
3718         }
3719
3720       /* Use the previously fetched status.  */
3721       gdb_assert (wait_status != NULL);
3722       strcpy (rs->buf, wait_status);
3723       rs->cached_wait_status = 1;
3724
3725       immediate_quit--;
3726       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
3727     }
3728   else
3729     {
3730       /* Clear WFI global state.  Do this before finding about new
3731          threads and inferiors, and setting the current inferior.
3732          Otherwise we would clear the proceed status of the current
3733          inferior when we want its stop_soon state to be preserved
3734          (see notice_new_inferior).  */
3735       init_wait_for_inferior ();
3736
3737       /* In non-stop, we will either get an "OK", meaning that there
3738          are no stopped threads at this time; or, a regular stop
3739          reply.  In the latter case, there may be more than one thread
3740          stopped --- we pull them all out using the vStopped
3741          mechanism.  */
3742       if (strcmp (rs->buf, "OK") != 0)
3743         {
3744           struct notif_client *notif = &notif_client_stop;
3745
3746           /* remote_notif_get_pending_replies acks this one, and gets
3747              the rest out.  */
3748           rs->notif_state->pending_event[notif_client_stop.id]
3749             = remote_notif_parse (notif, rs->buf);
3750           remote_notif_get_pending_events (notif);
3751
3752           /* Make sure that threads that were stopped remain
3753              stopped.  */
3754           iterate_over_threads (set_stop_requested_callback, NULL);
3755         }
3756
3757       if (target_can_async_p ())
3758         target_async (1);
3759
3760       if (thread_count () == 0)
3761         {
3762           if (!extended_p)
3763             error (_("The target is not running (try extended-remote?)"));
3764
3765           /* We're connected, but not running.  Drop out before we
3766              call start_remote.  */
3767           rs->starting_up = 0;
3768           return;
3769         }
3770
3771       /* Let the stub know that we want it to return the thread.  */
3772
3773       /* Force the stub to choose a thread.  */
3774       set_general_thread (null_ptid);
3775
3776       /* Query it.  */
3777       inferior_ptid = remote_current_thread (minus_one_ptid);
3778       if (ptid_equal (inferior_ptid, minus_one_ptid))
3779         error (_("remote didn't report the current thread in non-stop mode"));
3780
3781       get_offsets ();           /* Get text, data & bss offsets.  */
3782
3783       /* In non-stop mode, any cached wait status will be stored in
3784          the stop reply queue.  */
3785       gdb_assert (wait_status == NULL);
3786
3787       /* Report all signals during attach/startup.  */
3788       remote_pass_signals (target, 0, NULL);
3789     }
3790
3791   /* If we connected to a live target, do some additional setup.  */
3792   if (target_has_execution)
3793     {
3794       if (symfile_objfile)      /* No use without a symbol-file.  */
3795         remote_check_symbols ();
3796     }
3797
3798   /* Possibly the target has been engaged in a trace run started
3799      previously; find out where things are at.  */
3800   if (remote_get_trace_status (target, current_trace_status ()) != -1)
3801     {
3802       struct uploaded_tp *uploaded_tps = NULL;
3803
3804       if (current_trace_status ()->running)
3805         printf_filtered (_("Trace is already running on the target.\n"));
3806
3807       remote_upload_tracepoints (target, &uploaded_tps);
3808
3809       merge_uploaded_tracepoints (&uploaded_tps);
3810     }
3811
3812   /* The thread and inferior lists are now synchronized with the
3813      target, our symbols have been relocated, and we're merged the
3814      target's tracepoints with ours.  We're done with basic start
3815      up.  */
3816   rs->starting_up = 0;
3817
3818   /* Maybe breakpoints are global and need to be inserted now.  */
3819   if (breakpoints_should_be_inserted_now ())
3820     insert_breakpoints ();
3821 }
3822
3823 /* Open a connection to a remote debugger.
3824    NAME is the filename used for communication.  */
3825
3826 static void
3827 remote_open (const char *name, int from_tty)
3828 {
3829   remote_open_1 (name, from_tty, &remote_ops, 0);
3830 }
3831
3832 /* Open a connection to a remote debugger using the extended
3833    remote gdb protocol.  NAME is the filename used for communication.  */
3834
3835 static void
3836 extended_remote_open (const char *name, int from_tty)
3837 {
3838   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
3839 }
3840
3841 /* Reset all packets back to "unknown support".  Called when opening a
3842    new connection to a remote target.  */
3843
3844 static void
3845 reset_all_packet_configs_support (void)
3846 {
3847   int i;
3848
3849   for (i = 0; i < PACKET_MAX; i++)
3850     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3851 }
3852
3853 /* Initialize all packet configs.  */
3854
3855 static void
3856 init_all_packet_configs (void)
3857 {
3858   int i;
3859
3860   for (i = 0; i < PACKET_MAX; i++)
3861     {
3862       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
3863       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
3864     }
3865 }
3866
3867 /* Symbol look-up.  */
3868
3869 static void
3870 remote_check_symbols (void)
3871 {
3872   struct remote_state *rs = get_remote_state ();
3873   char *msg, *reply, *tmp;
3874   struct bound_minimal_symbol sym;
3875   int end;
3876
3877   /* The remote side has no concept of inferiors that aren't running
3878      yet, it only knows about running processes.  If we're connected
3879      but our current inferior is not running, we should not invite the
3880      remote target to request symbol lookups related to its
3881      (unrelated) current process.  */
3882   if (!target_has_execution)
3883     return;
3884
3885   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
3886     return;
3887
3888   /* Make sure the remote is pointing at the right process.  Note
3889      there's no way to select "no process".  */
3890   set_general_process ();
3891
3892   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
3893      because we need both at the same time.  */
3894   msg = alloca (get_remote_packet_size ());
3895
3896   /* Invite target to request symbol lookups.  */
3897
3898   putpkt ("qSymbol::");
3899   getpkt (&rs->buf, &rs->buf_size, 0);
3900   packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSymbol]);
3901   reply = rs->buf;
3902
3903   while (startswith (reply, "qSymbol:"))
3904     {
3905       struct bound_minimal_symbol sym;
3906
3907       tmp = &reply[8];
3908       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
3909       msg[end] = '\0';
3910       sym = lookup_minimal_symbol (msg, NULL, NULL);
3911       if (sym.minsym == NULL)
3912         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
3913       else
3914         {
3915           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
3916           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
3917
3918           /* If this is a function address, return the start of code
3919              instead of any data function descriptor.  */
3920           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
3921                                                          sym_addr,
3922                                                          &current_target);
3923
3924           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
3925                      phex_nz (sym_addr, addr_size), &reply[8]);
3926         }
3927   
3928       putpkt (msg);
3929       getpkt (&rs->buf, &rs->buf_size, 0);
3930       reply = rs->buf;
3931     }
3932 }
3933
3934 static struct serial *
3935 remote_serial_open (const char *name)
3936 {
3937   static int udp_warning = 0;
3938
3939   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
3940      of in ser-tcp.c, because it is the remote protocol assuming that the
3941      serial connection is reliable and not the serial connection promising
3942      to be.  */
3943   if (!udp_warning && startswith (name, "udp:"))
3944     {
3945       warning (_("The remote protocol may be unreliable over UDP.\n"
3946                  "Some events may be lost, rendering further debugging "
3947                  "impossible."));
3948       udp_warning = 1;
3949     }
3950
3951   return serial_open (name);
3952 }
3953
3954 /* Inform the target of our permission settings.  The permission flags
3955    work without this, but if the target knows the settings, it can do
3956    a couple things.  First, it can add its own check, to catch cases
3957    that somehow manage to get by the permissions checks in target
3958    methods.  Second, if the target is wired to disallow particular
3959    settings (for instance, a system in the field that is not set up to
3960    be able to stop at a breakpoint), it can object to any unavailable
3961    permissions.  */
3962
3963 void
3964 remote_set_permissions (struct target_ops *self)
3965 {
3966   struct remote_state *rs = get_remote_state ();
3967
3968   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
3969              "WriteReg:%x;WriteMem:%x;"
3970              "InsertBreak:%x;InsertTrace:%x;"
3971              "InsertFastTrace:%x;Stop:%x",
3972              may_write_registers, may_write_memory,
3973              may_insert_breakpoints, may_insert_tracepoints,
3974              may_insert_fast_tracepoints, may_stop);
3975   putpkt (rs->buf);
3976   getpkt (&rs->buf, &rs->buf_size, 0);
3977
3978   /* If the target didn't like the packet, warn the user.  Do not try
3979      to undo the user's settings, that would just be maddening.  */
3980   if (strcmp (rs->buf, "OK") != 0)
3981     warning (_("Remote refused setting permissions with: %s"), rs->buf);
3982 }
3983
3984 /* This type describes each known response to the qSupported
3985    packet.  */
3986 struct protocol_feature
3987 {
3988   /* The name of this protocol feature.  */
3989   const char *name;
3990
3991   /* The default for this protocol feature.  */
3992   enum packet_support default_support;
3993
3994   /* The function to call when this feature is reported, or after
3995      qSupported processing if the feature is not supported.
3996      The first argument points to this structure.  The second
3997      argument indicates whether the packet requested support be
3998      enabled, disabled, or probed (or the default, if this function
3999      is being called at the end of processing and this feature was
4000      not reported).  The third argument may be NULL; if not NULL, it
4001      is a NUL-terminated string taken from the packet following
4002      this feature's name and an equals sign.  */
4003   void (*func) (const struct protocol_feature *, enum packet_support,
4004                 const char *);
4005
4006   /* The corresponding packet for this feature.  Only used if
4007      FUNC is remote_supported_packet.  */
4008   int packet;
4009 };
4010
4011 static void
4012 remote_supported_packet (const struct protocol_feature *feature,
4013                          enum packet_support support,
4014                          const char *argument)
4015 {
4016   if (argument)
4017     {
4018       warning (_("Remote qSupported response supplied an unexpected value for"
4019                  " \"%s\"."), feature->name);
4020       return;
4021     }
4022
4023   remote_protocol_packets[feature->packet].support = support;
4024 }
4025
4026 static void
4027 remote_packet_size (const struct protocol_feature *feature,
4028                     enum packet_support support, const char *value)
4029 {
4030   struct remote_state *rs = get_remote_state ();
4031
4032   int packet_size;
4033   char *value_end;
4034
4035   if (support != PACKET_ENABLE)
4036     return;
4037
4038   if (value == NULL || *value == '\0')
4039     {
4040       warning (_("Remote target reported \"%s\" without a size."),
4041                feature->name);
4042       return;
4043     }
4044
4045   errno = 0;
4046   packet_size = strtol (value, &value_end, 16);
4047   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4048     {
4049       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4050                feature->name, value);
4051       return;
4052     }
4053
4054   if (packet_size > MAX_REMOTE_PACKET_SIZE)
4055     {
4056       warning (_("limiting remote suggested packet size (%d bytes) to %d"),
4057                packet_size, MAX_REMOTE_PACKET_SIZE);
4058       packet_size = MAX_REMOTE_PACKET_SIZE;
4059     }
4060
4061   /* Record the new maximum packet size.  */
4062   rs->explicit_packet_size = packet_size;
4063 }
4064
4065 static const struct protocol_feature remote_protocol_features[] = {
4066   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4067   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4068     PACKET_qXfer_auxv },
4069   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4070     PACKET_qXfer_exec_file },
4071   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4072     PACKET_qXfer_features },
4073   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4074     PACKET_qXfer_libraries },
4075   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4076     PACKET_qXfer_libraries_svr4 },
4077   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4078     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4079   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4080     PACKET_qXfer_memory_map },
4081   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4082     PACKET_qXfer_spu_read },
4083   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4084     PACKET_qXfer_spu_write },
4085   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4086     PACKET_qXfer_osdata },
4087   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4088     PACKET_qXfer_threads },
4089   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4090     PACKET_qXfer_traceframe_info },
4091   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4092     PACKET_QPassSignals },
4093   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4094     PACKET_QProgramSignals },
4095   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4096     PACKET_QStartNoAckMode },
4097   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4098     PACKET_multiprocess_feature },
4099   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4100   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4101     PACKET_qXfer_siginfo_read },
4102   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4103     PACKET_qXfer_siginfo_write },
4104   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4105     PACKET_ConditionalTracepoints },
4106   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4107     PACKET_ConditionalBreakpoints },
4108   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4109     PACKET_BreakpointCommands },
4110   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4111     PACKET_FastTracepoints },
4112   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4113     PACKET_StaticTracepoints },
4114   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4115    PACKET_InstallInTrace},
4116   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4117     PACKET_DisconnectedTracing_feature },
4118   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4119     PACKET_bc },
4120   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4121     PACKET_bs },
4122   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4123     PACKET_TracepointSource },
4124   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4125     PACKET_QAllow },
4126   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4127     PACKET_EnableDisableTracepoints_feature },
4128   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4129     PACKET_qXfer_fdpic },
4130   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4131     PACKET_qXfer_uib },
4132   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4133     PACKET_QDisableRandomization },
4134   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4135   { "QTBuffer:size", PACKET_DISABLE,
4136     remote_supported_packet, PACKET_QTBuffer_size},
4137   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4138   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4139   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4140   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4141     PACKET_qXfer_btrace },
4142   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4143     PACKET_qXfer_btrace_conf },
4144   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4145     PACKET_Qbtrace_conf_bts_size },
4146   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4147   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4148   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4149     PACKET_fork_event_feature },
4150   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4151     PACKET_vfork_event_feature },
4152 };
4153
4154 static char *remote_support_xml;
4155
4156 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4157
4158 void
4159 register_remote_support_xml (const char *xml)
4160 {
4161 #if defined(HAVE_LIBEXPAT)
4162   if (remote_support_xml == NULL)
4163     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4164   else
4165     {
4166       char *copy = xstrdup (remote_support_xml + 13);
4167       char *p = strtok (copy, ",");
4168
4169       do
4170         {
4171           if (strcmp (p, xml) == 0)
4172             {
4173               /* already there */
4174               xfree (copy);
4175               return;
4176             }
4177         }
4178       while ((p = strtok (NULL, ",")) != NULL);
4179       xfree (copy);
4180
4181       remote_support_xml = reconcat (remote_support_xml,
4182                                      remote_support_xml, ",", xml,
4183                                      (char *) NULL);
4184     }
4185 #endif
4186 }
4187
4188 static char *
4189 remote_query_supported_append (char *msg, const char *append)
4190 {
4191   if (msg)
4192     return reconcat (msg, msg, ";", append, (char *) NULL);
4193   else
4194     return xstrdup (append);
4195 }
4196
4197 static void
4198 remote_query_supported (void)
4199 {
4200   struct remote_state *rs = get_remote_state ();
4201   char *next;
4202   int i;
4203   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4204
4205   /* The packet support flags are handled differently for this packet
4206      than for most others.  We treat an error, a disabled packet, and
4207      an empty response identically: any features which must be reported
4208      to be used will be automatically disabled.  An empty buffer
4209      accomplishes this, since that is also the representation for a list
4210      containing no features.  */
4211
4212   rs->buf[0] = 0;
4213   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4214     {
4215       char *q = NULL;
4216       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4217
4218       q = remote_query_supported_append (q, "multiprocess+");
4219
4220       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4221         q = remote_query_supported_append (q, "swbreak+");
4222       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4223         q = remote_query_supported_append (q, "hwbreak+");
4224
4225       if (remote_support_xml)
4226         q = remote_query_supported_append (q, remote_support_xml);
4227
4228       q = remote_query_supported_append (q, "qRelocInsn+");
4229
4230       if (rs->extended)
4231         {
4232           if (packet_set_cmd_state (PACKET_fork_event_feature)
4233               != AUTO_BOOLEAN_FALSE)
4234             q = remote_query_supported_append (q, "fork-events+");
4235           if (packet_set_cmd_state (PACKET_vfork_event_feature)
4236               != AUTO_BOOLEAN_FALSE)
4237             q = remote_query_supported_append (q, "vfork-events+");
4238         }
4239
4240       q = reconcat (q, "qSupported:", q, (char *) NULL);
4241       putpkt (q);
4242
4243       do_cleanups (old_chain);
4244
4245       getpkt (&rs->buf, &rs->buf_size, 0);
4246
4247       /* If an error occured, warn, but do not return - just reset the
4248          buffer to empty and go on to disable features.  */
4249       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4250           == PACKET_ERROR)
4251         {
4252           warning (_("Remote failure reply: %s"), rs->buf);
4253           rs->buf[0] = 0;
4254         }
4255     }
4256
4257   memset (seen, 0, sizeof (seen));
4258
4259   next = rs->buf;
4260   while (*next)
4261     {
4262       enum packet_support is_supported;
4263       char *p, *end, *name_end, *value;
4264
4265       /* First separate out this item from the rest of the packet.  If
4266          there's another item after this, we overwrite the separator
4267          (terminated strings are much easier to work with).  */
4268       p = next;
4269       end = strchr (p, ';');
4270       if (end == NULL)
4271         {
4272           end = p + strlen (p);
4273           next = end;
4274         }
4275       else
4276         {
4277           *end = '\0';
4278           next = end + 1;
4279
4280           if (end == p)
4281             {
4282               warning (_("empty item in \"qSupported\" response"));
4283               continue;
4284             }
4285         }
4286
4287       name_end = strchr (p, '=');
4288       if (name_end)
4289         {
4290           /* This is a name=value entry.  */
4291           is_supported = PACKET_ENABLE;
4292           value = name_end + 1;
4293           *name_end = '\0';
4294         }
4295       else
4296         {
4297           value = NULL;
4298           switch (end[-1])
4299             {
4300             case '+':
4301               is_supported = PACKET_ENABLE;
4302               break;
4303
4304             case '-':
4305               is_supported = PACKET_DISABLE;
4306               break;
4307
4308             case '?':
4309               is_supported = PACKET_SUPPORT_UNKNOWN;
4310               break;
4311
4312             default:
4313               warning (_("unrecognized item \"%s\" "
4314                          "in \"qSupported\" response"), p);
4315               continue;
4316             }
4317           end[-1] = '\0';
4318         }
4319
4320       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4321         if (strcmp (remote_protocol_features[i].name, p) == 0)
4322           {
4323             const struct protocol_feature *feature;
4324
4325             seen[i] = 1;
4326             feature = &remote_protocol_features[i];
4327             feature->func (feature, is_supported, value);
4328             break;
4329           }
4330     }
4331
4332   /* If we increased the packet size, make sure to increase the global
4333      buffer size also.  We delay this until after parsing the entire
4334      qSupported packet, because this is the same buffer we were
4335      parsing.  */
4336   if (rs->buf_size < rs->explicit_packet_size)
4337     {
4338       rs->buf_size = rs->explicit_packet_size;
4339       rs->buf = xrealloc (rs->buf, rs->buf_size);
4340     }
4341
4342   /* Handle the defaults for unmentioned features.  */
4343   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4344     if (!seen[i])
4345       {
4346         const struct protocol_feature *feature;
4347
4348         feature = &remote_protocol_features[i];
4349         feature->func (feature, feature->default_support, NULL);
4350       }
4351 }
4352
4353 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4354    on it so remove them first.  */
4355
4356 static void
4357 remote_unpush_target (void)
4358 {
4359   pop_all_targets_above (process_stratum - 1);
4360 }
4361
4362 static void
4363 remote_open_1 (const char *name, int from_tty,
4364                struct target_ops *target, int extended_p)
4365 {
4366   struct remote_state *rs = get_remote_state ();
4367
4368   if (name == 0)
4369     error (_("To open a remote debug connection, you need to specify what\n"
4370            "serial device is attached to the remote system\n"
4371            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4372
4373   /* See FIXME above.  */
4374   if (!target_async_permitted)
4375     wait_forever_enabled_p = 1;
4376
4377   /* If we're connected to a running target, target_preopen will kill it.
4378      Ask this question first, before target_preopen has a chance to kill
4379      anything.  */
4380   if (rs->remote_desc != NULL && !have_inferiors ())
4381     {
4382       if (from_tty
4383           && !query (_("Already connected to a remote target.  Disconnect? ")))
4384         error (_("Still connected."));
4385     }
4386
4387   /* Here the possibly existing remote target gets unpushed.  */
4388   target_preopen (from_tty);
4389
4390   /* Make sure we send the passed signals list the next time we resume.  */
4391   xfree (rs->last_pass_packet);
4392   rs->last_pass_packet = NULL;
4393
4394   /* Make sure we send the program signals list the next time we
4395      resume.  */
4396   xfree (rs->last_program_signals_packet);
4397   rs->last_program_signals_packet = NULL;
4398
4399   remote_fileio_reset ();
4400   reopen_exec_file ();
4401   reread_symbols ();
4402
4403   rs->remote_desc = remote_serial_open (name);
4404   if (!rs->remote_desc)
4405     perror_with_name (name);
4406
4407   if (baud_rate != -1)
4408     {
4409       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4410         {
4411           /* The requested speed could not be set.  Error out to
4412              top level after closing remote_desc.  Take care to
4413              set remote_desc to NULL to avoid closing remote_desc
4414              more than once.  */
4415           serial_close (rs->remote_desc);
4416           rs->remote_desc = NULL;
4417           perror_with_name (name);
4418         }
4419     }
4420
4421   serial_setparity (rs->remote_desc, serial_parity);
4422   serial_raw (rs->remote_desc);
4423
4424   /* If there is something sitting in the buffer we might take it as a
4425      response to a command, which would be bad.  */
4426   serial_flush_input (rs->remote_desc);
4427
4428   if (from_tty)
4429     {
4430       puts_filtered ("Remote debugging using ");
4431       puts_filtered (name);
4432       puts_filtered ("\n");
4433     }
4434   push_target (target);         /* Switch to using remote target now.  */
4435
4436   /* Register extra event sources in the event loop.  */
4437   remote_async_inferior_event_token
4438     = create_async_event_handler (remote_async_inferior_event_handler,
4439                                   NULL);
4440   rs->notif_state = remote_notif_state_allocate ();
4441
4442   /* Reset the target state; these things will be queried either by
4443      remote_query_supported or as they are needed.  */
4444   reset_all_packet_configs_support ();
4445   rs->cached_wait_status = 0;
4446   rs->explicit_packet_size = 0;
4447   rs->noack_mode = 0;
4448   rs->extended = extended_p;
4449   rs->waiting_for_stop_reply = 0;
4450   rs->ctrlc_pending_p = 0;
4451
4452   rs->general_thread = not_sent_ptid;
4453   rs->continue_thread = not_sent_ptid;
4454   rs->remote_traceframe_number = -1;
4455
4456   /* Probe for ability to use "ThreadInfo" query, as required.  */
4457   rs->use_threadinfo_query = 1;
4458   rs->use_threadextra_query = 1;
4459
4460   if (target_async_permitted)
4461     {
4462       /* With this target we start out by owning the terminal.  */
4463       remote_async_terminal_ours_p = 1;
4464
4465       /* FIXME: cagney/1999-09-23: During the initial connection it is
4466          assumed that the target is already ready and able to respond to
4467          requests.  Unfortunately remote_start_remote() eventually calls
4468          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
4469          around this.  Eventually a mechanism that allows
4470          wait_for_inferior() to expect/get timeouts will be
4471          implemented.  */
4472       wait_forever_enabled_p = 0;
4473     }
4474
4475   /* First delete any symbols previously loaded from shared libraries.  */
4476   no_shared_libraries (NULL, 0);
4477
4478   /* Start afresh.  */
4479   init_thread_list ();
4480
4481   /* Start the remote connection.  If error() or QUIT, discard this
4482      target (we'd otherwise be in an inconsistent state) and then
4483      propogate the error on up the exception chain.  This ensures that
4484      the caller doesn't stumble along blindly assuming that the
4485      function succeeded.  The CLI doesn't have this problem but other
4486      UI's, such as MI do.
4487
4488      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
4489      this function should return an error indication letting the
4490      caller restore the previous state.  Unfortunately the command
4491      ``target remote'' is directly wired to this function making that
4492      impossible.  On a positive note, the CLI side of this problem has
4493      been fixed - the function set_cmd_context() makes it possible for
4494      all the ``target ....'' commands to share a common callback
4495      function.  See cli-dump.c.  */
4496   {
4497
4498     TRY
4499       {
4500         remote_start_remote (from_tty, target, extended_p);
4501       }
4502     CATCH (ex, RETURN_MASK_ALL)
4503       {
4504         /* Pop the partially set up target - unless something else did
4505            already before throwing the exception.  */
4506         if (rs->remote_desc != NULL)
4507           remote_unpush_target ();
4508         if (target_async_permitted)
4509           wait_forever_enabled_p = 1;
4510         throw_exception (ex);
4511       }
4512     END_CATCH
4513   }
4514
4515   remote_btrace_reset ();
4516
4517   if (target_async_permitted)
4518     wait_forever_enabled_p = 1;
4519 }
4520
4521 /* Detach the specified process.  */
4522
4523 static void
4524 remote_detach_pid (int pid)
4525 {
4526   struct remote_state *rs = get_remote_state ();
4527
4528   if (remote_multi_process_p (rs))
4529     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
4530   else
4531     strcpy (rs->buf, "D");
4532
4533   putpkt (rs->buf);
4534   getpkt (&rs->buf, &rs->buf_size, 0);
4535
4536   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
4537     ;
4538   else if (rs->buf[0] == '\0')
4539     error (_("Remote doesn't know how to detach"));
4540   else
4541     error (_("Can't detach process."));
4542 }
4543
4544 /* This detaches a program to which we previously attached, using
4545    inferior_ptid to identify the process.  After this is done, GDB
4546    can be used to debug some other program.  We better not have left
4547    any breakpoints in the target program or it'll die when it hits
4548    one.  */
4549
4550 static void
4551 remote_detach_1 (const char *args, int from_tty)
4552 {
4553   int pid = ptid_get_pid (inferior_ptid);
4554   struct remote_state *rs = get_remote_state ();
4555   struct thread_info *tp = find_thread_ptid (inferior_ptid);
4556   int is_fork_parent;
4557
4558   if (args)
4559     error (_("Argument given to \"detach\" when remotely debugging."));
4560
4561   if (!target_has_execution)
4562     error (_("No process to detach from."));
4563
4564   if (from_tty)
4565     {
4566       char *exec_file = get_exec_file (0);
4567       if (exec_file == NULL)
4568         exec_file = "";
4569       printf_unfiltered (_("Detaching from program: %s, %s\n"), exec_file,
4570                          target_pid_to_str (pid_to_ptid (pid)));
4571       gdb_flush (gdb_stdout);
4572     }
4573
4574   /* Tell the remote target to detach.  */
4575   remote_detach_pid (pid);
4576
4577   if (from_tty && !rs->extended)
4578     puts_filtered (_("Ending remote debugging.\n"));
4579
4580   /* Check to see if we are detaching a fork parent.  Note that if we
4581      are detaching a fork child, tp == NULL.  */
4582   is_fork_parent = (tp != NULL
4583                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
4584
4585   /* If doing detach-on-fork, we don't mourn, because that will delete
4586      breakpoints that should be available for the followed inferior.  */
4587   if (!is_fork_parent)
4588     target_mourn_inferior ();
4589   else
4590     {
4591       inferior_ptid = null_ptid;
4592       detach_inferior (pid);
4593     }
4594 }
4595
4596 static void
4597 remote_detach (struct target_ops *ops, const char *args, int from_tty)
4598 {
4599   remote_detach_1 (args, from_tty);
4600 }
4601
4602 static void
4603 extended_remote_detach (struct target_ops *ops, const char *args, int from_tty)
4604 {
4605   remote_detach_1 (args, from_tty);
4606 }
4607
4608 /* Target follow-fork function for remote targets.  On entry, and
4609    at return, the current inferior is the fork parent.
4610
4611    Note that although this is currently only used for extended-remote,
4612    it is named remote_follow_fork in anticipation of using it for the
4613    remote target as well.  */
4614
4615 static int
4616 remote_follow_fork (struct target_ops *ops, int follow_child,
4617                     int detach_fork)
4618 {
4619   struct remote_state *rs = get_remote_state ();
4620   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
4621
4622   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
4623       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
4624     {
4625       /* When following the parent and detaching the child, we detach
4626          the child here.  For the case of following the child and
4627          detaching the parent, the detach is done in the target-
4628          independent follow fork code in infrun.c.  We can't use
4629          target_detach when detaching an unfollowed child because
4630          the client side doesn't know anything about the child.  */
4631       if (detach_fork && !follow_child)
4632         {
4633           /* Detach the fork child.  */
4634           ptid_t child_ptid;
4635           pid_t child_pid;
4636
4637           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
4638           child_pid = ptid_get_pid (child_ptid);
4639
4640           remote_detach_pid (child_pid);
4641           detach_inferior (child_pid);
4642         }
4643     }
4644   return 0;
4645 }
4646
4647 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
4648
4649 static void
4650 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
4651 {
4652   if (args)
4653     error (_("Argument given to \"disconnect\" when remotely debugging."));
4654
4655   /* Make sure we unpush even the extended remote targets; mourn
4656      won't do it.  So call remote_mourn directly instead of
4657      target_mourn_inferior.  */
4658   remote_mourn (target);
4659
4660   if (from_tty)
4661     puts_filtered ("Ending remote debugging.\n");
4662 }
4663
4664 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
4665    be chatty about it.  */
4666
4667 static void
4668 extended_remote_attach (struct target_ops *target, const char *args,
4669                         int from_tty)
4670 {
4671   struct remote_state *rs = get_remote_state ();
4672   int pid;
4673   char *wait_status = NULL;
4674
4675   pid = parse_pid_to_attach (args);
4676
4677   /* Remote PID can be freely equal to getpid, do not check it here the same
4678      way as in other targets.  */
4679
4680   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
4681     error (_("This target does not support attaching to a process"));
4682
4683   if (from_tty)
4684     {
4685       char *exec_file = get_exec_file (0);
4686
4687       if (exec_file)
4688         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
4689                            target_pid_to_str (pid_to_ptid (pid)));
4690       else
4691         printf_unfiltered (_("Attaching to %s\n"),
4692                            target_pid_to_str (pid_to_ptid (pid)));
4693
4694       gdb_flush (gdb_stdout);
4695     }
4696
4697   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
4698   putpkt (rs->buf);
4699   getpkt (&rs->buf, &rs->buf_size, 0);
4700
4701   switch (packet_ok (rs->buf,
4702                      &remote_protocol_packets[PACKET_vAttach]))
4703     {
4704     case PACKET_OK:
4705       if (!non_stop)
4706         {
4707           /* Save the reply for later.  */
4708           wait_status = alloca (strlen (rs->buf) + 1);
4709           strcpy (wait_status, rs->buf);
4710         }
4711       else if (strcmp (rs->buf, "OK") != 0)
4712         error (_("Attaching to %s failed with: %s"),
4713                target_pid_to_str (pid_to_ptid (pid)),
4714                rs->buf);
4715       break;
4716     case PACKET_UNKNOWN:
4717       error (_("This target does not support attaching to a process"));
4718     default:
4719       error (_("Attaching to %s failed"),
4720              target_pid_to_str (pid_to_ptid (pid)));
4721     }
4722
4723   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
4724
4725   inferior_ptid = pid_to_ptid (pid);
4726
4727   if (non_stop)
4728     {
4729       struct thread_info *thread;
4730
4731       /* Get list of threads.  */
4732       remote_update_thread_list (target);
4733
4734       thread = first_thread_of_process (pid);
4735       if (thread)
4736         inferior_ptid = thread->ptid;
4737       else
4738         inferior_ptid = pid_to_ptid (pid);
4739
4740       /* Invalidate our notion of the remote current thread.  */
4741       record_currthread (rs, minus_one_ptid);
4742     }
4743   else
4744     {
4745       /* Now, if we have thread information, update inferior_ptid.  */
4746       inferior_ptid = remote_current_thread (inferior_ptid);
4747
4748       /* Add the main thread to the thread list.  */
4749       add_thread_silent (inferior_ptid);
4750     }
4751
4752   /* Next, if the target can specify a description, read it.  We do
4753      this before anything involving memory or registers.  */
4754   target_find_description ();
4755
4756   if (!non_stop)
4757     {
4758       /* Use the previously fetched status.  */
4759       gdb_assert (wait_status != NULL);
4760
4761       if (target_can_async_p ())
4762         {
4763           struct notif_event *reply
4764             =  remote_notif_parse (&notif_client_stop, wait_status);
4765
4766           push_stop_reply ((struct stop_reply *) reply);
4767
4768           target_async (1);
4769         }
4770       else
4771         {
4772           gdb_assert (wait_status != NULL);
4773           strcpy (rs->buf, wait_status);
4774           rs->cached_wait_status = 1;
4775         }
4776     }
4777   else
4778     gdb_assert (wait_status == NULL);
4779 }
4780
4781 /* Implementation of the to_post_attach method.  */
4782
4783 static void
4784 extended_remote_post_attach (struct target_ops *ops, int pid)
4785 {
4786   /* In certain cases GDB might not have had the chance to start
4787      symbol lookup up until now.  This could happen if the debugged
4788      binary is not using shared libraries, the vsyscall page is not
4789      present (on Linux) and the binary itself hadn't changed since the
4790      debugging process was started.  */
4791   if (symfile_objfile != NULL)
4792     remote_check_symbols();
4793 }
4794
4795 \f
4796 /* Check for the availability of vCont.  This function should also check
4797    the response.  */
4798
4799 static void
4800 remote_vcont_probe (struct remote_state *rs)
4801 {
4802   char *buf;
4803
4804   strcpy (rs->buf, "vCont?");
4805   putpkt (rs->buf);
4806   getpkt (&rs->buf, &rs->buf_size, 0);
4807   buf = rs->buf;
4808
4809   /* Make sure that the features we assume are supported.  */
4810   if (startswith (buf, "vCont"))
4811     {
4812       char *p = &buf[5];
4813       int support_s, support_S, support_c, support_C;
4814
4815       support_s = 0;
4816       support_S = 0;
4817       support_c = 0;
4818       support_C = 0;
4819       rs->supports_vCont.t = 0;
4820       rs->supports_vCont.r = 0;
4821       while (p && *p == ';')
4822         {
4823           p++;
4824           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
4825             support_s = 1;
4826           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
4827             support_S = 1;
4828           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
4829             support_c = 1;
4830           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
4831             support_C = 1;
4832           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
4833             rs->supports_vCont.t = 1;
4834           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
4835             rs->supports_vCont.r = 1;
4836
4837           p = strchr (p, ';');
4838         }
4839
4840       /* If s, S, c, and C are not all supported, we can't use vCont.  Clearing
4841          BUF will make packet_ok disable the packet.  */
4842       if (!support_s || !support_S || !support_c || !support_C)
4843         buf[0] = 0;
4844     }
4845
4846   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
4847 }
4848
4849 /* Helper function for building "vCont" resumptions.  Write a
4850    resumption to P.  ENDP points to one-passed-the-end of the buffer
4851    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
4852    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
4853    resumed thread should be single-stepped and/or signalled.  If PTID
4854    equals minus_one_ptid, then all threads are resumed; if PTID
4855    represents a process, then all threads of the process are resumed;
4856    the thread to be stepped and/or signalled is given in the global
4857    INFERIOR_PTID.  */
4858
4859 static char *
4860 append_resumption (char *p, char *endp,
4861                    ptid_t ptid, int step, enum gdb_signal siggnal)
4862 {
4863   struct remote_state *rs = get_remote_state ();
4864
4865   if (step && siggnal != GDB_SIGNAL_0)
4866     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
4867   else if (step
4868            /* GDB is willing to range step.  */
4869            && use_range_stepping
4870            /* Target supports range stepping.  */
4871            && rs->supports_vCont.r
4872            /* We don't currently support range stepping multiple
4873               threads with a wildcard (though the protocol allows it,
4874               so stubs shouldn't make an active effort to forbid
4875               it).  */
4876            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
4877     {
4878       struct thread_info *tp;
4879
4880       if (ptid_equal (ptid, minus_one_ptid))
4881         {
4882           /* If we don't know about the target thread's tid, then
4883              we're resuming magic_null_ptid (see caller).  */
4884           tp = find_thread_ptid (magic_null_ptid);
4885         }
4886       else
4887         tp = find_thread_ptid (ptid);
4888       gdb_assert (tp != NULL);
4889
4890       if (tp->control.may_range_step)
4891         {
4892           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4893
4894           p += xsnprintf (p, endp - p, ";r%s,%s",
4895                           phex_nz (tp->control.step_range_start,
4896                                    addr_size),
4897                           phex_nz (tp->control.step_range_end,
4898                                    addr_size));
4899         }
4900       else
4901         p += xsnprintf (p, endp - p, ";s");
4902     }
4903   else if (step)
4904     p += xsnprintf (p, endp - p, ";s");
4905   else if (siggnal != GDB_SIGNAL_0)
4906     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
4907   else
4908     p += xsnprintf (p, endp - p, ";c");
4909
4910   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
4911     {
4912       ptid_t nptid;
4913
4914       /* All (-1) threads of process.  */
4915       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
4916
4917       p += xsnprintf (p, endp - p, ":");
4918       p = write_ptid (p, endp, nptid);
4919     }
4920   else if (!ptid_equal (ptid, minus_one_ptid))
4921     {
4922       p += xsnprintf (p, endp - p, ":");
4923       p = write_ptid (p, endp, ptid);
4924     }
4925
4926   return p;
4927 }
4928
4929 /* Append a vCont continue-with-signal action for threads that have a
4930    non-zero stop signal.  */
4931
4932 static char *
4933 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
4934 {
4935   struct thread_info *thread;
4936
4937   ALL_NON_EXITED_THREADS (thread)
4938     if (ptid_match (thread->ptid, ptid)
4939         && !ptid_equal (inferior_ptid, thread->ptid)
4940         && thread->suspend.stop_signal != GDB_SIGNAL_0)
4941       {
4942         p = append_resumption (p, endp, thread->ptid,
4943                                0, thread->suspend.stop_signal);
4944         thread->suspend.stop_signal = GDB_SIGNAL_0;
4945       }
4946
4947   return p;
4948 }
4949
4950 /* Resume the remote inferior by using a "vCont" packet.  The thread
4951    to be resumed is PTID; STEP and SIGGNAL indicate whether the
4952    resumed thread should be single-stepped and/or signalled.  If PTID
4953    equals minus_one_ptid, then all threads are resumed; the thread to
4954    be stepped and/or signalled is given in the global INFERIOR_PTID.
4955    This function returns non-zero iff it resumes the inferior.
4956
4957    This function issues a strict subset of all possible vCont commands at the
4958    moment.  */
4959
4960 static int
4961 remote_vcont_resume (ptid_t ptid, int step, enum gdb_signal siggnal)
4962 {
4963   struct remote_state *rs = get_remote_state ();
4964   char *p;
4965   char *endp;
4966
4967   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
4968     remote_vcont_probe (rs);
4969
4970   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
4971     return 0;
4972
4973   p = rs->buf;
4974   endp = rs->buf + get_remote_packet_size ();
4975
4976   /* If we could generate a wider range of packets, we'd have to worry
4977      about overflowing BUF.  Should there be a generic
4978      "multi-part-packet" packet?  */
4979
4980   p += xsnprintf (p, endp - p, "vCont");
4981
4982   if (ptid_equal (ptid, magic_null_ptid))
4983     {
4984       /* MAGIC_NULL_PTID means that we don't have any active threads,
4985          so we don't have any TID numbers the inferior will
4986          understand.  Make sure to only send forms that do not specify
4987          a TID.  */
4988       append_resumption (p, endp, minus_one_ptid, step, siggnal);
4989     }
4990   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
4991     {
4992       /* Resume all threads (of all processes, or of a single
4993          process), with preference for INFERIOR_PTID.  This assumes
4994          inferior_ptid belongs to the set of all threads we are about
4995          to resume.  */
4996       if (step || siggnal != GDB_SIGNAL_0)
4997         {
4998           /* Step inferior_ptid, with or without signal.  */
4999           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5000         }
5001
5002       /* Also pass down any pending signaled resumption for other
5003          threads not the current.  */
5004       p = append_pending_thread_resumptions (p, endp, ptid);
5005
5006       /* And continue others without a signal.  */
5007       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5008     }
5009   else
5010     {
5011       /* Scheduler locking; resume only PTID.  */
5012       append_resumption (p, endp, ptid, step, siggnal);
5013     }
5014
5015   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5016   putpkt (rs->buf);
5017
5018   if (non_stop)
5019     {
5020       /* In non-stop, the stub replies to vCont with "OK".  The stop
5021          reply will be reported asynchronously by means of a `%Stop'
5022          notification.  */
5023       getpkt (&rs->buf, &rs->buf_size, 0);
5024       if (strcmp (rs->buf, "OK") != 0)
5025         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5026     }
5027
5028   return 1;
5029 }
5030
5031 /* Tell the remote machine to resume.  */
5032
5033 static void
5034 remote_resume (struct target_ops *ops,
5035                ptid_t ptid, int step, enum gdb_signal siggnal)
5036 {
5037   struct remote_state *rs = get_remote_state ();
5038   char *buf;
5039
5040   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5041      (explained in remote-notif.c:handle_notification) so
5042      remote_notif_process is not called.  We need find a place where
5043      it is safe to start a 'vNotif' sequence.  It is good to do it
5044      before resuming inferior, because inferior was stopped and no RSP
5045      traffic at that moment.  */
5046   if (!non_stop)
5047     remote_notif_process (rs->notif_state, &notif_client_stop);
5048
5049   rs->last_sent_signal = siggnal;
5050   rs->last_sent_step = step;
5051
5052   /* The vCont packet doesn't need to specify threads via Hc.  */
5053   /* No reverse support (yet) for vCont.  */
5054   if (execution_direction != EXEC_REVERSE)
5055     if (remote_vcont_resume (ptid, step, siggnal))
5056       goto done;
5057
5058   /* All other supported resume packets do use Hc, so set the continue
5059      thread.  */
5060   if (ptid_equal (ptid, minus_one_ptid))
5061     set_continue_thread (any_thread_ptid);
5062   else
5063     set_continue_thread (ptid);
5064
5065   buf = rs->buf;
5066   if (execution_direction == EXEC_REVERSE)
5067     {
5068       /* We don't pass signals to the target in reverse exec mode.  */
5069       if (info_verbose && siggnal != GDB_SIGNAL_0)
5070         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5071                  siggnal);
5072
5073       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5074         error (_("Remote reverse-step not supported."));
5075       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5076         error (_("Remote reverse-continue not supported."));
5077
5078       strcpy (buf, step ? "bs" : "bc");
5079     }
5080   else if (siggnal != GDB_SIGNAL_0)
5081     {
5082       buf[0] = step ? 'S' : 'C';
5083       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5084       buf[2] = tohex (((int) siggnal) & 0xf);
5085       buf[3] = '\0';
5086     }
5087   else
5088     strcpy (buf, step ? "s" : "c");
5089
5090   putpkt (buf);
5091
5092  done:
5093   /* We are about to start executing the inferior, let's register it
5094      with the event loop.  NOTE: this is the one place where all the
5095      execution commands end up.  We could alternatively do this in each
5096      of the execution commands in infcmd.c.  */
5097   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5098      into infcmd.c in order to allow inferior function calls to work
5099      NOT asynchronously.  */
5100   if (target_can_async_p ())
5101     target_async (1);
5102
5103   /* We've just told the target to resume.  The remote server will
5104      wait for the inferior to stop, and then send a stop reply.  In
5105      the mean time, we can't start another command/query ourselves
5106      because the stub wouldn't be ready to process it.  This applies
5107      only to the base all-stop protocol, however.  In non-stop (which
5108      only supports vCont), the stub replies with an "OK", and is
5109      immediate able to process further serial input.  */
5110   if (!non_stop)
5111     rs->waiting_for_stop_reply = 1;
5112 }
5113 \f
5114
5115 /* Set up the signal handler for SIGINT, while the target is
5116    executing, ovewriting the 'regular' SIGINT signal handler.  */
5117 static void
5118 async_initialize_sigint_signal_handler (void)
5119 {
5120   signal (SIGINT, async_handle_remote_sigint);
5121 }
5122
5123 /* Signal handler for SIGINT, while the target is executing.  */
5124 static void
5125 async_handle_remote_sigint (int sig)
5126 {
5127   signal (sig, async_handle_remote_sigint_twice);
5128   /* Note we need to go through gdb_call_async_signal_handler in order
5129      to wake up the event loop on Windows.  */
5130   gdb_call_async_signal_handler (async_sigint_remote_token, 0);
5131 }
5132
5133 /* Signal handler for SIGINT, installed after SIGINT has already been
5134    sent once.  It will take effect the second time that the user sends
5135    a ^C.  */
5136 static void
5137 async_handle_remote_sigint_twice (int sig)
5138 {
5139   signal (sig, async_handle_remote_sigint);
5140   /* See note in async_handle_remote_sigint.  */
5141   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 0);
5142 }
5143
5144 /* Perform the real interruption of the target execution, in response
5145    to a ^C.  */
5146 static void
5147 async_remote_interrupt (gdb_client_data arg)
5148 {
5149   if (remote_debug)
5150     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt called\n");
5151
5152   target_stop (inferior_ptid);
5153 }
5154
5155 /* Perform interrupt, if the first attempt did not succeed.  Just give
5156    up on the target alltogether.  */
5157 static void
5158 async_remote_interrupt_twice (gdb_client_data arg)
5159 {
5160   if (remote_debug)
5161     fprintf_unfiltered (gdb_stdlog, "async_remote_interrupt_twice called\n");
5162
5163   interrupt_query ();
5164 }
5165
5166 /* Reinstall the usual SIGINT handlers, after the target has
5167    stopped.  */
5168 static void
5169 async_cleanup_sigint_signal_handler (void *dummy)
5170 {
5171   signal (SIGINT, handle_sigint);
5172 }
5173
5174 /* Send ^C to target to halt it.  Target will respond, and send us a
5175    packet.  */
5176 static void (*ofunc) (int);
5177
5178 /* The command line interface's stop routine.  This function is installed
5179    as a signal handler for SIGINT.  The first time a user requests a
5180    stop, we call remote_stop to send a break or ^C.  If there is no
5181    response from the target (it didn't stop when the user requested it),
5182    we ask the user if he'd like to detach from the target.  */
5183 static void
5184 sync_remote_interrupt (int signo)
5185 {
5186   /* If this doesn't work, try more severe steps.  */
5187   signal (signo, sync_remote_interrupt_twice);
5188
5189   gdb_call_async_signal_handler (async_sigint_remote_token, 1);
5190 }
5191
5192 /* The user typed ^C twice.  */
5193
5194 static void
5195 sync_remote_interrupt_twice (int signo)
5196 {
5197   signal (signo, ofunc);
5198   gdb_call_async_signal_handler (async_sigint_remote_twice_token, 1);
5199   signal (signo, sync_remote_interrupt);
5200 }
5201
5202 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
5203    thread, all threads of a remote process, or all threads of all
5204    processes.  */
5205
5206 static void
5207 remote_stop_ns (ptid_t ptid)
5208 {
5209   struct remote_state *rs = get_remote_state ();
5210   char *p = rs->buf;
5211   char *endp = rs->buf + get_remote_packet_size ();
5212
5213   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5214     remote_vcont_probe (rs);
5215
5216   if (!rs->supports_vCont.t)
5217     error (_("Remote server does not support stopping threads"));
5218
5219   if (ptid_equal (ptid, minus_one_ptid)
5220       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5221     p += xsnprintf (p, endp - p, "vCont;t");
5222   else
5223     {
5224       ptid_t nptid;
5225
5226       p += xsnprintf (p, endp - p, "vCont;t:");
5227
5228       if (ptid_is_pid (ptid))
5229           /* All (-1) threads of process.  */
5230         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5231       else
5232         {
5233           /* Small optimization: if we already have a stop reply for
5234              this thread, no use in telling the stub we want this
5235              stopped.  */
5236           if (peek_stop_reply (ptid))
5237             return;
5238
5239           nptid = ptid;
5240         }
5241
5242       write_ptid (p, endp, nptid);
5243     }
5244
5245   /* In non-stop, we get an immediate OK reply.  The stop reply will
5246      come in asynchronously by notification.  */
5247   putpkt (rs->buf);
5248   getpkt (&rs->buf, &rs->buf_size, 0);
5249   if (strcmp (rs->buf, "OK") != 0)
5250     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
5251 }
5252
5253 /* All-stop version of target_stop.  Sends a break or a ^C to stop the
5254    remote target.  It is undefined which thread of which process
5255    reports the stop.  */
5256
5257 static void
5258 remote_stop_as (ptid_t ptid)
5259 {
5260   struct remote_state *rs = get_remote_state ();
5261
5262   rs->ctrlc_pending_p = 1;
5263
5264   /* If the inferior is stopped already, but the core didn't know
5265      about it yet, just ignore the request.  The cached wait status
5266      will be collected in remote_wait.  */
5267   if (rs->cached_wait_status)
5268     return;
5269
5270   /* Send interrupt_sequence to remote target.  */
5271   send_interrupt_sequence ();
5272 }
5273
5274 /* This is the generic stop called via the target vector.  When a target
5275    interrupt is requested, either by the command line or the GUI, we
5276    will eventually end up here.  */
5277
5278 static void
5279 remote_stop (struct target_ops *self, ptid_t ptid)
5280 {
5281   if (remote_debug)
5282     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
5283
5284   if (non_stop)
5285     remote_stop_ns (ptid);
5286   else
5287     remote_stop_as (ptid);
5288 }
5289
5290 /* Ask the user what to do when an interrupt is received.  */
5291
5292 static void
5293 interrupt_query (void)
5294 {
5295   target_terminal_ours ();
5296
5297   if (target_is_async_p ())
5298     {
5299       signal (SIGINT, handle_sigint);
5300       quit ();
5301     }
5302   else
5303     {
5304       if (query (_("Interrupted while waiting for the program.\n\
5305 Give up (and stop debugging it)? ")))
5306         {
5307           remote_unpush_target ();
5308           quit ();
5309         }
5310     }
5311
5312   target_terminal_inferior ();
5313 }
5314
5315 /* Enable/disable target terminal ownership.  Most targets can use
5316    terminal groups to control terminal ownership.  Remote targets are
5317    different in that explicit transfer of ownership to/from GDB/target
5318    is required.  */
5319
5320 static void
5321 remote_terminal_inferior (struct target_ops *self)
5322 {
5323   if (!target_async_permitted)
5324     /* Nothing to do.  */
5325     return;
5326
5327   /* FIXME: cagney/1999-09-27: Make calls to target_terminal_*()
5328      idempotent.  The event-loop GDB talking to an asynchronous target
5329      with a synchronous command calls this function from both
5330      event-top.c and infrun.c/infcmd.c.  Once GDB stops trying to
5331      transfer the terminal to the target when it shouldn't this guard
5332      can go away.  */
5333   if (!remote_async_terminal_ours_p)
5334     return;
5335   delete_file_handler (input_fd);
5336   remote_async_terminal_ours_p = 0;
5337   async_initialize_sigint_signal_handler ();
5338   /* NOTE: At this point we could also register our selves as the
5339      recipient of all input.  Any characters typed could then be
5340      passed on down to the target.  */
5341 }
5342
5343 static void
5344 remote_terminal_ours (struct target_ops *self)
5345 {
5346   if (!target_async_permitted)
5347     /* Nothing to do.  */
5348     return;
5349
5350   /* See FIXME in remote_terminal_inferior.  */
5351   if (remote_async_terminal_ours_p)
5352     return;
5353   async_cleanup_sigint_signal_handler (NULL);
5354   add_file_handler (input_fd, stdin_event_handler, 0);
5355   remote_async_terminal_ours_p = 1;
5356 }
5357
5358 static void
5359 remote_console_output (char *msg)
5360 {
5361   char *p;
5362
5363   for (p = msg; p[0] && p[1]; p += 2)
5364     {
5365       char tb[2];
5366       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
5367
5368       tb[0] = c;
5369       tb[1] = 0;
5370       fputs_unfiltered (tb, gdb_stdtarg);
5371     }
5372   gdb_flush (gdb_stdtarg);
5373 }
5374
5375 typedef struct cached_reg
5376 {
5377   int num;
5378   gdb_byte data[MAX_REGISTER_SIZE];
5379 } cached_reg_t;
5380
5381 DEF_VEC_O(cached_reg_t);
5382
5383 typedef struct stop_reply
5384 {
5385   struct notif_event base;
5386
5387   /* The identifier of the thread about this event  */
5388   ptid_t ptid;
5389
5390   /* The remote state this event is associated with.  When the remote
5391      connection, represented by a remote_state object, is closed,
5392      all the associated stop_reply events should be released.  */
5393   struct remote_state *rs;
5394
5395   struct target_waitstatus ws;
5396
5397   /* Expedited registers.  This makes remote debugging a bit more
5398      efficient for those targets that provide critical registers as
5399      part of their normal status mechanism (as another roundtrip to
5400      fetch them is avoided).  */
5401   VEC(cached_reg_t) *regcache;
5402
5403   enum target_stop_reason stop_reason;
5404
5405   CORE_ADDR watch_data_address;
5406
5407   int core;
5408 } *stop_reply_p;
5409
5410 DECLARE_QUEUE_P (stop_reply_p);
5411 DEFINE_QUEUE_P (stop_reply_p);
5412 /* The list of already fetched and acknowledged stop events.  This
5413    queue is used for notification Stop, and other notifications
5414    don't need queue for their events, because the notification events
5415    of Stop can't be consumed immediately, so that events should be
5416    queued first, and be consumed by remote_wait_{ns,as} one per
5417    time.  Other notifications can consume their events immediately,
5418    so queue is not needed for them.  */
5419 static QUEUE (stop_reply_p) *stop_reply_queue;
5420
5421 static void
5422 stop_reply_xfree (struct stop_reply *r)
5423 {
5424   notif_event_xfree ((struct notif_event *) r);
5425 }
5426
5427 static void
5428 remote_notif_stop_parse (struct notif_client *self, char *buf,
5429                          struct notif_event *event)
5430 {
5431   remote_parse_stop_reply (buf, (struct stop_reply *) event);
5432 }
5433
5434 static void
5435 remote_notif_stop_ack (struct notif_client *self, char *buf,
5436                        struct notif_event *event)
5437 {
5438   struct stop_reply *stop_reply = (struct stop_reply *) event;
5439
5440   /* acknowledge */
5441   putpkt ((char *) self->ack_command);
5442
5443   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
5444       /* We got an unknown stop reply.  */
5445       error (_("Unknown stop reply"));
5446
5447   push_stop_reply (stop_reply);
5448 }
5449
5450 static int
5451 remote_notif_stop_can_get_pending_events (struct notif_client *self)
5452 {
5453   /* We can't get pending events in remote_notif_process for
5454      notification stop, and we have to do this in remote_wait_ns
5455      instead.  If we fetch all queued events from stub, remote stub
5456      may exit and we have no chance to process them back in
5457      remote_wait_ns.  */
5458   mark_async_event_handler (remote_async_inferior_event_token);
5459   return 0;
5460 }
5461
5462 static void
5463 stop_reply_dtr (struct notif_event *event)
5464 {
5465   struct stop_reply *r = (struct stop_reply *) event;
5466
5467   VEC_free (cached_reg_t, r->regcache);
5468 }
5469
5470 static struct notif_event *
5471 remote_notif_stop_alloc_reply (void)
5472 {
5473   struct notif_event *r
5474     = (struct notif_event *) XNEW (struct stop_reply);
5475
5476   r->dtr = stop_reply_dtr;
5477
5478   return r;
5479 }
5480
5481 /* A client of notification Stop.  */
5482
5483 struct notif_client notif_client_stop =
5484 {
5485   "Stop",
5486   "vStopped",
5487   remote_notif_stop_parse,
5488   remote_notif_stop_ack,
5489   remote_notif_stop_can_get_pending_events,
5490   remote_notif_stop_alloc_reply,
5491   REMOTE_NOTIF_STOP,
5492 };
5493
5494 /* A parameter to pass data in and out.  */
5495
5496 struct queue_iter_param
5497 {
5498   void *input;
5499   struct stop_reply *output;
5500 };
5501
5502 /* Determine if THREAD is a pending fork parent thread.  ARG contains
5503    the pid of the process that owns the threads we want to check, or
5504    -1 if we want to check all threads.  */
5505
5506 static int
5507 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
5508                         ptid_t thread_ptid)
5509 {
5510   if (ws->kind == TARGET_WAITKIND_FORKED
5511       || ws->kind == TARGET_WAITKIND_VFORKED)
5512     {
5513       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
5514         return 1;
5515     }
5516
5517   return 0;
5518 }
5519
5520 /* Check whether EVENT is a fork event, and if it is, remove the
5521    fork child from the context list passed in DATA.  */
5522
5523 static int
5524 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
5525                               QUEUE_ITER (stop_reply_p) *iter,
5526                               stop_reply_p event,
5527                               void *data)
5528 {
5529   struct queue_iter_param *param = data;
5530   struct threads_listing_context *context = param->input;
5531
5532   if (event->ws.kind == TARGET_WAITKIND_FORKED
5533       || event->ws.kind == TARGET_WAITKIND_VFORKED)
5534     {
5535       threads_listing_context_remove (&event->ws, context);
5536     }
5537
5538   return 1;
5539 }
5540
5541 /* If CONTEXT contains any fork child threads that have not been
5542    reported yet, remove them from the CONTEXT list.  If such a
5543    thread exists it is because we are stopped at a fork catchpoint
5544    and have not yet called follow_fork, which will set up the
5545    host-side data structures for the new process.  */
5546
5547 static void
5548 remove_new_fork_children (struct threads_listing_context *context)
5549 {
5550   struct thread_info * thread;
5551   int pid = -1;
5552   struct notif_client *notif = &notif_client_stop;
5553   struct queue_iter_param param;
5554
5555   /* For any threads stopped at a fork event, remove the corresponding
5556      fork child threads from the CONTEXT list.  */
5557   ALL_NON_EXITED_THREADS (thread)
5558     {
5559       struct target_waitstatus *ws = &thread->pending_follow;
5560
5561       if (is_pending_fork_parent (ws, pid, thread->ptid))
5562         {
5563           threads_listing_context_remove (ws, context);
5564         }
5565     }
5566
5567   /* Check for any pending fork events (not reported or processed yet)
5568      in process PID and remove those fork child threads from the
5569      CONTEXT list as well.  */
5570   remote_notif_get_pending_events (notif);
5571   param.input = context;
5572   param.output = NULL;
5573   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5574                  remove_child_of_pending_fork, &param);
5575 }
5576
5577 /* Remove stop replies in the queue if its pid is equal to the given
5578    inferior's pid.  */
5579
5580 static int
5581 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
5582                                 QUEUE_ITER (stop_reply_p) *iter,
5583                                 stop_reply_p event,
5584                                 void *data)
5585 {
5586   struct queue_iter_param *param = data;
5587   struct inferior *inf = param->input;
5588
5589   if (ptid_get_pid (event->ptid) == inf->pid)
5590     {
5591       stop_reply_xfree (event);
5592       QUEUE_remove_elem (stop_reply_p, q, iter);
5593     }
5594
5595   return 1;
5596 }
5597
5598 /* Discard all pending stop replies of inferior INF.  */
5599
5600 static void
5601 discard_pending_stop_replies (struct inferior *inf)
5602 {
5603   int i;
5604   struct queue_iter_param param;
5605   struct stop_reply *reply;
5606   struct remote_state *rs = get_remote_state ();
5607   struct remote_notif_state *rns = rs->notif_state;
5608
5609   /* This function can be notified when an inferior exists.  When the
5610      target is not remote, the notification state is NULL.  */
5611   if (rs->remote_desc == NULL)
5612     return;
5613
5614   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
5615
5616   /* Discard the in-flight notification.  */
5617   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
5618     {
5619       stop_reply_xfree (reply);
5620       rns->pending_event[notif_client_stop.id] = NULL;
5621     }
5622
5623   param.input = inf;
5624   param.output = NULL;
5625   /* Discard the stop replies we have already pulled with
5626      vStopped.  */
5627   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5628                  remove_stop_reply_for_inferior, &param);
5629 }
5630
5631 /* If its remote state is equal to the given remote state,
5632    remove EVENT from the stop reply queue.  */
5633
5634 static int
5635 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
5636                                    QUEUE_ITER (stop_reply_p) *iter,
5637                                    stop_reply_p event,
5638                                    void *data)
5639 {
5640   struct queue_iter_param *param = data;
5641   struct remote_state *rs = param->input;
5642
5643   if (event->rs == rs)
5644     {
5645       stop_reply_xfree (event);
5646       QUEUE_remove_elem (stop_reply_p, q, iter);
5647     }
5648
5649   return 1;
5650 }
5651
5652 /* Discard the stop replies for RS in stop_reply_queue.  */
5653
5654 static void
5655 discard_pending_stop_replies_in_queue (struct remote_state *rs)
5656 {
5657   struct queue_iter_param param;
5658
5659   param.input = rs;
5660   param.output = NULL;
5661   /* Discard the stop replies we have already pulled with
5662      vStopped.  */
5663   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5664                  remove_stop_reply_of_remote_state, &param);
5665 }
5666
5667 /* A parameter to pass data in and out.  */
5668
5669 static int
5670 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
5671                                    QUEUE_ITER (stop_reply_p) *iter,
5672                                    stop_reply_p event,
5673                                    void *data)
5674 {
5675   struct queue_iter_param *param = data;
5676   ptid_t *ptid = param->input;
5677
5678   if (ptid_match (event->ptid, *ptid))
5679     {
5680       param->output = event;
5681       QUEUE_remove_elem (stop_reply_p, q, iter);
5682       return 0;
5683     }
5684
5685   return 1;
5686 }
5687
5688 /* Remove the first reply in 'stop_reply_queue' which matches
5689    PTID.  */
5690
5691 static struct stop_reply *
5692 remote_notif_remove_queued_reply (ptid_t ptid)
5693 {
5694   struct queue_iter_param param;
5695
5696   param.input = &ptid;
5697   param.output = NULL;
5698
5699   QUEUE_iterate (stop_reply_p, stop_reply_queue,
5700                  remote_notif_remove_once_on_match, &param);
5701   if (notif_debug)
5702     fprintf_unfiltered (gdb_stdlog,
5703                         "notif: discard queued event: 'Stop' in %s\n",
5704                         target_pid_to_str (ptid));
5705
5706   return param.output;
5707 }
5708
5709 /* Look for a queued stop reply belonging to PTID.  If one is found,
5710    remove it from the queue, and return it.  Returns NULL if none is
5711    found.  If there are still queued events left to process, tell the
5712    event loop to get back to target_wait soon.  */
5713
5714 static struct stop_reply *
5715 queued_stop_reply (ptid_t ptid)
5716 {
5717   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
5718
5719   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
5720     /* There's still at least an event left.  */
5721     mark_async_event_handler (remote_async_inferior_event_token);
5722
5723   return r;
5724 }
5725
5726 /* Push a fully parsed stop reply in the stop reply queue.  Since we
5727    know that we now have at least one queued event left to pass to the
5728    core side, tell the event loop to get back to target_wait soon.  */
5729
5730 static void
5731 push_stop_reply (struct stop_reply *new_event)
5732 {
5733   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
5734
5735   if (notif_debug)
5736     fprintf_unfiltered (gdb_stdlog,
5737                         "notif: push 'Stop' %s to queue %d\n",
5738                         target_pid_to_str (new_event->ptid),
5739                         QUEUE_length (stop_reply_p,
5740                                       stop_reply_queue));
5741
5742   mark_async_event_handler (remote_async_inferior_event_token);
5743 }
5744
5745 static int
5746 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
5747                               QUEUE_ITER (stop_reply_p) *iter,
5748                               struct stop_reply *event,
5749                               void *data)
5750 {
5751   ptid_t *ptid = data;
5752
5753   return !(ptid_equal (*ptid, event->ptid)
5754            && event->ws.kind == TARGET_WAITKIND_STOPPED);
5755 }
5756
5757 /* Returns true if we have a stop reply for PTID.  */
5758
5759 static int
5760 peek_stop_reply (ptid_t ptid)
5761 {
5762   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
5763                          stop_reply_match_ptid_and_ws, &ptid);
5764 }
5765
5766 /* Skip PACKET until the next semi-colon (or end of string).  */
5767
5768 static char *
5769 skip_to_semicolon (char *p)
5770 {
5771   while (*p != '\0' && *p != ';')
5772     p++;
5773   return p;
5774 }
5775
5776 /* Parse the stop reply in BUF.  Either the function succeeds, and the
5777    result is stored in EVENT, or throws an error.  */
5778
5779 static void
5780 remote_parse_stop_reply (char *buf, struct stop_reply *event)
5781 {
5782   struct remote_arch_state *rsa = get_remote_arch_state ();
5783   ULONGEST addr;
5784   char *p;
5785
5786   event->ptid = null_ptid;
5787   event->rs = get_remote_state ();
5788   event->ws.kind = TARGET_WAITKIND_IGNORE;
5789   event->ws.value.integer = 0;
5790   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5791   event->regcache = NULL;
5792   event->core = -1;
5793
5794   switch (buf[0])
5795     {
5796     case 'T':           /* Status with PC, SP, FP, ...  */
5797       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
5798       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
5799             ss = signal number
5800             n... = register number
5801             r... = register contents
5802       */
5803
5804       p = &buf[3];      /* after Txx */
5805       while (*p)
5806         {
5807           char *p1;
5808           int fieldsize;
5809
5810           p1 = strchr (p, ':');
5811           if (p1 == NULL)
5812             error (_("Malformed packet(a) (missing colon): %s\n\
5813 Packet: '%s'\n"),
5814                    p, buf);
5815           if (p == p1)
5816             error (_("Malformed packet(a) (missing register number): %s\n\
5817 Packet: '%s'\n"),
5818                    p, buf);
5819
5820           /* Some "registers" are actually extended stop information.
5821              Note if you're adding a new entry here: GDB 7.9 and
5822              earlier assume that all register "numbers" that start
5823              with an hex digit are real register numbers.  Make sure
5824              the server only sends such a packet if it knows the
5825              client understands it.  */
5826
5827           if (strncmp (p, "thread", p1 - p) == 0)
5828             event->ptid = read_ptid (++p1, &p);
5829           else if ((strncmp (p, "watch", p1 - p) == 0)
5830                    || (strncmp (p, "rwatch", p1 - p) == 0)
5831                    || (strncmp (p, "awatch", p1 - p) == 0))
5832             {
5833               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
5834               p = unpack_varlen_hex (++p1, &addr);
5835               event->watch_data_address = (CORE_ADDR) addr;
5836             }
5837           else if (strncmp (p, "swbreak", p1 - p) == 0)
5838             {
5839               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
5840
5841               /* Make sure the stub doesn't forget to indicate support
5842                  with qSupported.  */
5843               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
5844                 error (_("Unexpected swbreak stop reason"));
5845
5846               /* The value part is documented as "must be empty",
5847                  though we ignore it, in case we ever decide to make
5848                  use of it in a backward compatible way.  */
5849               p = skip_to_semicolon (p1 + 1);
5850             }
5851           else if (strncmp (p, "hwbreak", p1 - p) == 0)
5852             {
5853               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
5854
5855               /* Make sure the stub doesn't forget to indicate support
5856                  with qSupported.  */
5857               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
5858                 error (_("Unexpected hwbreak stop reason"));
5859
5860               /* See above.  */
5861               p = skip_to_semicolon (p1 + 1);
5862             }
5863           else if (strncmp (p, "library", p1 - p) == 0)
5864             {
5865               event->ws.kind = TARGET_WAITKIND_LOADED;
5866               p = skip_to_semicolon (p1 + 1);
5867             }
5868           else if (strncmp (p, "replaylog", p1 - p) == 0)
5869             {
5870               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
5871               /* p1 will indicate "begin" or "end", but it makes
5872                  no difference for now, so ignore it.  */
5873               p = skip_to_semicolon (p1 + 1);
5874             }
5875           else if (strncmp (p, "core", p1 - p) == 0)
5876             {
5877               ULONGEST c;
5878
5879               p = unpack_varlen_hex (++p1, &c);
5880               event->core = c;
5881             }
5882           else if (strncmp (p, "fork", p1 - p) == 0)
5883             {
5884               event->ws.value.related_pid = read_ptid (++p1, &p);
5885               event->ws.kind = TARGET_WAITKIND_FORKED;
5886             }
5887           else if (strncmp (p, "vfork", p1 - p) == 0)
5888             {
5889               event->ws.value.related_pid = read_ptid (++p1, &p);
5890               event->ws.kind = TARGET_WAITKIND_VFORKED;
5891             }
5892           else if (strncmp (p, "vforkdone", p1 - p) == 0)
5893             {
5894               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
5895               p = skip_to_semicolon (p1 + 1);
5896             }
5897           else
5898             {
5899               ULONGEST pnum;
5900               char *p_temp;
5901
5902               /* Maybe a real ``P'' register number.  */
5903               p_temp = unpack_varlen_hex (p, &pnum);
5904               /* If the first invalid character is the colon, we got a
5905                  register number.  Otherwise, it's an unknown stop
5906                  reason.  */
5907               if (p_temp == p1)
5908                 {
5909                   struct packet_reg *reg = packet_reg_from_pnum (rsa, pnum);
5910                   cached_reg_t cached_reg;
5911
5912                   if (reg == NULL)
5913                     error (_("Remote sent bad register number %s: %s\n\
5914 Packet: '%s'\n"),
5915                            hex_string (pnum), p, buf);
5916
5917                   cached_reg.num = reg->regnum;
5918
5919                   p = p1 + 1;
5920                   fieldsize = hex2bin (p, cached_reg.data,
5921                                        register_size (target_gdbarch (),
5922                                                       reg->regnum));
5923                   p += 2 * fieldsize;
5924                   if (fieldsize < register_size (target_gdbarch (),
5925                                                  reg->regnum))
5926                     warning (_("Remote reply is too short: %s"), buf);
5927
5928                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
5929                 }
5930               else
5931                 {
5932                   /* Not a number.  Silently skip unknown optional
5933                      info.  */
5934                   p = skip_to_semicolon (p1 + 1);
5935                 }
5936             }
5937
5938           if (*p != ';')
5939             error (_("Remote register badly formatted: %s\nhere: %s"),
5940                    buf, p);
5941           ++p;
5942         }
5943
5944       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
5945         break;
5946
5947       /* fall through */
5948     case 'S':           /* Old style status, just signal only.  */
5949       {
5950         int sig;
5951
5952         event->ws.kind = TARGET_WAITKIND_STOPPED;
5953         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
5954         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
5955           event->ws.value.sig = (enum gdb_signal) sig;
5956         else
5957           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5958       }
5959       break;
5960     case 'W':           /* Target exited.  */
5961     case 'X':
5962       {
5963         char *p;
5964         int pid;
5965         ULONGEST value;
5966
5967         /* GDB used to accept only 2 hex chars here.  Stubs should
5968            only send more if they detect GDB supports multi-process
5969            support.  */
5970         p = unpack_varlen_hex (&buf[1], &value);
5971
5972         if (buf[0] == 'W')
5973           {
5974             /* The remote process exited.  */
5975             event->ws.kind = TARGET_WAITKIND_EXITED;
5976             event->ws.value.integer = value;
5977           }
5978         else
5979           {
5980             /* The remote process exited with a signal.  */
5981             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
5982             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
5983               event->ws.value.sig = (enum gdb_signal) value;
5984             else
5985               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
5986           }
5987
5988         /* If no process is specified, assume inferior_ptid.  */
5989         pid = ptid_get_pid (inferior_ptid);
5990         if (*p == '\0')
5991           ;
5992         else if (*p == ';')
5993           {
5994             p++;
5995
5996             if (*p == '\0')
5997               ;
5998             else if (startswith (p, "process:"))
5999               {
6000                 ULONGEST upid;
6001
6002                 p += sizeof ("process:") - 1;
6003                 unpack_varlen_hex (p, &upid);
6004                 pid = upid;
6005               }
6006             else
6007               error (_("unknown stop reply packet: %s"), buf);
6008           }
6009         else
6010           error (_("unknown stop reply packet: %s"), buf);
6011         event->ptid = pid_to_ptid (pid);
6012       }
6013       break;
6014     }
6015
6016   if (non_stop && ptid_equal (event->ptid, null_ptid))
6017     error (_("No process or thread specified in stop reply: %s"), buf);
6018 }
6019
6020 /* When the stub wants to tell GDB about a new notification reply, it
6021    sends a notification (%Stop, for example).  Those can come it at
6022    any time, hence, we have to make sure that any pending
6023    putpkt/getpkt sequence we're making is finished, before querying
6024    the stub for more events with the corresponding ack command
6025    (vStopped, for example).  E.g., if we started a vStopped sequence
6026    immediately upon receiving the notification, something like this
6027    could happen:
6028
6029     1.1) --> Hg 1
6030     1.2) <-- OK
6031     1.3) --> g
6032     1.4) <-- %Stop
6033     1.5) --> vStopped
6034     1.6) <-- (registers reply to step #1.3)
6035
6036    Obviously, the reply in step #1.6 would be unexpected to a vStopped
6037    query.
6038
6039    To solve this, whenever we parse a %Stop notification successfully,
6040    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
6041    doing whatever we were doing:
6042
6043     2.1) --> Hg 1
6044     2.2) <-- OK
6045     2.3) --> g
6046     2.4) <-- %Stop
6047       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
6048     2.5) <-- (registers reply to step #2.3)
6049
6050    Eventualy after step #2.5, we return to the event loop, which
6051    notices there's an event on the
6052    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
6053    associated callback --- the function below.  At this point, we're
6054    always safe to start a vStopped sequence. :
6055
6056     2.6) --> vStopped
6057     2.7) <-- T05 thread:2
6058     2.8) --> vStopped
6059     2.9) --> OK
6060 */
6061
6062 void
6063 remote_notif_get_pending_events (struct notif_client *nc)
6064 {
6065   struct remote_state *rs = get_remote_state ();
6066
6067   if (rs->notif_state->pending_event[nc->id] != NULL)
6068     {
6069       if (notif_debug)
6070         fprintf_unfiltered (gdb_stdlog,
6071                             "notif: process: '%s' ack pending event\n",
6072                             nc->name);
6073
6074       /* acknowledge */
6075       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
6076       rs->notif_state->pending_event[nc->id] = NULL;
6077
6078       while (1)
6079         {
6080           getpkt (&rs->buf, &rs->buf_size, 0);
6081           if (strcmp (rs->buf, "OK") == 0)
6082             break;
6083           else
6084             remote_notif_ack (nc, rs->buf);
6085         }
6086     }
6087   else
6088     {
6089       if (notif_debug)
6090         fprintf_unfiltered (gdb_stdlog,
6091                             "notif: process: '%s' no pending reply\n",
6092                             nc->name);
6093     }
6094 }
6095
6096 /* Called when it is decided that STOP_REPLY holds the info of the
6097    event that is to be returned to the core.  This function always
6098    destroys STOP_REPLY.  */
6099
6100 static ptid_t
6101 process_stop_reply (struct stop_reply *stop_reply,
6102                     struct target_waitstatus *status)
6103 {
6104   ptid_t ptid;
6105
6106   *status = stop_reply->ws;
6107   ptid = stop_reply->ptid;
6108
6109   /* If no thread/process was reported by the stub, assume the current
6110      inferior.  */
6111   if (ptid_equal (ptid, null_ptid))
6112     ptid = inferior_ptid;
6113
6114   if (status->kind != TARGET_WAITKIND_EXITED
6115       && status->kind != TARGET_WAITKIND_SIGNALLED)
6116     {
6117       struct remote_state *rs = get_remote_state ();
6118
6119       /* Expedited registers.  */
6120       if (stop_reply->regcache)
6121         {
6122           struct regcache *regcache
6123             = get_thread_arch_regcache (ptid, target_gdbarch ());
6124           cached_reg_t *reg;
6125           int ix;
6126
6127           for (ix = 0;
6128                VEC_iterate(cached_reg_t, stop_reply->regcache, ix, reg);
6129                ix++)
6130             regcache_raw_supply (regcache, reg->num, reg->data);
6131           VEC_free (cached_reg_t, stop_reply->regcache);
6132         }
6133
6134       rs->stop_reason = stop_reply->stop_reason;
6135       rs->remote_watch_data_address = stop_reply->watch_data_address;
6136
6137       remote_notice_new_inferior (ptid, 0);
6138       demand_private_info (ptid)->core = stop_reply->core;
6139     }
6140
6141   stop_reply_xfree (stop_reply);
6142   return ptid;
6143 }
6144
6145 /* The non-stop mode version of target_wait.  */
6146
6147 static ptid_t
6148 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
6149 {
6150   struct remote_state *rs = get_remote_state ();
6151   struct stop_reply *stop_reply;
6152   int ret;
6153   int is_notif = 0;
6154
6155   /* If in non-stop mode, get out of getpkt even if a
6156      notification is received.  */
6157
6158   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6159                               0 /* forever */, &is_notif);
6160   while (1)
6161     {
6162       if (ret != -1 && !is_notif)
6163         switch (rs->buf[0])
6164           {
6165           case 'E':             /* Error of some sort.  */
6166             /* We're out of sync with the target now.  Did it continue
6167                or not?  We can't tell which thread it was in non-stop,
6168                so just ignore this.  */
6169             warning (_("Remote failure reply: %s"), rs->buf);
6170             break;
6171           case 'O':             /* Console output.  */
6172             remote_console_output (rs->buf + 1);
6173             break;
6174           default:
6175             warning (_("Invalid remote reply: %s"), rs->buf);
6176             break;
6177           }
6178
6179       /* Acknowledge a pending stop reply that may have arrived in the
6180          mean time.  */
6181       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
6182         remote_notif_get_pending_events (&notif_client_stop);
6183
6184       /* If indeed we noticed a stop reply, we're done.  */
6185       stop_reply = queued_stop_reply (ptid);
6186       if (stop_reply != NULL)
6187         return process_stop_reply (stop_reply, status);
6188
6189       /* Still no event.  If we're just polling for an event, then
6190          return to the event loop.  */
6191       if (options & TARGET_WNOHANG)
6192         {
6193           status->kind = TARGET_WAITKIND_IGNORE;
6194           return minus_one_ptid;
6195         }
6196
6197       /* Otherwise do a blocking wait.  */
6198       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6199                                   1 /* forever */, &is_notif);
6200     }
6201 }
6202
6203 /* Wait until the remote machine stops, then return, storing status in
6204    STATUS just as `wait' would.  */
6205
6206 static ptid_t
6207 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
6208 {
6209   struct remote_state *rs = get_remote_state ();
6210   ptid_t event_ptid = null_ptid;
6211   char *buf;
6212   struct stop_reply *stop_reply;
6213
6214  again:
6215
6216   status->kind = TARGET_WAITKIND_IGNORE;
6217   status->value.integer = 0;
6218
6219   stop_reply = queued_stop_reply (ptid);
6220   if (stop_reply != NULL)
6221     return process_stop_reply (stop_reply, status);
6222
6223   if (rs->cached_wait_status)
6224     /* Use the cached wait status, but only once.  */
6225     rs->cached_wait_status = 0;
6226   else
6227     {
6228       int ret;
6229       int is_notif;
6230
6231       if (!target_is_async_p ())
6232         {
6233           ofunc = signal (SIGINT, sync_remote_interrupt);
6234           /* If the user hit C-c before this packet, or between packets,
6235              pretend that it was hit right here.  */
6236           if (check_quit_flag ())
6237             {
6238               clear_quit_flag ();
6239               sync_remote_interrupt (SIGINT);
6240             }
6241         }
6242
6243       /* FIXME: cagney/1999-09-27: If we're in async mode we should
6244          _never_ wait for ever -> test on target_is_async_p().
6245          However, before we do that we need to ensure that the caller
6246          knows how to take the target into/out of async mode.  */
6247       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
6248                                   wait_forever_enabled_p, &is_notif);
6249
6250       if (!target_is_async_p ())
6251         signal (SIGINT, ofunc);
6252
6253       /* GDB gets a notification.  Return to core as this event is
6254          not interesting.  */
6255       if (ret != -1 && is_notif)
6256         return minus_one_ptid;
6257     }
6258
6259   buf = rs->buf;
6260
6261   rs->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6262
6263   /* We got something.  */
6264   rs->waiting_for_stop_reply = 0;
6265
6266   /* Assume that the target has acknowledged Ctrl-C unless we receive
6267      an 'F' or 'O' packet.  */
6268   if (buf[0] != 'F' && buf[0] != 'O')
6269     rs->ctrlc_pending_p = 0;
6270
6271   switch (buf[0])
6272     {
6273     case 'E':           /* Error of some sort.  */
6274       /* We're out of sync with the target now.  Did it continue or
6275          not?  Not is more likely, so report a stop.  */
6276       warning (_("Remote failure reply: %s"), buf);
6277       status->kind = TARGET_WAITKIND_STOPPED;
6278       status->value.sig = GDB_SIGNAL_0;
6279       break;
6280     case 'F':           /* File-I/O request.  */
6281       remote_fileio_request (buf, rs->ctrlc_pending_p);
6282       rs->ctrlc_pending_p = 0;
6283       break;
6284     case 'T': case 'S': case 'X': case 'W':
6285       {
6286         struct stop_reply *stop_reply
6287           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
6288                                                       rs->buf);
6289
6290         event_ptid = process_stop_reply (stop_reply, status);
6291         break;
6292       }
6293     case 'O':           /* Console output.  */
6294       remote_console_output (buf + 1);
6295
6296       /* The target didn't really stop; keep waiting.  */
6297       rs->waiting_for_stop_reply = 1;
6298
6299       break;
6300     case '\0':
6301       if (rs->last_sent_signal != GDB_SIGNAL_0)
6302         {
6303           /* Zero length reply means that we tried 'S' or 'C' and the
6304              remote system doesn't support it.  */
6305           target_terminal_ours_for_output ();
6306           printf_filtered
6307             ("Can't send signals to this remote system.  %s not sent.\n",
6308              gdb_signal_to_name (rs->last_sent_signal));
6309           rs->last_sent_signal = GDB_SIGNAL_0;
6310           target_terminal_inferior ();
6311
6312           strcpy ((char *) buf, rs->last_sent_step ? "s" : "c");
6313           putpkt ((char *) buf);
6314
6315           /* We just told the target to resume, so a stop reply is in
6316              order.  */
6317           rs->waiting_for_stop_reply = 1;
6318           break;
6319         }
6320       /* else fallthrough */
6321     default:
6322       warning (_("Invalid remote reply: %s"), buf);
6323       /* Keep waiting.  */
6324       rs->waiting_for_stop_reply = 1;
6325       break;
6326     }
6327
6328   if (status->kind == TARGET_WAITKIND_IGNORE)
6329     {
6330       /* Nothing interesting happened.  If we're doing a non-blocking
6331          poll, we're done.  Otherwise, go back to waiting.  */
6332       if (options & TARGET_WNOHANG)
6333         return minus_one_ptid;
6334       else
6335         goto again;
6336     }
6337   else if (status->kind != TARGET_WAITKIND_EXITED
6338            && status->kind != TARGET_WAITKIND_SIGNALLED)
6339     {
6340       if (!ptid_equal (event_ptid, null_ptid))
6341         record_currthread (rs, event_ptid);
6342       else
6343         event_ptid = inferior_ptid;
6344     }
6345   else
6346     /* A process exit.  Invalidate our notion of current thread.  */
6347     record_currthread (rs, minus_one_ptid);
6348
6349   return event_ptid;
6350 }
6351
6352 /* Wait until the remote machine stops, then return, storing status in
6353    STATUS just as `wait' would.  */
6354
6355 static ptid_t
6356 remote_wait (struct target_ops *ops,
6357              ptid_t ptid, struct target_waitstatus *status, int options)
6358 {
6359   ptid_t event_ptid;
6360
6361   if (non_stop)
6362     event_ptid = remote_wait_ns (ptid, status, options);
6363   else
6364     event_ptid = remote_wait_as (ptid, status, options);
6365
6366   if (target_is_async_p ())
6367     {
6368       /* If there are are events left in the queue tell the event loop
6369          to return here.  */
6370       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6371         mark_async_event_handler (remote_async_inferior_event_token);
6372     }
6373
6374   return event_ptid;
6375 }
6376
6377 /* Fetch a single register using a 'p' packet.  */
6378
6379 static int
6380 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
6381 {
6382   struct remote_state *rs = get_remote_state ();
6383   char *buf, *p;
6384   char regp[MAX_REGISTER_SIZE];
6385   int i;
6386
6387   if (packet_support (PACKET_p) == PACKET_DISABLE)
6388     return 0;
6389
6390   if (reg->pnum == -1)
6391     return 0;
6392
6393   p = rs->buf;
6394   *p++ = 'p';
6395   p += hexnumstr (p, reg->pnum);
6396   *p++ = '\0';
6397   putpkt (rs->buf);
6398   getpkt (&rs->buf, &rs->buf_size, 0);
6399
6400   buf = rs->buf;
6401
6402   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
6403     {
6404     case PACKET_OK:
6405       break;
6406     case PACKET_UNKNOWN:
6407       return 0;
6408     case PACKET_ERROR:
6409       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
6410              gdbarch_register_name (get_regcache_arch (regcache), 
6411                                     reg->regnum), 
6412              buf);
6413     }
6414
6415   /* If this register is unfetchable, tell the regcache.  */
6416   if (buf[0] == 'x')
6417     {
6418       regcache_raw_supply (regcache, reg->regnum, NULL);
6419       return 1;
6420     }
6421
6422   /* Otherwise, parse and supply the value.  */
6423   p = buf;
6424   i = 0;
6425   while (p[0] != 0)
6426     {
6427       if (p[1] == 0)
6428         error (_("fetch_register_using_p: early buf termination"));
6429
6430       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
6431       p += 2;
6432     }
6433   regcache_raw_supply (regcache, reg->regnum, regp);
6434   return 1;
6435 }
6436
6437 /* Fetch the registers included in the target's 'g' packet.  */
6438
6439 static int
6440 send_g_packet (void)
6441 {
6442   struct remote_state *rs = get_remote_state ();
6443   int buf_len;
6444
6445   xsnprintf (rs->buf, get_remote_packet_size (), "g");
6446   remote_send (&rs->buf, &rs->buf_size);
6447
6448   /* We can get out of synch in various cases.  If the first character
6449      in the buffer is not a hex character, assume that has happened
6450      and try to fetch another packet to read.  */
6451   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
6452          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
6453          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
6454          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
6455     {
6456       if (remote_debug)
6457         fprintf_unfiltered (gdb_stdlog,
6458                             "Bad register packet; fetching a new packet\n");
6459       getpkt (&rs->buf, &rs->buf_size, 0);
6460     }
6461
6462   buf_len = strlen (rs->buf);
6463
6464   /* Sanity check the received packet.  */
6465   if (buf_len % 2 != 0)
6466     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
6467
6468   return buf_len / 2;
6469 }
6470
6471 static void
6472 process_g_packet (struct regcache *regcache)
6473 {
6474   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6475   struct remote_state *rs = get_remote_state ();
6476   struct remote_arch_state *rsa = get_remote_arch_state ();
6477   int i, buf_len;
6478   char *p;
6479   char *regs;
6480
6481   buf_len = strlen (rs->buf);
6482
6483   /* Further sanity checks, with knowledge of the architecture.  */
6484   if (buf_len > 2 * rsa->sizeof_g_packet)
6485     error (_("Remote 'g' packet reply is too long: %s"), rs->buf);
6486
6487   /* Save the size of the packet sent to us by the target.  It is used
6488      as a heuristic when determining the max size of packets that the
6489      target can safely receive.  */
6490   if (rsa->actual_register_packet_size == 0)
6491     rsa->actual_register_packet_size = buf_len;
6492
6493   /* If this is smaller than we guessed the 'g' packet would be,
6494      update our records.  A 'g' reply that doesn't include a register's
6495      value implies either that the register is not available, or that
6496      the 'p' packet must be used.  */
6497   if (buf_len < 2 * rsa->sizeof_g_packet)
6498     {
6499       rsa->sizeof_g_packet = buf_len / 2;
6500
6501       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6502         {
6503           if (rsa->regs[i].pnum == -1)
6504             continue;
6505
6506           if (rsa->regs[i].offset >= rsa->sizeof_g_packet)
6507             rsa->regs[i].in_g_packet = 0;
6508           else
6509             rsa->regs[i].in_g_packet = 1;
6510         }
6511     }
6512
6513   regs = alloca (rsa->sizeof_g_packet);
6514
6515   /* Unimplemented registers read as all bits zero.  */
6516   memset (regs, 0, rsa->sizeof_g_packet);
6517
6518   /* Reply describes registers byte by byte, each byte encoded as two
6519      hex characters.  Suck them all up, then supply them to the
6520      register cacheing/storage mechanism.  */
6521
6522   p = rs->buf;
6523   for (i = 0; i < rsa->sizeof_g_packet; i++)
6524     {
6525       if (p[0] == 0 || p[1] == 0)
6526         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
6527         internal_error (__FILE__, __LINE__,
6528                         _("unexpected end of 'g' packet reply"));
6529
6530       if (p[0] == 'x' && p[1] == 'x')
6531         regs[i] = 0;            /* 'x' */
6532       else
6533         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
6534       p += 2;
6535     }
6536
6537   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
6538     {
6539       struct packet_reg *r = &rsa->regs[i];
6540
6541       if (r->in_g_packet)
6542         {
6543           if (r->offset * 2 >= strlen (rs->buf))
6544             /* This shouldn't happen - we adjusted in_g_packet above.  */
6545             internal_error (__FILE__, __LINE__,
6546                             _("unexpected end of 'g' packet reply"));
6547           else if (rs->buf[r->offset * 2] == 'x')
6548             {
6549               gdb_assert (r->offset * 2 < strlen (rs->buf));
6550               /* The register isn't available, mark it as such (at
6551                  the same time setting the value to zero).  */
6552               regcache_raw_supply (regcache, r->regnum, NULL);
6553             }
6554           else
6555             regcache_raw_supply (regcache, r->regnum,
6556                                  regs + r->offset);
6557         }
6558     }
6559 }
6560
6561 static void
6562 fetch_registers_using_g (struct regcache *regcache)
6563 {
6564   send_g_packet ();
6565   process_g_packet (regcache);
6566 }
6567
6568 /* Make the remote selected traceframe match GDB's selected
6569    traceframe.  */
6570
6571 static void
6572 set_remote_traceframe (void)
6573 {
6574   int newnum;
6575   struct remote_state *rs = get_remote_state ();
6576
6577   if (rs->remote_traceframe_number == get_traceframe_number ())
6578     return;
6579
6580   /* Avoid recursion, remote_trace_find calls us again.  */
6581   rs->remote_traceframe_number = get_traceframe_number ();
6582
6583   newnum = target_trace_find (tfind_number,
6584                               get_traceframe_number (), 0, 0, NULL);
6585
6586   /* Should not happen.  If it does, all bets are off.  */
6587   if (newnum != get_traceframe_number ())
6588     warning (_("could not set remote traceframe"));
6589 }
6590
6591 static void
6592 remote_fetch_registers (struct target_ops *ops,
6593                         struct regcache *regcache, int regnum)
6594 {
6595   struct remote_arch_state *rsa = get_remote_arch_state ();
6596   int i;
6597
6598   set_remote_traceframe ();
6599   set_general_thread (inferior_ptid);
6600
6601   if (regnum >= 0)
6602     {
6603       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6604
6605       gdb_assert (reg != NULL);
6606
6607       /* If this register might be in the 'g' packet, try that first -
6608          we are likely to read more than one register.  If this is the
6609          first 'g' packet, we might be overly optimistic about its
6610          contents, so fall back to 'p'.  */
6611       if (reg->in_g_packet)
6612         {
6613           fetch_registers_using_g (regcache);
6614           if (reg->in_g_packet)
6615             return;
6616         }
6617
6618       if (fetch_register_using_p (regcache, reg))
6619         return;
6620
6621       /* This register is not available.  */
6622       regcache_raw_supply (regcache, reg->regnum, NULL);
6623
6624       return;
6625     }
6626
6627   fetch_registers_using_g (regcache);
6628
6629   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6630     if (!rsa->regs[i].in_g_packet)
6631       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
6632         {
6633           /* This register is not available.  */
6634           regcache_raw_supply (regcache, i, NULL);
6635         }
6636 }
6637
6638 /* Prepare to store registers.  Since we may send them all (using a
6639    'G' request), we have to read out the ones we don't want to change
6640    first.  */
6641
6642 static void
6643 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
6644 {
6645   struct remote_arch_state *rsa = get_remote_arch_state ();
6646   int i;
6647   gdb_byte buf[MAX_REGISTER_SIZE];
6648
6649   /* Make sure the entire registers array is valid.  */
6650   switch (packet_support (PACKET_P))
6651     {
6652     case PACKET_DISABLE:
6653     case PACKET_SUPPORT_UNKNOWN:
6654       /* Make sure all the necessary registers are cached.  */
6655       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6656         if (rsa->regs[i].in_g_packet)
6657           regcache_raw_read (regcache, rsa->regs[i].regnum, buf);
6658       break;
6659     case PACKET_ENABLE:
6660       break;
6661     }
6662 }
6663
6664 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
6665    packet was not recognized.  */
6666
6667 static int
6668 store_register_using_P (const struct regcache *regcache, 
6669                         struct packet_reg *reg)
6670 {
6671   struct gdbarch *gdbarch = get_regcache_arch (regcache);
6672   struct remote_state *rs = get_remote_state ();
6673   /* Try storing a single register.  */
6674   char *buf = rs->buf;
6675   gdb_byte regp[MAX_REGISTER_SIZE];
6676   char *p;
6677
6678   if (packet_support (PACKET_P) == PACKET_DISABLE)
6679     return 0;
6680
6681   if (reg->pnum == -1)
6682     return 0;
6683
6684   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
6685   p = buf + strlen (buf);
6686   regcache_raw_collect (regcache, reg->regnum, regp);
6687   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
6688   putpkt (rs->buf);
6689   getpkt (&rs->buf, &rs->buf_size, 0);
6690
6691   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
6692     {
6693     case PACKET_OK:
6694       return 1;
6695     case PACKET_ERROR:
6696       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
6697              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
6698     case PACKET_UNKNOWN:
6699       return 0;
6700     default:
6701       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
6702     }
6703 }
6704
6705 /* Store register REGNUM, or all registers if REGNUM == -1, from the
6706    contents of the register cache buffer.  FIXME: ignores errors.  */
6707
6708 static void
6709 store_registers_using_G (const struct regcache *regcache)
6710 {
6711   struct remote_state *rs = get_remote_state ();
6712   struct remote_arch_state *rsa = get_remote_arch_state ();
6713   gdb_byte *regs;
6714   char *p;
6715
6716   /* Extract all the registers in the regcache copying them into a
6717      local buffer.  */
6718   {
6719     int i;
6720
6721     regs = alloca (rsa->sizeof_g_packet);
6722     memset (regs, 0, rsa->sizeof_g_packet);
6723     for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6724       {
6725         struct packet_reg *r = &rsa->regs[i];
6726
6727         if (r->in_g_packet)
6728           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
6729       }
6730   }
6731
6732   /* Command describes registers byte by byte,
6733      each byte encoded as two hex characters.  */
6734   p = rs->buf;
6735   *p++ = 'G';
6736   /* remote_prepare_to_store insures that rsa->sizeof_g_packet gets
6737      updated.  */
6738   bin2hex (regs, p, rsa->sizeof_g_packet);
6739   putpkt (rs->buf);
6740   getpkt (&rs->buf, &rs->buf_size, 0);
6741   if (packet_check_result (rs->buf) == PACKET_ERROR)
6742     error (_("Could not write registers; remote failure reply '%s'"), 
6743            rs->buf);
6744 }
6745
6746 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
6747    of the register cache buffer.  FIXME: ignores errors.  */
6748
6749 static void
6750 remote_store_registers (struct target_ops *ops,
6751                         struct regcache *regcache, int regnum)
6752 {
6753   struct remote_arch_state *rsa = get_remote_arch_state ();
6754   int i;
6755
6756   set_remote_traceframe ();
6757   set_general_thread (inferior_ptid);
6758
6759   if (regnum >= 0)
6760     {
6761       struct packet_reg *reg = packet_reg_from_regnum (rsa, regnum);
6762
6763       gdb_assert (reg != NULL);
6764
6765       /* Always prefer to store registers using the 'P' packet if
6766          possible; we often change only a small number of registers.
6767          Sometimes we change a larger number; we'd need help from a
6768          higher layer to know to use 'G'.  */
6769       if (store_register_using_P (regcache, reg))
6770         return;
6771
6772       /* For now, don't complain if we have no way to write the
6773          register.  GDB loses track of unavailable registers too
6774          easily.  Some day, this may be an error.  We don't have
6775          any way to read the register, either...  */
6776       if (!reg->in_g_packet)
6777         return;
6778
6779       store_registers_using_G (regcache);
6780       return;
6781     }
6782
6783   store_registers_using_G (regcache);
6784
6785   for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
6786     if (!rsa->regs[i].in_g_packet)
6787       if (!store_register_using_P (regcache, &rsa->regs[i]))
6788         /* See above for why we do not issue an error here.  */
6789         continue;
6790 }
6791 \f
6792
6793 /* Return the number of hex digits in num.  */
6794
6795 static int
6796 hexnumlen (ULONGEST num)
6797 {
6798   int i;
6799
6800   for (i = 0; num != 0; i++)
6801     num >>= 4;
6802
6803   return max (i, 1);
6804 }
6805
6806 /* Set BUF to the minimum number of hex digits representing NUM.  */
6807
6808 static int
6809 hexnumstr (char *buf, ULONGEST num)
6810 {
6811   int len = hexnumlen (num);
6812
6813   return hexnumnstr (buf, num, len);
6814 }
6815
6816
6817 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
6818
6819 static int
6820 hexnumnstr (char *buf, ULONGEST num, int width)
6821 {
6822   int i;
6823
6824   buf[width] = '\0';
6825
6826   for (i = width - 1; i >= 0; i--)
6827     {
6828       buf[i] = "0123456789abcdef"[(num & 0xf)];
6829       num >>= 4;
6830     }
6831
6832   return width;
6833 }
6834
6835 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
6836
6837 static CORE_ADDR
6838 remote_address_masked (CORE_ADDR addr)
6839 {
6840   unsigned int address_size = remote_address_size;
6841
6842   /* If "remoteaddresssize" was not set, default to target address size.  */
6843   if (!address_size)
6844     address_size = gdbarch_addr_bit (target_gdbarch ());
6845
6846   if (address_size > 0
6847       && address_size < (sizeof (ULONGEST) * 8))
6848     {
6849       /* Only create a mask when that mask can safely be constructed
6850          in a ULONGEST variable.  */
6851       ULONGEST mask = 1;
6852
6853       mask = (mask << address_size) - 1;
6854       addr &= mask;
6855     }
6856   return addr;
6857 }
6858
6859 /* Determine whether the remote target supports binary downloading.
6860    This is accomplished by sending a no-op memory write of zero length
6861    to the target at the specified address. It does not suffice to send
6862    the whole packet, since many stubs strip the eighth bit and
6863    subsequently compute a wrong checksum, which causes real havoc with
6864    remote_write_bytes.
6865
6866    NOTE: This can still lose if the serial line is not eight-bit
6867    clean.  In cases like this, the user should clear "remote
6868    X-packet".  */
6869
6870 static void
6871 check_binary_download (CORE_ADDR addr)
6872 {
6873   struct remote_state *rs = get_remote_state ();
6874
6875   switch (packet_support (PACKET_X))
6876     {
6877     case PACKET_DISABLE:
6878       break;
6879     case PACKET_ENABLE:
6880       break;
6881     case PACKET_SUPPORT_UNKNOWN:
6882       {
6883         char *p;
6884
6885         p = rs->buf;
6886         *p++ = 'X';
6887         p += hexnumstr (p, (ULONGEST) addr);
6888         *p++ = ',';
6889         p += hexnumstr (p, (ULONGEST) 0);
6890         *p++ = ':';
6891         *p = '\0';
6892
6893         putpkt_binary (rs->buf, (int) (p - rs->buf));
6894         getpkt (&rs->buf, &rs->buf_size, 0);
6895
6896         if (rs->buf[0] == '\0')
6897           {
6898             if (remote_debug)
6899               fprintf_unfiltered (gdb_stdlog,
6900                                   "binary downloading NOT "
6901                                   "supported by target\n");
6902             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
6903           }
6904         else
6905           {
6906             if (remote_debug)
6907               fprintf_unfiltered (gdb_stdlog,
6908                                   "binary downloading supported by target\n");
6909             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
6910           }
6911         break;
6912       }
6913     }
6914 }
6915
6916 /* Write memory data directly to the remote machine.
6917    This does not inform the data cache; the data cache uses this.
6918    HEADER is the starting part of the packet.
6919    MEMADDR is the address in the remote memory space.
6920    MYADDR is the address of the buffer in our space.
6921    LEN is the number of bytes.
6922    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
6923    should send data as binary ('X'), or hex-encoded ('M').
6924
6925    The function creates packet of the form
6926        <HEADER><ADDRESS>,<LENGTH>:<DATA>
6927
6928    where encoding of <DATA> is termined by PACKET_FORMAT.
6929
6930    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
6931    are omitted.
6932
6933    Return the transferred status, error or OK (an
6934    'enum target_xfer_status' value).  Save the number of bytes
6935    transferred in *XFERED_LEN.  Only transfer a single packet.  */
6936
6937 static enum target_xfer_status
6938 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
6939                         const gdb_byte *myaddr, ULONGEST len,
6940                         ULONGEST *xfered_len, char packet_format,
6941                         int use_length)
6942 {
6943   struct remote_state *rs = get_remote_state ();
6944   char *p;
6945   char *plen = NULL;
6946   int plenlen = 0;
6947   int todo;
6948   int nr_bytes;
6949   int payload_size;
6950   int payload_length;
6951   int header_length;
6952
6953   if (packet_format != 'X' && packet_format != 'M')
6954     internal_error (__FILE__, __LINE__,
6955                     _("remote_write_bytes_aux: bad packet format"));
6956
6957   if (len == 0)
6958     return TARGET_XFER_EOF;
6959
6960   payload_size = get_memory_write_packet_size ();
6961
6962   /* The packet buffer will be large enough for the payload;
6963      get_memory_packet_size ensures this.  */
6964   rs->buf[0] = '\0';
6965
6966   /* Compute the size of the actual payload by subtracting out the
6967      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
6968
6969   payload_size -= strlen ("$,:#NN");
6970   if (!use_length)
6971     /* The comma won't be used.  */
6972     payload_size += 1;
6973   header_length = strlen (header);
6974   payload_size -= header_length;
6975   payload_size -= hexnumlen (memaddr);
6976
6977   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
6978
6979   strcat (rs->buf, header);
6980   p = rs->buf + strlen (header);
6981
6982   /* Compute a best guess of the number of bytes actually transfered.  */
6983   if (packet_format == 'X')
6984     {
6985       /* Best guess at number of bytes that will fit.  */
6986       todo = min (len, payload_size);
6987       if (use_length)
6988         payload_size -= hexnumlen (todo);
6989       todo = min (todo, payload_size);
6990     }
6991   else
6992     {
6993       /* Num bytes that will fit.  */
6994       todo = min (len, payload_size / 2);
6995       if (use_length)
6996         payload_size -= hexnumlen (todo);
6997       todo = min (todo, payload_size / 2);
6998     }
6999
7000   if (todo <= 0)
7001     internal_error (__FILE__, __LINE__,
7002                     _("minimum packet size too small to write data"));
7003
7004   /* If we already need another packet, then try to align the end
7005      of this packet to a useful boundary.  */
7006   if (todo > 2 * REMOTE_ALIGN_WRITES && todo < len)
7007     todo = ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
7008
7009   /* Append "<memaddr>".  */
7010   memaddr = remote_address_masked (memaddr);
7011   p += hexnumstr (p, (ULONGEST) memaddr);
7012
7013   if (use_length)
7014     {
7015       /* Append ",".  */
7016       *p++ = ',';
7017
7018       /* Append <len>.  Retain the location/size of <len>.  It may need to
7019          be adjusted once the packet body has been created.  */
7020       plen = p;
7021       plenlen = hexnumstr (p, (ULONGEST) todo);
7022       p += plenlen;
7023     }
7024
7025   /* Append ":".  */
7026   *p++ = ':';
7027   *p = '\0';
7028
7029   /* Append the packet body.  */
7030   if (packet_format == 'X')
7031     {
7032       /* Binary mode.  Send target system values byte by byte, in
7033          increasing byte addresses.  Only escape certain critical
7034          characters.  */
7035       payload_length = remote_escape_output (myaddr, todo, (gdb_byte *) p,
7036                                              &nr_bytes, payload_size);
7037
7038       /* If not all TODO bytes fit, then we'll need another packet.  Make
7039          a second try to keep the end of the packet aligned.  Don't do
7040          this if the packet is tiny.  */
7041       if (nr_bytes < todo && nr_bytes > 2 * REMOTE_ALIGN_WRITES)
7042         {
7043           int new_nr_bytes;
7044
7045           new_nr_bytes = (((memaddr + nr_bytes) & ~(REMOTE_ALIGN_WRITES - 1))
7046                           - memaddr);
7047           if (new_nr_bytes != nr_bytes)
7048             payload_length = remote_escape_output (myaddr, new_nr_bytes,
7049                                                    (gdb_byte *) p, &nr_bytes,
7050                                                    payload_size);
7051         }
7052
7053       p += payload_length;
7054       if (use_length && nr_bytes < todo)
7055         {
7056           /* Escape chars have filled up the buffer prematurely,
7057              and we have actually sent fewer bytes than planned.
7058              Fix-up the length field of the packet.  Use the same
7059              number of characters as before.  */
7060           plen += hexnumnstr (plen, (ULONGEST) nr_bytes, plenlen);
7061           *plen = ':';  /* overwrite \0 from hexnumnstr() */
7062         }
7063     }
7064   else
7065     {
7066       /* Normal mode: Send target system values byte by byte, in
7067          increasing byte addresses.  Each byte is encoded as a two hex
7068          value.  */
7069       nr_bytes = bin2hex (myaddr, p, todo);
7070       p += 2 * nr_bytes;
7071     }
7072
7073   putpkt_binary (rs->buf, (int) (p - rs->buf));
7074   getpkt (&rs->buf, &rs->buf_size, 0);
7075
7076   if (rs->buf[0] == 'E')
7077     return TARGET_XFER_E_IO;
7078
7079   /* Return NR_BYTES, not TODO, in case escape chars caused us to send
7080      fewer bytes than we'd planned.  */
7081   *xfered_len = (ULONGEST) nr_bytes;
7082   return TARGET_XFER_OK;
7083 }
7084
7085 /* Write memory data directly to the remote machine.
7086    This does not inform the data cache; the data cache uses this.
7087    MEMADDR is the address in the remote memory space.
7088    MYADDR is the address of the buffer in our space.
7089    LEN is the number of bytes.
7090
7091    Return the transferred status, error or OK (an
7092    'enum target_xfer_status' value).  Save the number of bytes
7093    transferred in *XFERED_LEN.  Only transfer a single packet.  */
7094
7095 static enum target_xfer_status
7096 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
7097                     ULONGEST *xfered_len)
7098 {
7099   char *packet_format = 0;
7100
7101   /* Check whether the target supports binary download.  */
7102   check_binary_download (memaddr);
7103
7104   switch (packet_support (PACKET_X))
7105     {
7106     case PACKET_ENABLE:
7107       packet_format = "X";
7108       break;
7109     case PACKET_DISABLE:
7110       packet_format = "M";
7111       break;
7112     case PACKET_SUPPORT_UNKNOWN:
7113       internal_error (__FILE__, __LINE__,
7114                       _("remote_write_bytes: bad internal state"));
7115     default:
7116       internal_error (__FILE__, __LINE__, _("bad switch"));
7117     }
7118
7119   return remote_write_bytes_aux (packet_format,
7120                                  memaddr, myaddr, len, xfered_len,
7121                                  packet_format[0], 1);
7122 }
7123
7124 /* Read memory data directly from the remote machine.
7125    This does not use the data cache; the data cache uses this.
7126    MEMADDR is the address in the remote memory space.
7127    MYADDR is the address of the buffer in our space.
7128    LEN is the number of bytes.
7129
7130    Return the transferred status, error or OK (an
7131    'enum target_xfer_status' value).  Save the number of bytes
7132    transferred in *XFERED_LEN.  */
7133
7134 static enum target_xfer_status
7135 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len,
7136                      ULONGEST *xfered_len)
7137 {
7138   struct remote_state *rs = get_remote_state ();
7139   int max_buf_size;             /* Max size of packet output buffer.  */
7140   char *p;
7141   int todo;
7142   int i;
7143
7144   max_buf_size = get_memory_read_packet_size ();
7145   /* The packet buffer will be large enough for the payload;
7146      get_memory_packet_size ensures this.  */
7147
7148   /* Number if bytes that will fit.  */
7149   todo = min (len, max_buf_size / 2);
7150
7151   /* Construct "m"<memaddr>","<len>".  */
7152   memaddr = remote_address_masked (memaddr);
7153   p = rs->buf;
7154   *p++ = 'm';
7155   p += hexnumstr (p, (ULONGEST) memaddr);
7156   *p++ = ',';
7157   p += hexnumstr (p, (ULONGEST) todo);
7158   *p = '\0';
7159   putpkt (rs->buf);
7160   getpkt (&rs->buf, &rs->buf_size, 0);
7161   if (rs->buf[0] == 'E'
7162       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
7163       && rs->buf[3] == '\0')
7164     return TARGET_XFER_E_IO;
7165   /* Reply describes memory byte by byte, each byte encoded as two hex
7166      characters.  */
7167   p = rs->buf;
7168   i = hex2bin (p, myaddr, todo);
7169   /* Return what we have.  Let higher layers handle partial reads.  */
7170   *xfered_len = (ULONGEST) i;
7171   return TARGET_XFER_OK;
7172 }
7173
7174 /* Using the set of read-only target sections of remote, read live
7175    read-only memory.
7176
7177    For interface/parameters/return description see target.h,
7178    to_xfer_partial.  */
7179
7180 static enum target_xfer_status
7181 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
7182                                    ULONGEST memaddr, ULONGEST len,
7183                                    ULONGEST *xfered_len)
7184 {
7185   struct target_section *secp;
7186   struct target_section_table *table;
7187
7188   secp = target_section_by_addr (ops, memaddr);
7189   if (secp != NULL
7190       && (bfd_get_section_flags (secp->the_bfd_section->owner,
7191                                  secp->the_bfd_section)
7192           & SEC_READONLY))
7193     {
7194       struct target_section *p;
7195       ULONGEST memend = memaddr + len;
7196
7197       table = target_get_section_table (ops);
7198
7199       for (p = table->sections; p < table->sections_end; p++)
7200         {
7201           if (memaddr >= p->addr)
7202             {
7203               if (memend <= p->endaddr)
7204                 {
7205                   /* Entire transfer is within this section.  */
7206                   return remote_read_bytes_1 (memaddr, readbuf, len,
7207                                               xfered_len);
7208                 }
7209               else if (memaddr >= p->endaddr)
7210                 {
7211                   /* This section ends before the transfer starts.  */
7212                   continue;
7213                 }
7214               else
7215                 {
7216                   /* This section overlaps the transfer.  Just do half.  */
7217                   len = p->endaddr - memaddr;
7218                   return remote_read_bytes_1 (memaddr, readbuf, len,
7219                                               xfered_len);
7220                 }
7221             }
7222         }
7223     }
7224
7225   return TARGET_XFER_EOF;
7226 }
7227
7228 /* Similar to remote_read_bytes_1, but it reads from the remote stub
7229    first if the requested memory is unavailable in traceframe.
7230    Otherwise, fall back to remote_read_bytes_1.  */
7231
7232 static enum target_xfer_status
7233 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
7234                    gdb_byte *myaddr, ULONGEST len, ULONGEST *xfered_len)
7235 {
7236   if (len == 0)
7237     return TARGET_XFER_EOF;
7238
7239   if (get_traceframe_number () != -1)
7240     {
7241       VEC(mem_range_s) *available;
7242
7243       /* If we fail to get the set of available memory, then the
7244          target does not support querying traceframe info, and so we
7245          attempt reading from the traceframe anyway (assuming the
7246          target implements the old QTro packet then).  */
7247       if (traceframe_available_memory (&available, memaddr, len))
7248         {
7249           struct cleanup *old_chain;
7250
7251           old_chain = make_cleanup (VEC_cleanup(mem_range_s), &available);
7252
7253           if (VEC_empty (mem_range_s, available)
7254               || VEC_index (mem_range_s, available, 0)->start != memaddr)
7255             {
7256               enum target_xfer_status res;
7257
7258               /* Don't read into the traceframe's available
7259                  memory.  */
7260               if (!VEC_empty (mem_range_s, available))
7261                 {
7262                   LONGEST oldlen = len;
7263
7264                   len = VEC_index (mem_range_s, available, 0)->start - memaddr;
7265                   gdb_assert (len <= oldlen);
7266                 }
7267
7268               do_cleanups (old_chain);
7269
7270               /* This goes through the topmost target again.  */
7271               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
7272                                                        len, xfered_len);
7273               if (res == TARGET_XFER_OK)
7274                 return TARGET_XFER_OK;
7275               else
7276                 {
7277                   /* No use trying further, we know some memory starting
7278                      at MEMADDR isn't available.  */
7279                   *xfered_len = len;
7280                   return TARGET_XFER_UNAVAILABLE;
7281                 }
7282             }
7283
7284           /* Don't try to read more than how much is available, in
7285              case the target implements the deprecated QTro packet to
7286              cater for older GDBs (the target's knowledge of read-only
7287              sections may be outdated by now).  */
7288           len = VEC_index (mem_range_s, available, 0)->length;
7289
7290           do_cleanups (old_chain);
7291         }
7292     }
7293
7294   return remote_read_bytes_1 (memaddr, myaddr, len, xfered_len);
7295 }
7296
7297 \f
7298
7299 /* Sends a packet with content determined by the printf format string
7300    FORMAT and the remaining arguments, then gets the reply.  Returns
7301    whether the packet was a success, a failure, or unknown.  */
7302
7303 static enum packet_result remote_send_printf (const char *format, ...)
7304   ATTRIBUTE_PRINTF (1, 2);
7305
7306 static enum packet_result
7307 remote_send_printf (const char *format, ...)
7308 {
7309   struct remote_state *rs = get_remote_state ();
7310   int max_size = get_remote_packet_size ();
7311   va_list ap;
7312
7313   va_start (ap, format);
7314
7315   rs->buf[0] = '\0';
7316   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
7317     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
7318
7319   if (putpkt (rs->buf) < 0)
7320     error (_("Communication problem with target."));
7321
7322   rs->buf[0] = '\0';
7323   getpkt (&rs->buf, &rs->buf_size, 0);
7324
7325   return packet_check_result (rs->buf);
7326 }
7327
7328 static void
7329 restore_remote_timeout (void *p)
7330 {
7331   int value = *(int *)p;
7332
7333   remote_timeout = value;
7334 }
7335
7336 /* Flash writing can take quite some time.  We'll set
7337    effectively infinite timeout for flash operations.
7338    In future, we'll need to decide on a better approach.  */
7339 static const int remote_flash_timeout = 1000;
7340
7341 static void
7342 remote_flash_erase (struct target_ops *ops,
7343                     ULONGEST address, LONGEST length)
7344 {
7345   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
7346   int saved_remote_timeout = remote_timeout;
7347   enum packet_result ret;
7348   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7349                                           &saved_remote_timeout);
7350
7351   remote_timeout = remote_flash_timeout;
7352
7353   ret = remote_send_printf ("vFlashErase:%s,%s",
7354                             phex (address, addr_size),
7355                             phex (length, 4));
7356   switch (ret)
7357     {
7358     case PACKET_UNKNOWN:
7359       error (_("Remote target does not support flash erase"));
7360     case PACKET_ERROR:
7361       error (_("Error erasing flash with vFlashErase packet"));
7362     default:
7363       break;
7364     }
7365
7366   do_cleanups (back_to);
7367 }
7368
7369 static enum target_xfer_status
7370 remote_flash_write (struct target_ops *ops, ULONGEST address,
7371                     ULONGEST length, ULONGEST *xfered_len,
7372                     const gdb_byte *data)
7373 {
7374   int saved_remote_timeout = remote_timeout;
7375   enum target_xfer_status ret;
7376   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7377                                           &saved_remote_timeout);
7378
7379   remote_timeout = remote_flash_timeout;
7380   ret = remote_write_bytes_aux ("vFlashWrite:", address, data, length,
7381                                 xfered_len,'X', 0);
7382   do_cleanups (back_to);
7383
7384   return ret;
7385 }
7386
7387 static void
7388 remote_flash_done (struct target_ops *ops)
7389 {
7390   int saved_remote_timeout = remote_timeout;
7391   int ret;
7392   struct cleanup *back_to = make_cleanup (restore_remote_timeout,
7393                                           &saved_remote_timeout);
7394
7395   remote_timeout = remote_flash_timeout;
7396   ret = remote_send_printf ("vFlashDone");
7397   do_cleanups (back_to);
7398
7399   switch (ret)
7400     {
7401     case PACKET_UNKNOWN:
7402       error (_("Remote target does not support vFlashDone"));
7403     case PACKET_ERROR:
7404       error (_("Error finishing flash operation"));
7405     default:
7406       break;
7407     }
7408 }
7409
7410 static void
7411 remote_files_info (struct target_ops *ignore)
7412 {
7413   puts_filtered ("Debugging a target over a serial line.\n");
7414 }
7415 \f
7416 /* Stuff for dealing with the packets which are part of this protocol.
7417    See comment at top of file for details.  */
7418
7419 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
7420    error to higher layers.  Called when a serial error is detected.
7421    The exception message is STRING, followed by a colon and a blank,
7422    the system error message for errno at function entry and final dot
7423    for output compatibility with throw_perror_with_name.  */
7424
7425 static void
7426 unpush_and_perror (const char *string)
7427 {
7428   int saved_errno = errno;
7429
7430   remote_unpush_target ();
7431   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
7432                safe_strerror (saved_errno));
7433 }
7434
7435 /* Read a single character from the remote end.  */
7436
7437 static int
7438 readchar (int timeout)
7439 {
7440   int ch;
7441   struct remote_state *rs = get_remote_state ();
7442
7443   ch = serial_readchar (rs->remote_desc, timeout);
7444
7445   if (ch >= 0)
7446     return ch;
7447
7448   switch ((enum serial_rc) ch)
7449     {
7450     case SERIAL_EOF:
7451       remote_unpush_target ();
7452       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
7453       /* no return */
7454     case SERIAL_ERROR:
7455       unpush_and_perror (_("Remote communication error.  "
7456                            "Target disconnected."));
7457       /* no return */
7458     case SERIAL_TIMEOUT:
7459       break;
7460     }
7461   return ch;
7462 }
7463
7464 /* Wrapper for serial_write that closes the target and throws if
7465    writing fails.  */
7466
7467 static void
7468 remote_serial_write (const char *str, int len)
7469 {
7470   struct remote_state *rs = get_remote_state ();
7471
7472   if (serial_write (rs->remote_desc, str, len))
7473     {
7474       unpush_and_perror (_("Remote communication error.  "
7475                            "Target disconnected."));
7476     }
7477 }
7478
7479 /* Send the command in *BUF to the remote machine, and read the reply
7480    into *BUF.  Report an error if we get an error reply.  Resize
7481    *BUF using xrealloc if necessary to hold the result, and update
7482    *SIZEOF_BUF.  */
7483
7484 static void
7485 remote_send (char **buf,
7486              long *sizeof_buf)
7487 {
7488   putpkt (*buf);
7489   getpkt (buf, sizeof_buf, 0);
7490
7491   if ((*buf)[0] == 'E')
7492     error (_("Remote failure reply: %s"), *buf);
7493 }
7494
7495 /* Return a pointer to an xmalloc'ed string representing an escaped
7496    version of BUF, of len N.  E.g. \n is converted to \\n, \t to \\t,
7497    etc.  The caller is responsible for releasing the returned
7498    memory.  */
7499
7500 static char *
7501 escape_buffer (const char *buf, int n)
7502 {
7503   struct cleanup *old_chain;
7504   struct ui_file *stb;
7505   char *str;
7506
7507   stb = mem_fileopen ();
7508   old_chain = make_cleanup_ui_file_delete (stb);
7509
7510   fputstrn_unfiltered (buf, n, '\\', stb);
7511   str = ui_file_xstrdup (stb, NULL);
7512   do_cleanups (old_chain);
7513   return str;
7514 }
7515
7516 /* Display a null-terminated packet on stdout, for debugging, using C
7517    string notation.  */
7518
7519 static void
7520 print_packet (const char *buf)
7521 {
7522   puts_filtered ("\"");
7523   fputstr_filtered (buf, '"', gdb_stdout);
7524   puts_filtered ("\"");
7525 }
7526
7527 int
7528 putpkt (const char *buf)
7529 {
7530   return putpkt_binary (buf, strlen (buf));
7531 }
7532
7533 /* Send a packet to the remote machine, with error checking.  The data
7534    of the packet is in BUF.  The string in BUF can be at most
7535    get_remote_packet_size () - 5 to account for the $, # and checksum,
7536    and for a possible /0 if we are debugging (remote_debug) and want
7537    to print the sent packet as a string.  */
7538
7539 static int
7540 putpkt_binary (const char *buf, int cnt)
7541 {
7542   struct remote_state *rs = get_remote_state ();
7543   int i;
7544   unsigned char csum = 0;
7545   char *buf2 = alloca (cnt + 6);
7546
7547   int ch;
7548   int tcount = 0;
7549   char *p;
7550   char *message;
7551
7552   /* Catch cases like trying to read memory or listing threads while
7553      we're waiting for a stop reply.  The remote server wouldn't be
7554      ready to handle this request, so we'd hang and timeout.  We don't
7555      have to worry about this in synchronous mode, because in that
7556      case it's not possible to issue a command while the target is
7557      running.  This is not a problem in non-stop mode, because in that
7558      case, the stub is always ready to process serial input.  */
7559   if (!non_stop && target_is_async_p () && rs->waiting_for_stop_reply)
7560     {
7561       error (_("Cannot execute this command while the target is running.\n"
7562                "Use the \"interrupt\" command to stop the target\n"
7563                "and then try again."));
7564     }
7565
7566   /* We're sending out a new packet.  Make sure we don't look at a
7567      stale cached response.  */
7568   rs->cached_wait_status = 0;
7569
7570   /* Copy the packet into buffer BUF2, encapsulating it
7571      and giving it a checksum.  */
7572
7573   p = buf2;
7574   *p++ = '$';
7575
7576   for (i = 0; i < cnt; i++)
7577     {
7578       csum += buf[i];
7579       *p++ = buf[i];
7580     }
7581   *p++ = '#';
7582   *p++ = tohex ((csum >> 4) & 0xf);
7583   *p++ = tohex (csum & 0xf);
7584
7585   /* Send it over and over until we get a positive ack.  */
7586
7587   while (1)
7588     {
7589       int started_error_output = 0;
7590
7591       if (remote_debug)
7592         {
7593           struct cleanup *old_chain;
7594           char *str;
7595
7596           *p = '\0';
7597           str = escape_buffer (buf2, p - buf2);
7598           old_chain = make_cleanup (xfree, str);
7599           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s...", str);
7600           gdb_flush (gdb_stdlog);
7601           do_cleanups (old_chain);
7602         }
7603       remote_serial_write (buf2, p - buf2);
7604
7605       /* If this is a no acks version of the remote protocol, send the
7606          packet and move on.  */
7607       if (rs->noack_mode)
7608         break;
7609
7610       /* Read until either a timeout occurs (-2) or '+' is read.
7611          Handle any notification that arrives in the mean time.  */
7612       while (1)
7613         {
7614           ch = readchar (remote_timeout);
7615
7616           if (remote_debug)
7617             {
7618               switch (ch)
7619                 {
7620                 case '+':
7621                 case '-':
7622                 case SERIAL_TIMEOUT:
7623                 case '$':
7624                 case '%':
7625                   if (started_error_output)
7626                     {
7627                       putchar_unfiltered ('\n');
7628                       started_error_output = 0;
7629                     }
7630                 }
7631             }
7632
7633           switch (ch)
7634             {
7635             case '+':
7636               if (remote_debug)
7637                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
7638               return 1;
7639             case '-':
7640               if (remote_debug)
7641                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
7642               /* FALLTHROUGH */
7643             case SERIAL_TIMEOUT:
7644               tcount++;
7645               if (tcount > 3)
7646                 return 0;
7647               break;            /* Retransmit buffer.  */
7648             case '$':
7649               {
7650                 if (remote_debug)
7651                   fprintf_unfiltered (gdb_stdlog,
7652                                       "Packet instead of Ack, ignoring it\n");
7653                 /* It's probably an old response sent because an ACK
7654                    was lost.  Gobble up the packet and ack it so it
7655                    doesn't get retransmitted when we resend this
7656                    packet.  */
7657                 skip_frame ();
7658                 remote_serial_write ("+", 1);
7659                 continue;       /* Now, go look for +.  */
7660               }
7661
7662             case '%':
7663               {
7664                 int val;
7665
7666                 /* If we got a notification, handle it, and go back to looking
7667                    for an ack.  */
7668                 /* We've found the start of a notification.  Now
7669                    collect the data.  */
7670                 val = read_frame (&rs->buf, &rs->buf_size);
7671                 if (val >= 0)
7672                   {
7673                     if (remote_debug)
7674                       {
7675                         struct cleanup *old_chain;
7676                         char *str;
7677
7678                         str = escape_buffer (rs->buf, val);
7679                         old_chain = make_cleanup (xfree, str);
7680                         fprintf_unfiltered (gdb_stdlog,
7681                                             "  Notification received: %s\n",
7682                                             str);
7683                         do_cleanups (old_chain);
7684                       }
7685                     handle_notification (rs->notif_state, rs->buf);
7686                     /* We're in sync now, rewait for the ack.  */
7687                     tcount = 0;
7688                   }
7689                 else
7690                   {
7691                     if (remote_debug)
7692                       {
7693                         if (!started_error_output)
7694                           {
7695                             started_error_output = 1;
7696                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7697                           }
7698                         fputc_unfiltered (ch & 0177, gdb_stdlog);
7699                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
7700                       }
7701                   }
7702                 continue;
7703               }
7704               /* fall-through */
7705             default:
7706               if (remote_debug)
7707                 {
7708                   if (!started_error_output)
7709                     {
7710                       started_error_output = 1;
7711                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
7712                     }
7713                   fputc_unfiltered (ch & 0177, gdb_stdlog);
7714                 }
7715               continue;
7716             }
7717           break;                /* Here to retransmit.  */
7718         }
7719
7720 #if 0
7721       /* This is wrong.  If doing a long backtrace, the user should be
7722          able to get out next time we call QUIT, without anything as
7723          violent as interrupt_query.  If we want to provide a way out of
7724          here without getting to the next QUIT, it should be based on
7725          hitting ^C twice as in remote_wait.  */
7726       if (quit_flag)
7727         {
7728           quit_flag = 0;
7729           interrupt_query ();
7730         }
7731 #endif
7732     }
7733   return 0;
7734 }
7735
7736 /* Come here after finding the start of a frame when we expected an
7737    ack.  Do our best to discard the rest of this packet.  */
7738
7739 static void
7740 skip_frame (void)
7741 {
7742   int c;
7743
7744   while (1)
7745     {
7746       c = readchar (remote_timeout);
7747       switch (c)
7748         {
7749         case SERIAL_TIMEOUT:
7750           /* Nothing we can do.  */
7751           return;
7752         case '#':
7753           /* Discard the two bytes of checksum and stop.  */
7754           c = readchar (remote_timeout);
7755           if (c >= 0)
7756             c = readchar (remote_timeout);
7757
7758           return;
7759         case '*':               /* Run length encoding.  */
7760           /* Discard the repeat count.  */
7761           c = readchar (remote_timeout);
7762           if (c < 0)
7763             return;
7764           break;
7765         default:
7766           /* A regular character.  */
7767           break;
7768         }
7769     }
7770 }
7771
7772 /* Come here after finding the start of the frame.  Collect the rest
7773    into *BUF, verifying the checksum, length, and handling run-length
7774    compression.  NUL terminate the buffer.  If there is not enough room,
7775    expand *BUF using xrealloc.
7776
7777    Returns -1 on error, number of characters in buffer (ignoring the
7778    trailing NULL) on success. (could be extended to return one of the
7779    SERIAL status indications).  */
7780
7781 static long
7782 read_frame (char **buf_p,
7783             long *sizeof_buf)
7784 {
7785   unsigned char csum;
7786   long bc;
7787   int c;
7788   char *buf = *buf_p;
7789   struct remote_state *rs = get_remote_state ();
7790
7791   csum = 0;
7792   bc = 0;
7793
7794   while (1)
7795     {
7796       c = readchar (remote_timeout);
7797       switch (c)
7798         {
7799         case SERIAL_TIMEOUT:
7800           if (remote_debug)
7801             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
7802           return -1;
7803         case '$':
7804           if (remote_debug)
7805             fputs_filtered ("Saw new packet start in middle of old one\n",
7806                             gdb_stdlog);
7807           return -1;            /* Start a new packet, count retries.  */
7808         case '#':
7809           {
7810             unsigned char pktcsum;
7811             int check_0 = 0;
7812             int check_1 = 0;
7813
7814             buf[bc] = '\0';
7815
7816             check_0 = readchar (remote_timeout);
7817             if (check_0 >= 0)
7818               check_1 = readchar (remote_timeout);
7819
7820             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
7821               {
7822                 if (remote_debug)
7823                   fputs_filtered ("Timeout in checksum, retrying\n",
7824                                   gdb_stdlog);
7825                 return -1;
7826               }
7827             else if (check_0 < 0 || check_1 < 0)
7828               {
7829                 if (remote_debug)
7830                   fputs_filtered ("Communication error in checksum\n",
7831                                   gdb_stdlog);
7832                 return -1;
7833               }
7834
7835             /* Don't recompute the checksum; with no ack packets we
7836                don't have any way to indicate a packet retransmission
7837                is necessary.  */
7838             if (rs->noack_mode)
7839               return bc;
7840
7841             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
7842             if (csum == pktcsum)
7843               return bc;
7844
7845             if (remote_debug)
7846               {
7847                 struct cleanup *old_chain;
7848                 char *str;
7849
7850                 str = escape_buffer (buf, bc);
7851                 old_chain = make_cleanup (xfree, str);
7852                 fprintf_unfiltered (gdb_stdlog,
7853                                     "Bad checksum, sentsum=0x%x, "
7854                                     "csum=0x%x, buf=%s\n",
7855                                     pktcsum, csum, str);
7856                 do_cleanups (old_chain);
7857               }
7858             /* Number of characters in buffer ignoring trailing
7859                NULL.  */
7860             return -1;
7861           }
7862         case '*':               /* Run length encoding.  */
7863           {
7864             int repeat;
7865
7866             csum += c;
7867             c = readchar (remote_timeout);
7868             csum += c;
7869             repeat = c - ' ' + 3;       /* Compute repeat count.  */
7870
7871             /* The character before ``*'' is repeated.  */
7872
7873             if (repeat > 0 && repeat <= 255 && bc > 0)
7874               {
7875                 if (bc + repeat - 1 >= *sizeof_buf - 1)
7876                   {
7877                     /* Make some more room in the buffer.  */
7878                     *sizeof_buf += repeat;
7879                     *buf_p = xrealloc (*buf_p, *sizeof_buf);
7880                     buf = *buf_p;
7881                   }
7882
7883                 memset (&buf[bc], buf[bc - 1], repeat);
7884                 bc += repeat;
7885                 continue;
7886               }
7887
7888             buf[bc] = '\0';
7889             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
7890             return -1;
7891           }
7892         default:
7893           if (bc >= *sizeof_buf - 1)
7894             {
7895               /* Make some more room in the buffer.  */
7896               *sizeof_buf *= 2;
7897               *buf_p = xrealloc (*buf_p, *sizeof_buf);
7898               buf = *buf_p;
7899             }
7900
7901           buf[bc++] = c;
7902           csum += c;
7903           continue;
7904         }
7905     }
7906 }
7907
7908 /* Read a packet from the remote machine, with error checking, and
7909    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
7910    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
7911    rather than timing out; this is used (in synchronous mode) to wait
7912    for a target that is is executing user code to stop.  */
7913 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
7914    don't have to change all the calls to getpkt to deal with the
7915    return value, because at the moment I don't know what the right
7916    thing to do it for those.  */
7917 void
7918 getpkt (char **buf,
7919         long *sizeof_buf,
7920         int forever)
7921 {
7922   int timed_out;
7923
7924   timed_out = getpkt_sane (buf, sizeof_buf, forever);
7925 }
7926
7927
7928 /* Read a packet from the remote machine, with error checking, and
7929    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
7930    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
7931    rather than timing out; this is used (in synchronous mode) to wait
7932    for a target that is is executing user code to stop.  If FOREVER ==
7933    0, this function is allowed to time out gracefully and return an
7934    indication of this to the caller.  Otherwise return the number of
7935    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
7936    enough reason to return to the caller.  *IS_NOTIF is an output
7937    boolean that indicates whether *BUF holds a notification or not
7938    (a regular packet).  */
7939
7940 static int
7941 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
7942                         int expecting_notif, int *is_notif)
7943 {
7944   struct remote_state *rs = get_remote_state ();
7945   int c;
7946   int tries;
7947   int timeout;
7948   int val = -1;
7949
7950   /* We're reading a new response.  Make sure we don't look at a
7951      previously cached response.  */
7952   rs->cached_wait_status = 0;
7953
7954   strcpy (*buf, "timeout");
7955
7956   if (forever)
7957     timeout = watchdog > 0 ? watchdog : -1;
7958   else if (expecting_notif)
7959     timeout = 0; /* There should already be a char in the buffer.  If
7960                     not, bail out.  */
7961   else
7962     timeout = remote_timeout;
7963
7964 #define MAX_TRIES 3
7965
7966   /* Process any number of notifications, and then return when
7967      we get a packet.  */
7968   for (;;)
7969     {
7970       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
7971          times.  */
7972       for (tries = 1; tries <= MAX_TRIES; tries++)
7973         {
7974           /* This can loop forever if the remote side sends us
7975              characters continuously, but if it pauses, we'll get
7976              SERIAL_TIMEOUT from readchar because of timeout.  Then
7977              we'll count that as a retry.
7978
7979              Note that even when forever is set, we will only wait
7980              forever prior to the start of a packet.  After that, we
7981              expect characters to arrive at a brisk pace.  They should
7982              show up within remote_timeout intervals.  */
7983           do
7984             c = readchar (timeout);
7985           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
7986
7987           if (c == SERIAL_TIMEOUT)
7988             {
7989               if (expecting_notif)
7990                 return -1; /* Don't complain, it's normal to not get
7991                               anything in this case.  */
7992
7993               if (forever)      /* Watchdog went off?  Kill the target.  */
7994                 {
7995                   QUIT;
7996                   remote_unpush_target ();
7997                   throw_error (TARGET_CLOSE_ERROR,
7998                                _("Watchdog timeout has expired.  "
7999                                  "Target detached."));
8000                 }
8001               if (remote_debug)
8002                 fputs_filtered ("Timed out.\n", gdb_stdlog);
8003             }
8004           else
8005             {
8006               /* We've found the start of a packet or notification.
8007                  Now collect the data.  */
8008               val = read_frame (buf, sizeof_buf);
8009               if (val >= 0)
8010                 break;
8011             }
8012
8013           remote_serial_write ("-", 1);
8014         }
8015
8016       if (tries > MAX_TRIES)
8017         {
8018           /* We have tried hard enough, and just can't receive the
8019              packet/notification.  Give up.  */
8020           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
8021
8022           /* Skip the ack char if we're in no-ack mode.  */
8023           if (!rs->noack_mode)
8024             remote_serial_write ("+", 1);
8025           return -1;
8026         }
8027
8028       /* If we got an ordinary packet, return that to our caller.  */
8029       if (c == '$')
8030         {
8031           if (remote_debug)
8032             {
8033              struct cleanup *old_chain;
8034              char *str;
8035
8036              str = escape_buffer (*buf, val);
8037              old_chain = make_cleanup (xfree, str);
8038              fprintf_unfiltered (gdb_stdlog, "Packet received: %s\n", str);
8039              do_cleanups (old_chain);
8040             }
8041
8042           /* Skip the ack char if we're in no-ack mode.  */
8043           if (!rs->noack_mode)
8044             remote_serial_write ("+", 1);
8045           if (is_notif != NULL)
8046             *is_notif = 0;
8047           return val;
8048         }
8049
8050        /* If we got a notification, handle it, and go back to looking
8051          for a packet.  */
8052       else
8053         {
8054           gdb_assert (c == '%');
8055
8056           if (remote_debug)
8057             {
8058               struct cleanup *old_chain;
8059               char *str;
8060
8061               str = escape_buffer (*buf, val);
8062               old_chain = make_cleanup (xfree, str);
8063               fprintf_unfiltered (gdb_stdlog,
8064                                   "  Notification received: %s\n",
8065                                   str);
8066               do_cleanups (old_chain);
8067             }
8068           if (is_notif != NULL)
8069             *is_notif = 1;
8070
8071           handle_notification (rs->notif_state, *buf);
8072
8073           /* Notifications require no acknowledgement.  */
8074
8075           if (expecting_notif)
8076             return val;
8077         }
8078     }
8079 }
8080
8081 static int
8082 getpkt_sane (char **buf, long *sizeof_buf, int forever)
8083 {
8084   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
8085 }
8086
8087 static int
8088 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
8089                       int *is_notif)
8090 {
8091   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
8092                                  is_notif);
8093 }
8094
8095 /* Check whether EVENT is a fork event for the process specified
8096    by the pid passed in DATA, and if it is, kill the fork child.  */
8097
8098 static int
8099 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
8100                             QUEUE_ITER (stop_reply_p) *iter,
8101                             stop_reply_p event,
8102                             void *data)
8103 {
8104   struct queue_iter_param *param = data;
8105   int parent_pid = *(int *) param->input;
8106
8107   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
8108     {
8109       struct remote_state *rs = get_remote_state ();
8110       int child_pid = ptid_get_pid (event->ws.value.related_pid);
8111       int res;
8112
8113       res = remote_vkill (child_pid, rs);
8114       if (res != 0)
8115         error (_("Can't kill fork child process %d"), child_pid);
8116     }
8117
8118   return 1;
8119 }
8120
8121 /* Kill any new fork children of process PID that haven't been
8122    processed by follow_fork.  */
8123
8124 static void
8125 kill_new_fork_children (int pid, struct remote_state *rs)
8126 {
8127   struct thread_info *thread;
8128   struct notif_client *notif = &notif_client_stop;
8129   struct queue_iter_param param;
8130
8131   /* Kill the fork child threads of any threads in process PID
8132      that are stopped at a fork event.  */
8133   ALL_NON_EXITED_THREADS (thread)
8134     {
8135       struct target_waitstatus *ws = &thread->pending_follow;
8136
8137       if (is_pending_fork_parent (ws, pid, thread->ptid))
8138         {
8139           struct remote_state *rs = get_remote_state ();
8140           int child_pid = ptid_get_pid (ws->value.related_pid);
8141           int res;
8142
8143           res = remote_vkill (child_pid, rs);
8144           if (res != 0)
8145             error (_("Can't kill fork child process %d"), child_pid);
8146         }
8147     }
8148
8149   /* Check for any pending fork events (not reported or processed yet)
8150      in process PID and kill those fork child threads as well.  */
8151   remote_notif_get_pending_events (notif);
8152   param.input = &pid;
8153   param.output = NULL;
8154   QUEUE_iterate (stop_reply_p, stop_reply_queue,
8155                  kill_child_of_pending_fork, &param);
8156 }
8157
8158 \f
8159 static void
8160 remote_kill (struct target_ops *ops)
8161 {
8162
8163   /* Catch errors so the user can quit from gdb even when we
8164      aren't on speaking terms with the remote system.  */
8165   TRY
8166     {
8167       putpkt ("k");
8168     }
8169   CATCH (ex, RETURN_MASK_ERROR)
8170     {
8171       if (ex.error == TARGET_CLOSE_ERROR)
8172         {
8173           /* If we got an (EOF) error that caused the target
8174              to go away, then we're done, that's what we wanted.
8175              "k" is susceptible to cause a premature EOF, given
8176              that the remote server isn't actually required to
8177              reply to "k", and it can happen that it doesn't
8178              even get to reply ACK to the "k".  */
8179           return;
8180         }
8181
8182         /* Otherwise, something went wrong.  We didn't actually kill
8183            the target.  Just propagate the exception, and let the
8184            user or higher layers decide what to do.  */
8185         throw_exception (ex);
8186     }
8187   END_CATCH
8188
8189   /* We've killed the remote end, we get to mourn it.  Since this is
8190      target remote, single-process, mourning the inferior also
8191      unpushes remote_ops.  */
8192   target_mourn_inferior ();
8193 }
8194
8195 static int
8196 remote_vkill (int pid, struct remote_state *rs)
8197 {
8198   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
8199     return -1;
8200
8201   /* Tell the remote target to detach.  */
8202   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
8203   putpkt (rs->buf);
8204   getpkt (&rs->buf, &rs->buf_size, 0);
8205
8206   switch (packet_ok (rs->buf,
8207                      &remote_protocol_packets[PACKET_vKill]))
8208     {
8209     case PACKET_OK:
8210       return 0;
8211     case PACKET_ERROR:
8212       return 1;
8213     case PACKET_UNKNOWN:
8214       return -1;
8215     default:
8216       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8217     }
8218 }
8219
8220 static void
8221 extended_remote_kill (struct target_ops *ops)
8222 {
8223   int res;
8224   int pid = ptid_get_pid (inferior_ptid);
8225   struct remote_state *rs = get_remote_state ();
8226
8227   /* If we're stopped while forking and we haven't followed yet, kill the
8228      child task.  We need to do this before killing the parent task
8229      because if this is a vfork then the parent will be sleeping.  */
8230   kill_new_fork_children (pid, rs);
8231
8232   res = remote_vkill (pid, rs);
8233   if (res == -1 && !(rs->extended && remote_multi_process_p (rs)))
8234     {
8235       /* Don't try 'k' on a multi-process aware stub -- it has no way
8236          to specify the pid.  */
8237
8238       putpkt ("k");
8239 #if 0
8240       getpkt (&rs->buf, &rs->buf_size, 0);
8241       if (rs->buf[0] != 'O' || rs->buf[0] != 'K')
8242         res = 1;
8243 #else
8244       /* Don't wait for it to die.  I'm not really sure it matters whether
8245          we do or not.  For the existing stubs, kill is a noop.  */
8246       res = 0;
8247 #endif
8248     }
8249
8250   if (res != 0)
8251     error (_("Can't kill process"));
8252
8253   target_mourn_inferior ();
8254 }
8255
8256 static void
8257 remote_mourn (struct target_ops *target)
8258 {
8259   unpush_target (target);
8260
8261   /* remote_close takes care of doing most of the clean up.  */
8262   generic_mourn_inferior ();
8263 }
8264
8265 static void
8266 extended_remote_mourn (struct target_ops *target)
8267 {
8268   struct remote_state *rs = get_remote_state ();
8269
8270   /* In case we got here due to an error, but we're going to stay
8271      connected.  */
8272   rs->waiting_for_stop_reply = 0;
8273
8274   /* If the current general thread belonged to the process we just
8275      detached from or has exited, the remote side current general
8276      thread becomes undefined.  Considering a case like this:
8277
8278      - We just got here due to a detach.
8279      - The process that we're detaching from happens to immediately
8280        report a global breakpoint being hit in non-stop mode, in the
8281        same thread we had selected before.
8282      - GDB attaches to this process again.
8283      - This event happens to be the next event we handle.
8284
8285      GDB would consider that the current general thread didn't need to
8286      be set on the stub side (with Hg), since for all it knew,
8287      GENERAL_THREAD hadn't changed.
8288
8289      Notice that although in all-stop mode, the remote server always
8290      sets the current thread to the thread reporting the stop event,
8291      that doesn't happen in non-stop mode; in non-stop, the stub *must
8292      not* change the current thread when reporting a breakpoint hit,
8293      due to the decoupling of event reporting and event handling.
8294
8295      To keep things simple, we always invalidate our notion of the
8296      current thread.  */
8297   record_currthread (rs, minus_one_ptid);
8298
8299   /* Unlike "target remote", we do not want to unpush the target; then
8300      the next time the user says "run", we won't be connected.  */
8301
8302   /* Call common code to mark the inferior as not running.      */
8303   generic_mourn_inferior ();
8304
8305   if (!have_inferiors ())
8306     {
8307       if (!remote_multi_process_p (rs))
8308         {
8309           /* Check whether the target is running now - some remote stubs
8310              automatically restart after kill.  */
8311           putpkt ("?");
8312           getpkt (&rs->buf, &rs->buf_size, 0);
8313
8314           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
8315             {
8316               /* Assume that the target has been restarted.  Set
8317                  inferior_ptid so that bits of core GDB realizes
8318                  there's something here, e.g., so that the user can
8319                  say "kill" again.  */
8320               inferior_ptid = magic_null_ptid;
8321             }
8322         }
8323     }
8324 }
8325
8326 static int
8327 extended_remote_supports_disable_randomization (struct target_ops *self)
8328 {
8329   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
8330 }
8331
8332 static void
8333 extended_remote_disable_randomization (int val)
8334 {
8335   struct remote_state *rs = get_remote_state ();
8336   char *reply;
8337
8338   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
8339              val);
8340   putpkt (rs->buf);
8341   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
8342   if (*reply == '\0')
8343     error (_("Target does not support QDisableRandomization."));
8344   if (strcmp (reply, "OK") != 0)
8345     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
8346 }
8347
8348 static int
8349 extended_remote_run (char *args)
8350 {
8351   struct remote_state *rs = get_remote_state ();
8352   int len;
8353
8354   /* If the user has disabled vRun support, or we have detected that
8355      support is not available, do not try it.  */
8356   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
8357     return -1;
8358
8359   strcpy (rs->buf, "vRun;");
8360   len = strlen (rs->buf);
8361
8362   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
8363     error (_("Remote file name too long for run packet"));
8364   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
8365                       strlen (remote_exec_file));
8366
8367   gdb_assert (args != NULL);
8368   if (*args)
8369     {
8370       struct cleanup *back_to;
8371       int i;
8372       char **argv;
8373
8374       argv = gdb_buildargv (args);
8375       back_to = make_cleanup_freeargv (argv);
8376       for (i = 0; argv[i] != NULL; i++)
8377         {
8378           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
8379             error (_("Argument list too long for run packet"));
8380           rs->buf[len++] = ';';
8381           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
8382                               strlen (argv[i]));
8383         }
8384       do_cleanups (back_to);
8385     }
8386
8387   rs->buf[len++] = '\0';
8388
8389   putpkt (rs->buf);
8390   getpkt (&rs->buf, &rs->buf_size, 0);
8391
8392   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
8393     {
8394     case PACKET_OK:
8395       /* We have a wait response.  All is well.  */
8396       return 0;
8397     case PACKET_UNKNOWN:
8398       return -1;
8399     case PACKET_ERROR:
8400       if (remote_exec_file[0] == '\0')
8401         error (_("Running the default executable on the remote target failed; "
8402                  "try \"set remote exec-file\"?"));
8403       else
8404         error (_("Running \"%s\" on the remote target failed"),
8405                remote_exec_file);
8406     default:
8407       gdb_assert_not_reached (_("bad switch"));
8408     }
8409 }
8410
8411 /* In the extended protocol we want to be able to do things like
8412    "run" and have them basically work as expected.  So we need
8413    a special create_inferior function.  We support changing the
8414    executable file and the command line arguments, but not the
8415    environment.  */
8416
8417 static void
8418 extended_remote_create_inferior (struct target_ops *ops,
8419                                  char *exec_file, char *args,
8420                                  char **env, int from_tty)
8421 {
8422   int run_worked;
8423   char *stop_reply;
8424   struct remote_state *rs = get_remote_state ();
8425
8426   /* If running asynchronously, register the target file descriptor
8427      with the event loop.  */
8428   if (target_can_async_p ())
8429     target_async (1);
8430
8431   /* Disable address space randomization if requested (and supported).  */
8432   if (extended_remote_supports_disable_randomization (ops))
8433     extended_remote_disable_randomization (disable_randomization);
8434
8435   /* Now restart the remote server.  */
8436   run_worked = extended_remote_run (args) != -1;
8437   if (!run_worked)
8438     {
8439       /* vRun was not supported.  Fail if we need it to do what the
8440          user requested.  */
8441       if (remote_exec_file[0])
8442         error (_("Remote target does not support \"set remote exec-file\""));
8443       if (args[0])
8444         error (_("Remote target does not support \"set args\" or run <ARGS>"));
8445
8446       /* Fall back to "R".  */
8447       extended_remote_restart ();
8448     }
8449
8450   if (!have_inferiors ())
8451     {
8452       /* Clean up from the last time we ran, before we mark the target
8453          running again.  This will mark breakpoints uninserted, and
8454          get_offsets may insert breakpoints.  */
8455       init_thread_list ();
8456       init_wait_for_inferior ();
8457     }
8458
8459   /* vRun's success return is a stop reply.  */
8460   stop_reply = run_worked ? rs->buf : NULL;
8461   add_current_inferior_and_thread (stop_reply);
8462
8463   /* Get updated offsets, if the stub uses qOffsets.  */
8464   get_offsets ();
8465 }
8466 \f
8467
8468 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
8469    the list of conditions (in agent expression bytecode format), if any, the
8470    target needs to evaluate.  The output is placed into the packet buffer
8471    started from BUF and ended at BUF_END.  */
8472
8473 static int
8474 remote_add_target_side_condition (struct gdbarch *gdbarch,
8475                                   struct bp_target_info *bp_tgt, char *buf,
8476                                   char *buf_end)
8477 {
8478   struct agent_expr *aexpr = NULL;
8479   int i, ix;
8480   char *pkt;
8481   char *buf_start = buf;
8482
8483   if (VEC_empty (agent_expr_p, bp_tgt->conditions))
8484     return 0;
8485
8486   buf += strlen (buf);
8487   xsnprintf (buf, buf_end - buf, "%s", ";");
8488   buf++;
8489
8490   /* Send conditions to the target and free the vector.  */
8491   for (ix = 0;
8492        VEC_iterate (agent_expr_p, bp_tgt->conditions, ix, aexpr);
8493        ix++)
8494     {
8495       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
8496       buf += strlen (buf);
8497       for (i = 0; i < aexpr->len; ++i)
8498         buf = pack_hex_byte (buf, aexpr->buf[i]);
8499       *buf = '\0';
8500     }
8501   return 0;
8502 }
8503
8504 static void
8505 remote_add_target_side_commands (struct gdbarch *gdbarch,
8506                                  struct bp_target_info *bp_tgt, char *buf)
8507 {
8508   struct agent_expr *aexpr = NULL;
8509   int i, ix;
8510
8511   if (VEC_empty (agent_expr_p, bp_tgt->tcommands))
8512     return;
8513
8514   buf += strlen (buf);
8515
8516   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
8517   buf += strlen (buf);
8518
8519   /* Concatenate all the agent expressions that are commands into the
8520      cmds parameter.  */
8521   for (ix = 0;
8522        VEC_iterate (agent_expr_p, bp_tgt->tcommands, ix, aexpr);
8523        ix++)
8524     {
8525       sprintf (buf, "X%x,", aexpr->len);
8526       buf += strlen (buf);
8527       for (i = 0; i < aexpr->len; ++i)
8528         buf = pack_hex_byte (buf, aexpr->buf[i]);
8529       *buf = '\0';
8530     }
8531 }
8532
8533 /* Insert a breakpoint.  On targets that have software breakpoint
8534    support, we ask the remote target to do the work; on targets
8535    which don't, we insert a traditional memory breakpoint.  */
8536
8537 static int
8538 remote_insert_breakpoint (struct target_ops *ops,
8539                           struct gdbarch *gdbarch,
8540                           struct bp_target_info *bp_tgt)
8541 {
8542   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
8543      If it succeeds, then set the support to PACKET_ENABLE.  If it
8544      fails, and the user has explicitly requested the Z support then
8545      report an error, otherwise, mark it disabled and go on.  */
8546
8547   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8548     {
8549       CORE_ADDR addr = bp_tgt->reqstd_address;
8550       struct remote_state *rs;
8551       char *p, *endbuf;
8552       int bpsize;
8553       struct condition_list *cond = NULL;
8554
8555       /* Make sure the remote is pointing at the right process, if
8556          necessary.  */
8557       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8558         set_general_process ();
8559
8560       gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8561
8562       rs = get_remote_state ();
8563       p = rs->buf;
8564       endbuf = rs->buf + get_remote_packet_size ();
8565
8566       *(p++) = 'Z';
8567       *(p++) = '0';
8568       *(p++) = ',';
8569       addr = (ULONGEST) remote_address_masked (addr);
8570       p += hexnumstr (p, addr);
8571       xsnprintf (p, endbuf - p, ",%d", bpsize);
8572
8573       if (remote_supports_cond_breakpoints (ops))
8574         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8575
8576       if (remote_can_run_breakpoint_commands (ops))
8577         remote_add_target_side_commands (gdbarch, bp_tgt, p);
8578
8579       putpkt (rs->buf);
8580       getpkt (&rs->buf, &rs->buf_size, 0);
8581
8582       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
8583         {
8584         case PACKET_ERROR:
8585           return -1;
8586         case PACKET_OK:
8587           bp_tgt->placed_address = addr;
8588           bp_tgt->placed_size = bpsize;
8589           return 0;
8590         case PACKET_UNKNOWN:
8591           break;
8592         }
8593     }
8594
8595   /* If this breakpoint has target-side commands but this stub doesn't
8596      support Z0 packets, throw error.  */
8597   if (!VEC_empty (agent_expr_p, bp_tgt->tcommands))
8598     throw_error (NOT_SUPPORTED_ERROR, _("\
8599 Target doesn't support breakpoints that have target side commands."));
8600
8601   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
8602 }
8603
8604 static int
8605 remote_remove_breakpoint (struct target_ops *ops,
8606                           struct gdbarch *gdbarch,
8607                           struct bp_target_info *bp_tgt)
8608 {
8609   CORE_ADDR addr = bp_tgt->placed_address;
8610   struct remote_state *rs = get_remote_state ();
8611
8612   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
8613     {
8614       char *p = rs->buf;
8615       char *endbuf = rs->buf + get_remote_packet_size ();
8616
8617       /* Make sure the remote is pointing at the right process, if
8618          necessary.  */
8619       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8620         set_general_process ();
8621
8622       *(p++) = 'z';
8623       *(p++) = '0';
8624       *(p++) = ',';
8625
8626       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
8627       p += hexnumstr (p, addr);
8628       xsnprintf (p, endbuf - p, ",%d", bp_tgt->placed_size);
8629
8630       putpkt (rs->buf);
8631       getpkt (&rs->buf, &rs->buf_size, 0);
8632
8633       return (rs->buf[0] == 'E');
8634     }
8635
8636   return memory_remove_breakpoint (ops, gdbarch, bp_tgt);
8637 }
8638
8639 static int
8640 watchpoint_to_Z_packet (int type)
8641 {
8642   switch (type)
8643     {
8644     case hw_write:
8645       return Z_PACKET_WRITE_WP;
8646       break;
8647     case hw_read:
8648       return Z_PACKET_READ_WP;
8649       break;
8650     case hw_access:
8651       return Z_PACKET_ACCESS_WP;
8652       break;
8653     default:
8654       internal_error (__FILE__, __LINE__,
8655                       _("hw_bp_to_z: bad watchpoint type %d"), type);
8656     }
8657 }
8658
8659 static int
8660 remote_insert_watchpoint (struct target_ops *self,
8661                           CORE_ADDR addr, int len, int type,
8662                           struct expression *cond)
8663 {
8664   struct remote_state *rs = get_remote_state ();
8665   char *endbuf = rs->buf + get_remote_packet_size ();
8666   char *p;
8667   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8668
8669   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8670     return 1;
8671
8672   /* Make sure the remote is pointing at the right process, if
8673      necessary.  */
8674   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8675     set_general_process ();
8676
8677   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
8678   p = strchr (rs->buf, '\0');
8679   addr = remote_address_masked (addr);
8680   p += hexnumstr (p, (ULONGEST) addr);
8681   xsnprintf (p, endbuf - p, ",%x", len);
8682
8683   putpkt (rs->buf);
8684   getpkt (&rs->buf, &rs->buf_size, 0);
8685
8686   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8687     {
8688     case PACKET_ERROR:
8689       return -1;
8690     case PACKET_UNKNOWN:
8691       return 1;
8692     case PACKET_OK:
8693       return 0;
8694     }
8695   internal_error (__FILE__, __LINE__,
8696                   _("remote_insert_watchpoint: reached end of function"));
8697 }
8698
8699 static int
8700 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
8701                                      CORE_ADDR start, int length)
8702 {
8703   CORE_ADDR diff = remote_address_masked (addr - start);
8704
8705   return diff < length;
8706 }
8707
8708
8709 static int
8710 remote_remove_watchpoint (struct target_ops *self,
8711                           CORE_ADDR addr, int len, int type,
8712                           struct expression *cond)
8713 {
8714   struct remote_state *rs = get_remote_state ();
8715   char *endbuf = rs->buf + get_remote_packet_size ();
8716   char *p;
8717   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
8718
8719   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
8720     return -1;
8721
8722   /* Make sure the remote is pointing at the right process, if
8723      necessary.  */
8724   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8725     set_general_process ();
8726
8727   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
8728   p = strchr (rs->buf, '\0');
8729   addr = remote_address_masked (addr);
8730   p += hexnumstr (p, (ULONGEST) addr);
8731   xsnprintf (p, endbuf - p, ",%x", len);
8732   putpkt (rs->buf);
8733   getpkt (&rs->buf, &rs->buf_size, 0);
8734
8735   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
8736     {
8737     case PACKET_ERROR:
8738     case PACKET_UNKNOWN:
8739       return -1;
8740     case PACKET_OK:
8741       return 0;
8742     }
8743   internal_error (__FILE__, __LINE__,
8744                   _("remote_remove_watchpoint: reached end of function"));
8745 }
8746
8747
8748 int remote_hw_watchpoint_limit = -1;
8749 int remote_hw_watchpoint_length_limit = -1;
8750 int remote_hw_breakpoint_limit = -1;
8751
8752 static int
8753 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
8754                                     CORE_ADDR addr, int len)
8755 {
8756   if (remote_hw_watchpoint_length_limit == 0)
8757     return 0;
8758   else if (remote_hw_watchpoint_length_limit < 0)
8759     return 1;
8760   else if (len <= remote_hw_watchpoint_length_limit)
8761     return 1;
8762   else
8763     return 0;
8764 }
8765
8766 static int
8767 remote_check_watch_resources (struct target_ops *self,
8768                               int type, int cnt, int ot)
8769 {
8770   if (type == bp_hardware_breakpoint)
8771     {
8772       if (remote_hw_breakpoint_limit == 0)
8773         return 0;
8774       else if (remote_hw_breakpoint_limit < 0)
8775         return 1;
8776       else if (cnt <= remote_hw_breakpoint_limit)
8777         return 1;
8778     }
8779   else
8780     {
8781       if (remote_hw_watchpoint_limit == 0)
8782         return 0;
8783       else if (remote_hw_watchpoint_limit < 0)
8784         return 1;
8785       else if (ot)
8786         return -1;
8787       else if (cnt <= remote_hw_watchpoint_limit)
8788         return 1;
8789     }
8790   return -1;
8791 }
8792
8793 /* The to_stopped_by_sw_breakpoint method of target remote.  */
8794
8795 static int
8796 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
8797 {
8798   struct remote_state *rs = get_remote_state ();
8799
8800   return rs->stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
8801 }
8802
8803 /* The to_supports_stopped_by_sw_breakpoint method of target
8804    remote.  */
8805
8806 static int
8807 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
8808 {
8809   struct remote_state *rs = get_remote_state ();
8810
8811   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
8812 }
8813
8814 /* The to_stopped_by_hw_breakpoint method of target remote.  */
8815
8816 static int
8817 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
8818 {
8819   struct remote_state *rs = get_remote_state ();
8820
8821   return rs->stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
8822 }
8823
8824 /* The to_supports_stopped_by_hw_breakpoint method of target
8825    remote.  */
8826
8827 static int
8828 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
8829 {
8830   struct remote_state *rs = get_remote_state ();
8831
8832   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
8833 }
8834
8835 static int
8836 remote_stopped_by_watchpoint (struct target_ops *ops)
8837 {
8838   struct remote_state *rs = get_remote_state ();
8839
8840   return rs->stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
8841 }
8842
8843 static int
8844 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
8845 {
8846   struct remote_state *rs = get_remote_state ();
8847   int rc = 0;
8848
8849   if (remote_stopped_by_watchpoint (target))
8850     {
8851       *addr_p = rs->remote_watch_data_address;
8852       rc = 1;
8853     }
8854
8855   return rc;
8856 }
8857
8858
8859 static int
8860 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8861                              struct bp_target_info *bp_tgt)
8862 {
8863   CORE_ADDR addr = bp_tgt->reqstd_address;
8864   struct remote_state *rs;
8865   char *p, *endbuf;
8866   char *message;
8867   int bpsize;
8868
8869   /* The length field should be set to the size of a breakpoint
8870      instruction, even though we aren't inserting one ourselves.  */
8871
8872   gdbarch_remote_breakpoint_from_pc (gdbarch, &addr, &bpsize);
8873
8874   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8875     return -1;
8876
8877   /* Make sure the remote is pointing at the right process, if
8878      necessary.  */
8879   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8880     set_general_process ();
8881
8882   rs = get_remote_state ();
8883   p = rs->buf;
8884   endbuf = rs->buf + get_remote_packet_size ();
8885
8886   *(p++) = 'Z';
8887   *(p++) = '1';
8888   *(p++) = ',';
8889
8890   addr = remote_address_masked (addr);
8891   p += hexnumstr (p, (ULONGEST) addr);
8892   xsnprintf (p, endbuf - p, ",%x", bpsize);
8893
8894   if (remote_supports_cond_breakpoints (self))
8895     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
8896
8897   if (remote_can_run_breakpoint_commands (self))
8898     remote_add_target_side_commands (gdbarch, bp_tgt, p);
8899
8900   putpkt (rs->buf);
8901   getpkt (&rs->buf, &rs->buf_size, 0);
8902
8903   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8904     {
8905     case PACKET_ERROR:
8906       if (rs->buf[1] == '.')
8907         {
8908           message = strchr (rs->buf + 2, '.');
8909           if (message)
8910             error (_("Remote failure reply: %s"), message + 1);
8911         }
8912       return -1;
8913     case PACKET_UNKNOWN:
8914       return -1;
8915     case PACKET_OK:
8916       bp_tgt->placed_address = addr;
8917       bp_tgt->placed_size = bpsize;
8918       return 0;
8919     }
8920   internal_error (__FILE__, __LINE__,
8921                   _("remote_insert_hw_breakpoint: reached end of function"));
8922 }
8923
8924
8925 static int
8926 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
8927                              struct bp_target_info *bp_tgt)
8928 {
8929   CORE_ADDR addr;
8930   struct remote_state *rs = get_remote_state ();
8931   char *p = rs->buf;
8932   char *endbuf = rs->buf + get_remote_packet_size ();
8933
8934   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
8935     return -1;
8936
8937   /* Make sure the remote is pointing at the right process, if
8938      necessary.  */
8939   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
8940     set_general_process ();
8941
8942   *(p++) = 'z';
8943   *(p++) = '1';
8944   *(p++) = ',';
8945
8946   addr = remote_address_masked (bp_tgt->placed_address);
8947   p += hexnumstr (p, (ULONGEST) addr);
8948   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->placed_size);
8949
8950   putpkt (rs->buf);
8951   getpkt (&rs->buf, &rs->buf_size, 0);
8952
8953   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
8954     {
8955     case PACKET_ERROR:
8956     case PACKET_UNKNOWN:
8957       return -1;
8958     case PACKET_OK:
8959       return 0;
8960     }
8961   internal_error (__FILE__, __LINE__,
8962                   _("remote_remove_hw_breakpoint: reached end of function"));
8963 }
8964
8965 /* Verify memory using the "qCRC:" request.  */
8966
8967 static int
8968 remote_verify_memory (struct target_ops *ops,
8969                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
8970 {
8971   struct remote_state *rs = get_remote_state ();
8972   unsigned long host_crc, target_crc;
8973   char *tmp;
8974
8975   /* It doesn't make sense to use qCRC if the remote target is
8976      connected but not running.  */
8977   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
8978     {
8979       enum packet_result result;
8980
8981       /* Make sure the remote is pointing at the right process.  */
8982       set_general_process ();
8983
8984       /* FIXME: assumes lma can fit into long.  */
8985       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
8986                  (long) lma, (long) size);
8987       putpkt (rs->buf);
8988
8989       /* Be clever; compute the host_crc before waiting for target
8990          reply.  */
8991       host_crc = xcrc32 (data, size, 0xffffffff);
8992
8993       getpkt (&rs->buf, &rs->buf_size, 0);
8994
8995       result = packet_ok (rs->buf,
8996                           &remote_protocol_packets[PACKET_qCRC]);
8997       if (result == PACKET_ERROR)
8998         return -1;
8999       else if (result == PACKET_OK)
9000         {
9001           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
9002             target_crc = target_crc * 16 + fromhex (*tmp);
9003
9004           return (host_crc == target_crc);
9005         }
9006     }
9007
9008   return simple_verify_memory (ops, data, lma, size);
9009 }
9010
9011 /* compare-sections command
9012
9013    With no arguments, compares each loadable section in the exec bfd
9014    with the same memory range on the target, and reports mismatches.
9015    Useful for verifying the image on the target against the exec file.  */
9016
9017 static void
9018 compare_sections_command (char *args, int from_tty)
9019 {
9020   asection *s;
9021   struct cleanup *old_chain;
9022   gdb_byte *sectdata;
9023   const char *sectname;
9024   bfd_size_type size;
9025   bfd_vma lma;
9026   int matched = 0;
9027   int mismatched = 0;
9028   int res;
9029   int read_only = 0;
9030
9031   if (!exec_bfd)
9032     error (_("command cannot be used without an exec file"));
9033
9034   /* Make sure the remote is pointing at the right process.  */
9035   set_general_process ();
9036
9037   if (args != NULL && strcmp (args, "-r") == 0)
9038     {
9039       read_only = 1;
9040       args = NULL;
9041     }
9042
9043   for (s = exec_bfd->sections; s; s = s->next)
9044     {
9045       if (!(s->flags & SEC_LOAD))
9046         continue;               /* Skip non-loadable section.  */
9047
9048       if (read_only && (s->flags & SEC_READONLY) == 0)
9049         continue;               /* Skip writeable sections */
9050
9051       size = bfd_get_section_size (s);
9052       if (size == 0)
9053         continue;               /* Skip zero-length section.  */
9054
9055       sectname = bfd_get_section_name (exec_bfd, s);
9056       if (args && strcmp (args, sectname) != 0)
9057         continue;               /* Not the section selected by user.  */
9058
9059       matched = 1;              /* Do this section.  */
9060       lma = s->lma;
9061
9062       sectdata = xmalloc (size);
9063       old_chain = make_cleanup (xfree, sectdata);
9064       bfd_get_section_contents (exec_bfd, s, sectdata, 0, size);
9065
9066       res = target_verify_memory (sectdata, lma, size);
9067
9068       if (res == -1)
9069         error (_("target memory fault, section %s, range %s -- %s"), sectname,
9070                paddress (target_gdbarch (), lma),
9071                paddress (target_gdbarch (), lma + size));
9072
9073       printf_filtered ("Section %s, range %s -- %s: ", sectname,
9074                        paddress (target_gdbarch (), lma),
9075                        paddress (target_gdbarch (), lma + size));
9076       if (res)
9077         printf_filtered ("matched.\n");
9078       else
9079         {
9080           printf_filtered ("MIS-MATCHED!\n");
9081           mismatched++;
9082         }
9083
9084       do_cleanups (old_chain);
9085     }
9086   if (mismatched > 0)
9087     warning (_("One or more sections of the target image does not match\n\
9088 the loaded file\n"));
9089   if (args && !matched)
9090     printf_filtered (_("No loaded section named '%s'.\n"), args);
9091 }
9092
9093 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
9094    into remote target.  The number of bytes written to the remote
9095    target is returned, or -1 for error.  */
9096
9097 static enum target_xfer_status
9098 remote_write_qxfer (struct target_ops *ops, const char *object_name,
9099                     const char *annex, const gdb_byte *writebuf, 
9100                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
9101                     struct packet_config *packet)
9102 {
9103   int i, buf_len;
9104   ULONGEST n;
9105   struct remote_state *rs = get_remote_state ();
9106   int max_size = get_memory_write_packet_size (); 
9107
9108   if (packet->support == PACKET_DISABLE)
9109     return TARGET_XFER_E_IO;
9110
9111   /* Insert header.  */
9112   i = snprintf (rs->buf, max_size, 
9113                 "qXfer:%s:write:%s:%s:",
9114                 object_name, annex ? annex : "",
9115                 phex_nz (offset, sizeof offset));
9116   max_size -= (i + 1);
9117
9118   /* Escape as much data as fits into rs->buf.  */
9119   buf_len = remote_escape_output 
9120     (writebuf, len, (gdb_byte *) rs->buf + i, &max_size, max_size);
9121
9122   if (putpkt_binary (rs->buf, i + buf_len) < 0
9123       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9124       || packet_ok (rs->buf, packet) != PACKET_OK)
9125     return TARGET_XFER_E_IO;
9126
9127   unpack_varlen_hex (rs->buf, &n);
9128
9129   *xfered_len = n;
9130   return TARGET_XFER_OK;
9131 }
9132
9133 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
9134    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
9135    number of bytes read is returned, or 0 for EOF, or -1 for error.
9136    The number of bytes read may be less than LEN without indicating an
9137    EOF.  PACKET is checked and updated to indicate whether the remote
9138    target supports this object.  */
9139
9140 static enum target_xfer_status
9141 remote_read_qxfer (struct target_ops *ops, const char *object_name,
9142                    const char *annex,
9143                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
9144                    ULONGEST *xfered_len,
9145                    struct packet_config *packet)
9146 {
9147   struct remote_state *rs = get_remote_state ();
9148   LONGEST i, n, packet_len;
9149
9150   if (packet->support == PACKET_DISABLE)
9151     return TARGET_XFER_E_IO;
9152
9153   /* Check whether we've cached an end-of-object packet that matches
9154      this request.  */
9155   if (rs->finished_object)
9156     {
9157       if (strcmp (object_name, rs->finished_object) == 0
9158           && strcmp (annex ? annex : "", rs->finished_annex) == 0
9159           && offset == rs->finished_offset)
9160         return TARGET_XFER_EOF;
9161
9162
9163       /* Otherwise, we're now reading something different.  Discard
9164          the cache.  */
9165       xfree (rs->finished_object);
9166       xfree (rs->finished_annex);
9167       rs->finished_object = NULL;
9168       rs->finished_annex = NULL;
9169     }
9170
9171   /* Request only enough to fit in a single packet.  The actual data
9172      may not, since we don't know how much of it will need to be escaped;
9173      the target is free to respond with slightly less data.  We subtract
9174      five to account for the response type and the protocol frame.  */
9175   n = min (get_remote_packet_size () - 5, len);
9176   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
9177             object_name, annex ? annex : "",
9178             phex_nz (offset, sizeof offset),
9179             phex_nz (n, sizeof n));
9180   i = putpkt (rs->buf);
9181   if (i < 0)
9182     return TARGET_XFER_E_IO;
9183
9184   rs->buf[0] = '\0';
9185   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
9186   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
9187     return TARGET_XFER_E_IO;
9188
9189   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
9190     error (_("Unknown remote qXfer reply: %s"), rs->buf);
9191
9192   /* 'm' means there is (or at least might be) more data after this
9193      batch.  That does not make sense unless there's at least one byte
9194      of data in this reply.  */
9195   if (rs->buf[0] == 'm' && packet_len == 1)
9196     error (_("Remote qXfer reply contained no data."));
9197
9198   /* Got some data.  */
9199   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
9200                              packet_len - 1, readbuf, n);
9201
9202   /* 'l' is an EOF marker, possibly including a final block of data,
9203      or possibly empty.  If we have the final block of a non-empty
9204      object, record this fact to bypass a subsequent partial read.  */
9205   if (rs->buf[0] == 'l' && offset + i > 0)
9206     {
9207       rs->finished_object = xstrdup (object_name);
9208       rs->finished_annex = xstrdup (annex ? annex : "");
9209       rs->finished_offset = offset + i;
9210     }
9211
9212   if (i == 0)
9213     return TARGET_XFER_EOF;
9214   else
9215     {
9216       *xfered_len = i;
9217       return TARGET_XFER_OK;
9218     }
9219 }
9220
9221 static enum target_xfer_status
9222 remote_xfer_partial (struct target_ops *ops, enum target_object object,
9223                      const char *annex, gdb_byte *readbuf,
9224                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
9225                      ULONGEST *xfered_len)
9226 {
9227   struct remote_state *rs;
9228   int i;
9229   char *p2;
9230   char query_type;
9231
9232   set_remote_traceframe ();
9233   set_general_thread (inferior_ptid);
9234
9235   rs = get_remote_state ();
9236
9237   /* Handle memory using the standard memory routines.  */
9238   if (object == TARGET_OBJECT_MEMORY)
9239     {
9240       /* If the remote target is connected but not running, we should
9241          pass this request down to a lower stratum (e.g. the executable
9242          file).  */
9243       if (!target_has_execution)
9244         return TARGET_XFER_EOF;
9245
9246       if (writebuf != NULL)
9247         return remote_write_bytes (offset, writebuf, len, xfered_len);
9248       else
9249         return remote_read_bytes (ops, offset, readbuf, len, xfered_len);
9250     }
9251
9252   /* Handle SPU memory using qxfer packets.  */
9253   if (object == TARGET_OBJECT_SPU)
9254     {
9255       if (readbuf)
9256         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
9257                                   xfered_len, &remote_protocol_packets
9258                                   [PACKET_qXfer_spu_read]);
9259       else
9260         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
9261                                    xfered_len, &remote_protocol_packets
9262                                    [PACKET_qXfer_spu_write]);
9263     }
9264
9265   /* Handle extra signal info using qxfer packets.  */
9266   if (object == TARGET_OBJECT_SIGNAL_INFO)
9267     {
9268       if (readbuf)
9269         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
9270                                   xfered_len, &remote_protocol_packets
9271                                   [PACKET_qXfer_siginfo_read]);
9272       else
9273         return remote_write_qxfer (ops, "siginfo", annex,
9274                                    writebuf, offset, len, xfered_len,
9275                                    &remote_protocol_packets
9276                                    [PACKET_qXfer_siginfo_write]);
9277     }
9278
9279   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
9280     {
9281       if (readbuf)
9282         return remote_read_qxfer (ops, "statictrace", annex,
9283                                   readbuf, offset, len, xfered_len,
9284                                   &remote_protocol_packets
9285                                   [PACKET_qXfer_statictrace_read]);
9286       else
9287         return TARGET_XFER_E_IO;
9288     }
9289
9290   /* Only handle flash writes.  */
9291   if (writebuf != NULL)
9292     {
9293       LONGEST xfered;
9294
9295       switch (object)
9296         {
9297         case TARGET_OBJECT_FLASH:
9298           return remote_flash_write (ops, offset, len, xfered_len,
9299                                      writebuf);
9300
9301         default:
9302           return TARGET_XFER_E_IO;
9303         }
9304     }
9305
9306   /* Map pre-existing objects onto letters.  DO NOT do this for new
9307      objects!!!  Instead specify new query packets.  */
9308   switch (object)
9309     {
9310     case TARGET_OBJECT_AVR:
9311       query_type = 'R';
9312       break;
9313
9314     case TARGET_OBJECT_AUXV:
9315       gdb_assert (annex == NULL);
9316       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
9317                                 xfered_len,
9318                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
9319
9320     case TARGET_OBJECT_AVAILABLE_FEATURES:
9321       return remote_read_qxfer
9322         (ops, "features", annex, readbuf, offset, len, xfered_len,
9323          &remote_protocol_packets[PACKET_qXfer_features]);
9324
9325     case TARGET_OBJECT_LIBRARIES:
9326       return remote_read_qxfer
9327         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
9328          &remote_protocol_packets[PACKET_qXfer_libraries]);
9329
9330     case TARGET_OBJECT_LIBRARIES_SVR4:
9331       return remote_read_qxfer
9332         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
9333          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
9334
9335     case TARGET_OBJECT_MEMORY_MAP:
9336       gdb_assert (annex == NULL);
9337       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
9338                                  xfered_len,
9339                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
9340
9341     case TARGET_OBJECT_OSDATA:
9342       /* Should only get here if we're connected.  */
9343       gdb_assert (rs->remote_desc);
9344       return remote_read_qxfer
9345         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
9346         &remote_protocol_packets[PACKET_qXfer_osdata]);
9347
9348     case TARGET_OBJECT_THREADS:
9349       gdb_assert (annex == NULL);
9350       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
9351                                 xfered_len,
9352                                 &remote_protocol_packets[PACKET_qXfer_threads]);
9353
9354     case TARGET_OBJECT_TRACEFRAME_INFO:
9355       gdb_assert (annex == NULL);
9356       return remote_read_qxfer
9357         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
9358          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
9359
9360     case TARGET_OBJECT_FDPIC:
9361       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
9362                                 xfered_len,
9363                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
9364
9365     case TARGET_OBJECT_OPENVMS_UIB:
9366       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
9367                                 xfered_len,
9368                                 &remote_protocol_packets[PACKET_qXfer_uib]);
9369
9370     case TARGET_OBJECT_BTRACE:
9371       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
9372                                 xfered_len,
9373         &remote_protocol_packets[PACKET_qXfer_btrace]);
9374
9375     case TARGET_OBJECT_BTRACE_CONF:
9376       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
9377                                 len, xfered_len,
9378         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
9379
9380     case TARGET_OBJECT_EXEC_FILE:
9381       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
9382                                 len, xfered_len,
9383         &remote_protocol_packets[PACKET_qXfer_exec_file]);
9384
9385     default:
9386       return TARGET_XFER_E_IO;
9387     }
9388
9389   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
9390      large enough let the caller deal with it.  */
9391   if (len < get_remote_packet_size ())
9392     return TARGET_XFER_E_IO;
9393   len = get_remote_packet_size ();
9394
9395   /* Except for querying the minimum buffer size, target must be open.  */
9396   if (!rs->remote_desc)
9397     error (_("remote query is only available after target open"));
9398
9399   gdb_assert (annex != NULL);
9400   gdb_assert (readbuf != NULL);
9401
9402   p2 = rs->buf;
9403   *p2++ = 'q';
9404   *p2++ = query_type;
9405
9406   /* We used one buffer char for the remote protocol q command and
9407      another for the query type.  As the remote protocol encapsulation
9408      uses 4 chars plus one extra in case we are debugging
9409      (remote_debug), we have PBUFZIZ - 7 left to pack the query
9410      string.  */
9411   i = 0;
9412   while (annex[i] && (i < (get_remote_packet_size () - 8)))
9413     {
9414       /* Bad caller may have sent forbidden characters.  */
9415       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
9416       *p2++ = annex[i];
9417       i++;
9418     }
9419   *p2 = '\0';
9420   gdb_assert (annex[i] == '\0');
9421
9422   i = putpkt (rs->buf);
9423   if (i < 0)
9424     return TARGET_XFER_E_IO;
9425
9426   getpkt (&rs->buf, &rs->buf_size, 0);
9427   strcpy ((char *) readbuf, rs->buf);
9428
9429   *xfered_len = strlen ((char *) readbuf);
9430   return TARGET_XFER_OK;
9431 }
9432
9433 static int
9434 remote_search_memory (struct target_ops* ops,
9435                       CORE_ADDR start_addr, ULONGEST search_space_len,
9436                       const gdb_byte *pattern, ULONGEST pattern_len,
9437                       CORE_ADDR *found_addrp)
9438 {
9439   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9440   struct remote_state *rs = get_remote_state ();
9441   int max_size = get_memory_write_packet_size ();
9442   struct packet_config *packet =
9443     &remote_protocol_packets[PACKET_qSearch_memory];
9444   /* Number of packet bytes used to encode the pattern;
9445      this could be more than PATTERN_LEN due to escape characters.  */
9446   int escaped_pattern_len;
9447   /* Amount of pattern that was encodable in the packet.  */
9448   int used_pattern_len;
9449   int i;
9450   int found;
9451   ULONGEST found_addr;
9452
9453   /* Don't go to the target if we don't have to.
9454      This is done before checking packet->support to avoid the possibility that
9455      a success for this edge case means the facility works in general.  */
9456   if (pattern_len > search_space_len)
9457     return 0;
9458   if (pattern_len == 0)
9459     {
9460       *found_addrp = start_addr;
9461       return 1;
9462     }
9463
9464   /* If we already know the packet isn't supported, fall back to the simple
9465      way of searching memory.  */
9466
9467   if (packet_config_support (packet) == PACKET_DISABLE)
9468     {
9469       /* Target doesn't provided special support, fall back and use the
9470          standard support (copy memory and do the search here).  */
9471       return simple_search_memory (ops, start_addr, search_space_len,
9472                                    pattern, pattern_len, found_addrp);
9473     }
9474
9475   /* Make sure the remote is pointing at the right process.  */
9476   set_general_process ();
9477
9478   /* Insert header.  */
9479   i = snprintf (rs->buf, max_size, 
9480                 "qSearch:memory:%s;%s;",
9481                 phex_nz (start_addr, addr_size),
9482                 phex_nz (search_space_len, sizeof (search_space_len)));
9483   max_size -= (i + 1);
9484
9485   /* Escape as much data as fits into rs->buf.  */
9486   escaped_pattern_len =
9487     remote_escape_output (pattern, pattern_len, (gdb_byte *) rs->buf + i,
9488                           &used_pattern_len, max_size);
9489
9490   /* Bail if the pattern is too large.  */
9491   if (used_pattern_len != pattern_len)
9492     error (_("Pattern is too large to transmit to remote target."));
9493
9494   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
9495       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
9496       || packet_ok (rs->buf, packet) != PACKET_OK)
9497     {
9498       /* The request may not have worked because the command is not
9499          supported.  If so, fall back to the simple way.  */
9500       if (packet->support == PACKET_DISABLE)
9501         {
9502           return simple_search_memory (ops, start_addr, search_space_len,
9503                                        pattern, pattern_len, found_addrp);
9504         }
9505       return -1;
9506     }
9507
9508   if (rs->buf[0] == '0')
9509     found = 0;
9510   else if (rs->buf[0] == '1')
9511     {
9512       found = 1;
9513       if (rs->buf[1] != ',')
9514         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9515       unpack_varlen_hex (rs->buf + 2, &found_addr);
9516       *found_addrp = found_addr;
9517     }
9518   else
9519     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
9520
9521   return found;
9522 }
9523
9524 static void
9525 remote_rcmd (struct target_ops *self, const char *command,
9526              struct ui_file *outbuf)
9527 {
9528   struct remote_state *rs = get_remote_state ();
9529   char *p = rs->buf;
9530
9531   if (!rs->remote_desc)
9532     error (_("remote rcmd is only available after target open"));
9533
9534   /* Send a NULL command across as an empty command.  */
9535   if (command == NULL)
9536     command = "";
9537
9538   /* The query prefix.  */
9539   strcpy (rs->buf, "qRcmd,");
9540   p = strchr (rs->buf, '\0');
9541
9542   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
9543       > get_remote_packet_size ())
9544     error (_("\"monitor\" command ``%s'' is too long."), command);
9545
9546   /* Encode the actual command.  */
9547   bin2hex ((const gdb_byte *) command, p, strlen (command));
9548
9549   if (putpkt (rs->buf) < 0)
9550     error (_("Communication problem with target."));
9551
9552   /* get/display the response */
9553   while (1)
9554     {
9555       char *buf;
9556
9557       /* XXX - see also remote_get_noisy_reply().  */
9558       QUIT;                     /* Allow user to bail out with ^C.  */
9559       rs->buf[0] = '\0';
9560       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
9561         { 
9562           /* Timeout.  Continue to (try to) read responses.
9563              This is better than stopping with an error, assuming the stub
9564              is still executing the (long) monitor command.
9565              If needed, the user can interrupt gdb using C-c, obtaining
9566              an effect similar to stop on timeout.  */
9567           continue;
9568         }
9569       buf = rs->buf;
9570       if (buf[0] == '\0')
9571         error (_("Target does not support this command."));
9572       if (buf[0] == 'O' && buf[1] != 'K')
9573         {
9574           remote_console_output (buf + 1); /* 'O' message from stub.  */
9575           continue;
9576         }
9577       if (strcmp (buf, "OK") == 0)
9578         break;
9579       if (strlen (buf) == 3 && buf[0] == 'E'
9580           && isdigit (buf[1]) && isdigit (buf[2]))
9581         {
9582           error (_("Protocol error with Rcmd"));
9583         }
9584       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
9585         {
9586           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
9587
9588           fputc_unfiltered (c, outbuf);
9589         }
9590       break;
9591     }
9592 }
9593
9594 static VEC(mem_region_s) *
9595 remote_memory_map (struct target_ops *ops)
9596 {
9597   VEC(mem_region_s) *result = NULL;
9598   char *text = target_read_stralloc (&current_target,
9599                                      TARGET_OBJECT_MEMORY_MAP, NULL);
9600
9601   if (text)
9602     {
9603       struct cleanup *back_to = make_cleanup (xfree, text);
9604
9605       result = parse_memory_map (text);
9606       do_cleanups (back_to);
9607     }
9608
9609   return result;
9610 }
9611
9612 static void
9613 packet_command (char *args, int from_tty)
9614 {
9615   struct remote_state *rs = get_remote_state ();
9616
9617   if (!rs->remote_desc)
9618     error (_("command can only be used with remote target"));
9619
9620   if (!args)
9621     error (_("remote-packet command requires packet text as argument"));
9622
9623   puts_filtered ("sending: ");
9624   print_packet (args);
9625   puts_filtered ("\n");
9626   putpkt (args);
9627
9628   getpkt (&rs->buf, &rs->buf_size, 0);
9629   puts_filtered ("received: ");
9630   print_packet (rs->buf);
9631   puts_filtered ("\n");
9632 }
9633
9634 #if 0
9635 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
9636
9637 static void display_thread_info (struct gdb_ext_thread_info *info);
9638
9639 static void threadset_test_cmd (char *cmd, int tty);
9640
9641 static void threadalive_test (char *cmd, int tty);
9642
9643 static void threadlist_test_cmd (char *cmd, int tty);
9644
9645 int get_and_display_threadinfo (threadref *ref);
9646
9647 static void threadinfo_test_cmd (char *cmd, int tty);
9648
9649 static int thread_display_step (threadref *ref, void *context);
9650
9651 static void threadlist_update_test_cmd (char *cmd, int tty);
9652
9653 static void init_remote_threadtests (void);
9654
9655 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
9656
9657 static void
9658 threadset_test_cmd (char *cmd, int tty)
9659 {
9660   int sample_thread = SAMPLE_THREAD;
9661
9662   printf_filtered (_("Remote threadset test\n"));
9663   set_general_thread (sample_thread);
9664 }
9665
9666
9667 static void
9668 threadalive_test (char *cmd, int tty)
9669 {
9670   int sample_thread = SAMPLE_THREAD;
9671   int pid = ptid_get_pid (inferior_ptid);
9672   ptid_t ptid = ptid_build (pid, sample_thread, 0);
9673
9674   if (remote_thread_alive (ptid))
9675     printf_filtered ("PASS: Thread alive test\n");
9676   else
9677     printf_filtered ("FAIL: Thread alive test\n");
9678 }
9679
9680 void output_threadid (char *title, threadref *ref);
9681
9682 void
9683 output_threadid (char *title, threadref *ref)
9684 {
9685   char hexid[20];
9686
9687   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
9688   hexid[16] = 0;
9689   printf_filtered ("%s  %s\n", title, (&hexid[0]));
9690 }
9691
9692 static void
9693 threadlist_test_cmd (char *cmd, int tty)
9694 {
9695   int startflag = 1;
9696   threadref nextthread;
9697   int done, result_count;
9698   threadref threadlist[3];
9699
9700   printf_filtered ("Remote Threadlist test\n");
9701   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
9702                               &result_count, &threadlist[0]))
9703     printf_filtered ("FAIL: threadlist test\n");
9704   else
9705     {
9706       threadref *scan = threadlist;
9707       threadref *limit = scan + result_count;
9708
9709       while (scan < limit)
9710         output_threadid (" thread ", scan++);
9711     }
9712 }
9713
9714 void
9715 display_thread_info (struct gdb_ext_thread_info *info)
9716 {
9717   output_threadid ("Threadid: ", &info->threadid);
9718   printf_filtered ("Name: %s\n ", info->shortname);
9719   printf_filtered ("State: %s\n", info->display);
9720   printf_filtered ("other: %s\n\n", info->more_display);
9721 }
9722
9723 int
9724 get_and_display_threadinfo (threadref *ref)
9725 {
9726   int result;
9727   int set;
9728   struct gdb_ext_thread_info threadinfo;
9729
9730   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
9731     | TAG_MOREDISPLAY | TAG_DISPLAY;
9732   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
9733     display_thread_info (&threadinfo);
9734   return result;
9735 }
9736
9737 static void
9738 threadinfo_test_cmd (char *cmd, int tty)
9739 {
9740   int athread = SAMPLE_THREAD;
9741   threadref thread;
9742   int set;
9743
9744   int_to_threadref (&thread, athread);
9745   printf_filtered ("Remote Threadinfo test\n");
9746   if (!get_and_display_threadinfo (&thread))
9747     printf_filtered ("FAIL cannot get thread info\n");
9748 }
9749
9750 static int
9751 thread_display_step (threadref *ref, void *context)
9752 {
9753   /* output_threadid(" threadstep ",ref); *//* simple test */
9754   return get_and_display_threadinfo (ref);
9755 }
9756
9757 static void
9758 threadlist_update_test_cmd (char *cmd, int tty)
9759 {
9760   printf_filtered ("Remote Threadlist update test\n");
9761   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
9762 }
9763
9764 static void
9765 init_remote_threadtests (void)
9766 {
9767   add_com ("tlist", class_obscure, threadlist_test_cmd,
9768            _("Fetch and print the remote list of "
9769              "thread identifiers, one pkt only"));
9770   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
9771            _("Fetch and display info about one thread"));
9772   add_com ("tset", class_obscure, threadset_test_cmd,
9773            _("Test setting to a different thread"));
9774   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
9775            _("Iterate through updating all remote thread info"));
9776   add_com ("talive", class_obscure, threadalive_test,
9777            _(" Remote thread alive test "));
9778 }
9779
9780 #endif /* 0 */
9781
9782 /* Convert a thread ID to a string.  Returns the string in a static
9783    buffer.  */
9784
9785 static char *
9786 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
9787 {
9788   static char buf[64];
9789   struct remote_state *rs = get_remote_state ();
9790
9791   if (ptid_equal (ptid, null_ptid))
9792     return normal_pid_to_str (ptid);
9793   else if (ptid_is_pid (ptid))
9794     {
9795       /* Printing an inferior target id.  */
9796
9797       /* When multi-process extensions are off, there's no way in the
9798          remote protocol to know the remote process id, if there's any
9799          at all.  There's one exception --- when we're connected with
9800          target extended-remote, and we manually attached to a process
9801          with "attach PID".  We don't record anywhere a flag that
9802          allows us to distinguish that case from the case of
9803          connecting with extended-remote and the stub already being
9804          attached to a process, and reporting yes to qAttached, hence
9805          no smart special casing here.  */
9806       if (!remote_multi_process_p (rs))
9807         {
9808           xsnprintf (buf, sizeof buf, "Remote target");
9809           return buf;
9810         }
9811
9812       return normal_pid_to_str (ptid);
9813     }
9814   else
9815     {
9816       if (ptid_equal (magic_null_ptid, ptid))
9817         xsnprintf (buf, sizeof buf, "Thread <main>");
9818       else if (rs->extended && remote_multi_process_p (rs))
9819         if (ptid_get_lwp (ptid) == 0)
9820           return normal_pid_to_str (ptid);
9821         else
9822           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
9823                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
9824       else
9825         xsnprintf (buf, sizeof buf, "Thread %ld",
9826                    ptid_get_lwp (ptid));
9827       return buf;
9828     }
9829 }
9830
9831 /* Get the address of the thread local variable in OBJFILE which is
9832    stored at OFFSET within the thread local storage for thread PTID.  */
9833
9834 static CORE_ADDR
9835 remote_get_thread_local_address (struct target_ops *ops,
9836                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
9837 {
9838   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
9839     {
9840       struct remote_state *rs = get_remote_state ();
9841       char *p = rs->buf;
9842       char *endp = rs->buf + get_remote_packet_size ();
9843       enum packet_result result;
9844
9845       strcpy (p, "qGetTLSAddr:");
9846       p += strlen (p);
9847       p = write_ptid (p, endp, ptid);
9848       *p++ = ',';
9849       p += hexnumstr (p, offset);
9850       *p++ = ',';
9851       p += hexnumstr (p, lm);
9852       *p++ = '\0';
9853
9854       putpkt (rs->buf);
9855       getpkt (&rs->buf, &rs->buf_size, 0);
9856       result = packet_ok (rs->buf,
9857                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
9858       if (result == PACKET_OK)
9859         {
9860           ULONGEST result;
9861
9862           unpack_varlen_hex (rs->buf, &result);
9863           return result;
9864         }
9865       else if (result == PACKET_UNKNOWN)
9866         throw_error (TLS_GENERIC_ERROR,
9867                      _("Remote target doesn't support qGetTLSAddr packet"));
9868       else
9869         throw_error (TLS_GENERIC_ERROR,
9870                      _("Remote target failed to process qGetTLSAddr request"));
9871     }
9872   else
9873     throw_error (TLS_GENERIC_ERROR,
9874                  _("TLS not supported or disabled on this target"));
9875   /* Not reached.  */
9876   return 0;
9877 }
9878
9879 /* Provide thread local base, i.e. Thread Information Block address.
9880    Returns 1 if ptid is found and thread_local_base is non zero.  */
9881
9882 static int
9883 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
9884 {
9885   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
9886     {
9887       struct remote_state *rs = get_remote_state ();
9888       char *p = rs->buf;
9889       char *endp = rs->buf + get_remote_packet_size ();
9890       enum packet_result result;
9891
9892       strcpy (p, "qGetTIBAddr:");
9893       p += strlen (p);
9894       p = write_ptid (p, endp, ptid);
9895       *p++ = '\0';
9896
9897       putpkt (rs->buf);
9898       getpkt (&rs->buf, &rs->buf_size, 0);
9899       result = packet_ok (rs->buf,
9900                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
9901       if (result == PACKET_OK)
9902         {
9903           ULONGEST result;
9904
9905           unpack_varlen_hex (rs->buf, &result);
9906           if (addr)
9907             *addr = (CORE_ADDR) result;
9908           return 1;
9909         }
9910       else if (result == PACKET_UNKNOWN)
9911         error (_("Remote target doesn't support qGetTIBAddr packet"));
9912       else
9913         error (_("Remote target failed to process qGetTIBAddr request"));
9914     }
9915   else
9916     error (_("qGetTIBAddr not supported or disabled on this target"));
9917   /* Not reached.  */
9918   return 0;
9919 }
9920
9921 /* Support for inferring a target description based on the current
9922    architecture and the size of a 'g' packet.  While the 'g' packet
9923    can have any size (since optional registers can be left off the
9924    end), some sizes are easily recognizable given knowledge of the
9925    approximate architecture.  */
9926
9927 struct remote_g_packet_guess
9928 {
9929   int bytes;
9930   const struct target_desc *tdesc;
9931 };
9932 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
9933 DEF_VEC_O(remote_g_packet_guess_s);
9934
9935 struct remote_g_packet_data
9936 {
9937   VEC(remote_g_packet_guess_s) *guesses;
9938 };
9939
9940 static struct gdbarch_data *remote_g_packet_data_handle;
9941
9942 static void *
9943 remote_g_packet_data_init (struct obstack *obstack)
9944 {
9945   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
9946 }
9947
9948 void
9949 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
9950                                 const struct target_desc *tdesc)
9951 {
9952   struct remote_g_packet_data *data
9953     = gdbarch_data (gdbarch, remote_g_packet_data_handle);
9954   struct remote_g_packet_guess new_guess, *guess;
9955   int ix;
9956
9957   gdb_assert (tdesc != NULL);
9958
9959   for (ix = 0;
9960        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
9961        ix++)
9962     if (guess->bytes == bytes)
9963       internal_error (__FILE__, __LINE__,
9964                       _("Duplicate g packet description added for size %d"),
9965                       bytes);
9966
9967   new_guess.bytes = bytes;
9968   new_guess.tdesc = tdesc;
9969   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
9970 }
9971
9972 /* Return 1 if remote_read_description would do anything on this target
9973    and architecture, 0 otherwise.  */
9974
9975 static int
9976 remote_read_description_p (struct target_ops *target)
9977 {
9978   struct remote_g_packet_data *data
9979     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9980
9981   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9982     return 1;
9983
9984   return 0;
9985 }
9986
9987 static const struct target_desc *
9988 remote_read_description (struct target_ops *target)
9989 {
9990   struct remote_g_packet_data *data
9991     = gdbarch_data (target_gdbarch (), remote_g_packet_data_handle);
9992
9993   /* Do not try this during initial connection, when we do not know
9994      whether there is a running but stopped thread.  */
9995   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
9996     return target->beneath->to_read_description (target->beneath);
9997
9998   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
9999     {
10000       struct remote_g_packet_guess *guess;
10001       int ix;
10002       int bytes = send_g_packet ();
10003
10004       for (ix = 0;
10005            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
10006            ix++)
10007         if (guess->bytes == bytes)
10008           return guess->tdesc;
10009
10010       /* We discard the g packet.  A minor optimization would be to
10011          hold on to it, and fill the register cache once we have selected
10012          an architecture, but it's too tricky to do safely.  */
10013     }
10014
10015   return target->beneath->to_read_description (target->beneath);
10016 }
10017
10018 /* Remote file transfer support.  This is host-initiated I/O, not
10019    target-initiated; for target-initiated, see remote-fileio.c.  */
10020
10021 /* If *LEFT is at least the length of STRING, copy STRING to
10022    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10023    decrease *LEFT.  Otherwise raise an error.  */
10024
10025 static void
10026 remote_buffer_add_string (char **buffer, int *left, char *string)
10027 {
10028   int len = strlen (string);
10029
10030   if (len > *left)
10031     error (_("Packet too long for target."));
10032
10033   memcpy (*buffer, string, len);
10034   *buffer += len;
10035   *left -= len;
10036
10037   /* NUL-terminate the buffer as a convenience, if there is
10038      room.  */
10039   if (*left)
10040     **buffer = '\0';
10041 }
10042
10043 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
10044    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10045    decrease *LEFT.  Otherwise raise an error.  */
10046
10047 static void
10048 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
10049                          int len)
10050 {
10051   if (2 * len > *left)
10052     error (_("Packet too long for target."));
10053
10054   bin2hex (bytes, *buffer, len);
10055   *buffer += 2 * len;
10056   *left -= 2 * len;
10057
10058   /* NUL-terminate the buffer as a convenience, if there is
10059      room.  */
10060   if (*left)
10061     **buffer = '\0';
10062 }
10063
10064 /* If *LEFT is large enough, convert VALUE to hex and add it to
10065    *BUFFER, update *BUFFER to point to the new end of the buffer, and
10066    decrease *LEFT.  Otherwise raise an error.  */
10067
10068 static void
10069 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
10070 {
10071   int len = hexnumlen (value);
10072
10073   if (len > *left)
10074     error (_("Packet too long for target."));
10075
10076   hexnumstr (*buffer, value);
10077   *buffer += len;
10078   *left -= len;
10079
10080   /* NUL-terminate the buffer as a convenience, if there is
10081      room.  */
10082   if (*left)
10083     **buffer = '\0';
10084 }
10085
10086 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
10087    value, *REMOTE_ERRNO to the remote error number or zero if none
10088    was included, and *ATTACHMENT to point to the start of the annex
10089    if any.  The length of the packet isn't needed here; there may
10090    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
10091
10092    Return 0 if the packet could be parsed, -1 if it could not.  If
10093    -1 is returned, the other variables may not be initialized.  */
10094
10095 static int
10096 remote_hostio_parse_result (char *buffer, int *retcode,
10097                             int *remote_errno, char **attachment)
10098 {
10099   char *p, *p2;
10100
10101   *remote_errno = 0;
10102   *attachment = NULL;
10103
10104   if (buffer[0] != 'F')
10105     return -1;
10106
10107   errno = 0;
10108   *retcode = strtol (&buffer[1], &p, 16);
10109   if (errno != 0 || p == &buffer[1])
10110     return -1;
10111
10112   /* Check for ",errno".  */
10113   if (*p == ',')
10114     {
10115       errno = 0;
10116       *remote_errno = strtol (p + 1, &p2, 16);
10117       if (errno != 0 || p + 1 == p2)
10118         return -1;
10119       p = p2;
10120     }
10121
10122   /* Check for ";attachment".  If there is no attachment, the
10123      packet should end here.  */
10124   if (*p == ';')
10125     {
10126       *attachment = p + 1;
10127       return 0;
10128     }
10129   else if (*p == '\0')
10130     return 0;
10131   else
10132     return -1;
10133 }
10134
10135 /* Send a prepared I/O packet to the target and read its response.
10136    The prepared packet is in the global RS->BUF before this function
10137    is called, and the answer is there when we return.
10138
10139    COMMAND_BYTES is the length of the request to send, which may include
10140    binary data.  WHICH_PACKET is the packet configuration to check
10141    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
10142    is set to the error number and -1 is returned.  Otherwise the value
10143    returned by the function is returned.
10144
10145    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
10146    attachment is expected; an error will be reported if there's a
10147    mismatch.  If one is found, *ATTACHMENT will be set to point into
10148    the packet buffer and *ATTACHMENT_LEN will be set to the
10149    attachment's length.  */
10150
10151 static int
10152 remote_hostio_send_command (int command_bytes, int which_packet,
10153                             int *remote_errno, char **attachment,
10154                             int *attachment_len)
10155 {
10156   struct remote_state *rs = get_remote_state ();
10157   int ret, bytes_read;
10158   char *attachment_tmp;
10159
10160   if (!rs->remote_desc
10161       || packet_support (which_packet) == PACKET_DISABLE)
10162     {
10163       *remote_errno = FILEIO_ENOSYS;
10164       return -1;
10165     }
10166
10167   putpkt_binary (rs->buf, command_bytes);
10168   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10169
10170   /* If it timed out, something is wrong.  Don't try to parse the
10171      buffer.  */
10172   if (bytes_read < 0)
10173     {
10174       *remote_errno = FILEIO_EINVAL;
10175       return -1;
10176     }
10177
10178   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
10179     {
10180     case PACKET_ERROR:
10181       *remote_errno = FILEIO_EINVAL;
10182       return -1;
10183     case PACKET_UNKNOWN:
10184       *remote_errno = FILEIO_ENOSYS;
10185       return -1;
10186     case PACKET_OK:
10187       break;
10188     }
10189
10190   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
10191                                   &attachment_tmp))
10192     {
10193       *remote_errno = FILEIO_EINVAL;
10194       return -1;
10195     }
10196
10197   /* Make sure we saw an attachment if and only if we expected one.  */
10198   if ((attachment_tmp == NULL && attachment != NULL)
10199       || (attachment_tmp != NULL && attachment == NULL))
10200     {
10201       *remote_errno = FILEIO_EINVAL;
10202       return -1;
10203     }
10204
10205   /* If an attachment was found, it must point into the packet buffer;
10206      work out how many bytes there were.  */
10207   if (attachment_tmp != NULL)
10208     {
10209       *attachment = attachment_tmp;
10210       *attachment_len = bytes_read - (*attachment - rs->buf);
10211     }
10212
10213   return ret;
10214 }
10215
10216 /* Return nonzero if the filesystem accessed by the target_fileio_*
10217    methods is the local filesystem, zero otherwise.  */
10218
10219 static int
10220 remote_filesystem_is_local (struct target_ops *self)
10221 {
10222   return 0;
10223 }
10224
10225 /* Open FILENAME on the remote target, using FLAGS and MODE.  Return a
10226    remote file descriptor, or -1 if an error occurs (and set
10227    *REMOTE_ERRNO).  */
10228
10229 static int
10230 remote_hostio_open (struct target_ops *self,
10231                     const char *filename, int flags, int mode,
10232                     int *remote_errno)
10233 {
10234   struct remote_state *rs = get_remote_state ();
10235   char *p = rs->buf;
10236   int left = get_remote_packet_size () - 1;
10237
10238   remote_buffer_add_string (&p, &left, "vFile:open:");
10239
10240   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10241                            strlen (filename));
10242   remote_buffer_add_string (&p, &left, ",");
10243
10244   remote_buffer_add_int (&p, &left, flags);
10245   remote_buffer_add_string (&p, &left, ",");
10246
10247   remote_buffer_add_int (&p, &left, mode);
10248
10249   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
10250                                      remote_errno, NULL, NULL);
10251 }
10252
10253 /* Write up to LEN bytes from WRITE_BUF to FD on the remote target.
10254    Return the number of bytes written, or -1 if an error occurs (and
10255    set *REMOTE_ERRNO).  */
10256
10257 static int
10258 remote_hostio_pwrite (struct target_ops *self,
10259                       int fd, const gdb_byte *write_buf, int len,
10260                       ULONGEST offset, int *remote_errno)
10261 {
10262   struct remote_state *rs = get_remote_state ();
10263   char *p = rs->buf;
10264   int left = get_remote_packet_size ();
10265   int out_len;
10266
10267   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
10268
10269   remote_buffer_add_int (&p, &left, fd);
10270   remote_buffer_add_string (&p, &left, ",");
10271
10272   remote_buffer_add_int (&p, &left, offset);
10273   remote_buffer_add_string (&p, &left, ",");
10274
10275   p += remote_escape_output (write_buf, len, (gdb_byte *) p, &out_len,
10276                              get_remote_packet_size () - (p - rs->buf));
10277
10278   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
10279                                      remote_errno, NULL, NULL);
10280 }
10281
10282 /* Read up to LEN bytes FD on the remote target into READ_BUF
10283    Return the number of bytes read, or -1 if an error occurs (and
10284    set *REMOTE_ERRNO).  */
10285
10286 static int
10287 remote_hostio_pread (struct target_ops *self,
10288                      int fd, gdb_byte *read_buf, int len,
10289                      ULONGEST offset, int *remote_errno)
10290 {
10291   struct remote_state *rs = get_remote_state ();
10292   char *p = rs->buf;
10293   char *attachment;
10294   int left = get_remote_packet_size ();
10295   int ret, attachment_len;
10296   int read_len;
10297
10298   remote_buffer_add_string (&p, &left, "vFile:pread:");
10299
10300   remote_buffer_add_int (&p, &left, fd);
10301   remote_buffer_add_string (&p, &left, ",");
10302
10303   remote_buffer_add_int (&p, &left, len);
10304   remote_buffer_add_string (&p, &left, ",");
10305
10306   remote_buffer_add_int (&p, &left, offset);
10307
10308   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
10309                                     remote_errno, &attachment,
10310                                     &attachment_len);
10311
10312   if (ret < 0)
10313     return ret;
10314
10315   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10316                                     read_buf, len);
10317   if (read_len != ret)
10318     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
10319
10320   return ret;
10321 }
10322
10323 /* Close FD on the remote target.  Return 0, or -1 if an error occurs
10324    (and set *REMOTE_ERRNO).  */
10325
10326 static int
10327 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
10328 {
10329   struct remote_state *rs = get_remote_state ();
10330   char *p = rs->buf;
10331   int left = get_remote_packet_size () - 1;
10332
10333   remote_buffer_add_string (&p, &left, "vFile:close:");
10334
10335   remote_buffer_add_int (&p, &left, fd);
10336
10337   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
10338                                      remote_errno, NULL, NULL);
10339 }
10340
10341 /* Unlink FILENAME on the remote target.  Return 0, or -1 if an error
10342    occurs (and set *REMOTE_ERRNO).  */
10343
10344 static int
10345 remote_hostio_unlink (struct target_ops *self,
10346                       const char *filename, int *remote_errno)
10347 {
10348   struct remote_state *rs = get_remote_state ();
10349   char *p = rs->buf;
10350   int left = get_remote_packet_size () - 1;
10351
10352   remote_buffer_add_string (&p, &left, "vFile:unlink:");
10353
10354   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10355                            strlen (filename));
10356
10357   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
10358                                      remote_errno, NULL, NULL);
10359 }
10360
10361 /* Read value of symbolic link FILENAME on the remote target.  Return
10362    a null-terminated string allocated via xmalloc, or NULL if an error
10363    occurs (and set *REMOTE_ERRNO).  */
10364
10365 static char *
10366 remote_hostio_readlink (struct target_ops *self,
10367                         const char *filename, int *remote_errno)
10368 {
10369   struct remote_state *rs = get_remote_state ();
10370   char *p = rs->buf;
10371   char *attachment;
10372   int left = get_remote_packet_size ();
10373   int len, attachment_len;
10374   int read_len;
10375   char *ret;
10376
10377   remote_buffer_add_string (&p, &left, "vFile:readlink:");
10378
10379   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
10380                            strlen (filename));
10381
10382   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
10383                                     remote_errno, &attachment,
10384                                     &attachment_len);
10385
10386   if (len < 0)
10387     return NULL;
10388
10389   ret = xmalloc (len + 1);
10390
10391   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10392                                     (gdb_byte *) ret, len);
10393   if (read_len != len)
10394     error (_("Readlink returned %d, but %d bytes."), len, read_len);
10395
10396   ret[len] = '\0';
10397   return ret;
10398 }
10399
10400 /* Read information about the open file FD on the remote target
10401    into ST.  Return 0 on success, or -1 if an error occurs (and
10402    set *REMOTE_ERRNO).  */
10403
10404 static int
10405 remote_hostio_fstat (struct target_ops *self,
10406                      int fd, struct stat *st,
10407                      int *remote_errno)
10408 {
10409   struct remote_state *rs = get_remote_state ();
10410   char *p = rs->buf;
10411   int left = get_remote_packet_size ();
10412   int attachment_len, ret;
10413   char *attachment;
10414   struct fio_stat fst;
10415   int read_len;
10416
10417   remote_buffer_add_string (&p, &left, "vFile:fstat:");
10418
10419   remote_buffer_add_int (&p, &left, fd);
10420
10421   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
10422                                     remote_errno, &attachment,
10423                                     &attachment_len);
10424   if (ret < 0)
10425     {
10426       if (*remote_errno != FILEIO_ENOSYS)
10427         return ret;
10428
10429       /* Strictly we should return -1, ENOSYS here, but when
10430          "set sysroot remote:" was implemented in August 2008
10431          BFD's need for a stat function was sidestepped with
10432          this hack.  This was not remedied until March 2015
10433          so we retain the previous behavior to avoid breaking
10434          compatibility.
10435
10436          Note that the memset is a March 2015 addition; older
10437          GDBs set st_size *and nothing else* so the structure
10438          would have garbage in all other fields.  This might
10439          break something but retaining the previous behavior
10440          here would be just too wrong.  */
10441
10442       memset (st, 0, sizeof (struct stat));
10443       st->st_size = INT_MAX;
10444       return 0;
10445     }
10446
10447   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
10448                                     (gdb_byte *) &fst, sizeof (fst));
10449
10450   if (read_len != ret)
10451     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
10452
10453   if (read_len != sizeof (fst))
10454     error (_("vFile:fstat returned %d bytes, but expecting %d."),
10455            read_len, (int) sizeof (fst));
10456
10457   remote_fileio_to_host_stat (&fst, st);
10458
10459   return 0;
10460 }
10461
10462 static int
10463 remote_fileio_errno_to_host (int errnum)
10464 {
10465   switch (errnum)
10466     {
10467       case FILEIO_EPERM:
10468         return EPERM;
10469       case FILEIO_ENOENT:
10470         return ENOENT;
10471       case FILEIO_EINTR:
10472         return EINTR;
10473       case FILEIO_EIO:
10474         return EIO;
10475       case FILEIO_EBADF:
10476         return EBADF;
10477       case FILEIO_EACCES:
10478         return EACCES;
10479       case FILEIO_EFAULT:
10480         return EFAULT;
10481       case FILEIO_EBUSY:
10482         return EBUSY;
10483       case FILEIO_EEXIST:
10484         return EEXIST;
10485       case FILEIO_ENODEV:
10486         return ENODEV;
10487       case FILEIO_ENOTDIR:
10488         return ENOTDIR;
10489       case FILEIO_EISDIR:
10490         return EISDIR;
10491       case FILEIO_EINVAL:
10492         return EINVAL;
10493       case FILEIO_ENFILE:
10494         return ENFILE;
10495       case FILEIO_EMFILE:
10496         return EMFILE;
10497       case FILEIO_EFBIG:
10498         return EFBIG;
10499       case FILEIO_ENOSPC:
10500         return ENOSPC;
10501       case FILEIO_ESPIPE:
10502         return ESPIPE;
10503       case FILEIO_EROFS:
10504         return EROFS;
10505       case FILEIO_ENOSYS:
10506         return ENOSYS;
10507       case FILEIO_ENAMETOOLONG:
10508         return ENAMETOOLONG;
10509     }
10510   return -1;
10511 }
10512
10513 static char *
10514 remote_hostio_error (int errnum)
10515 {
10516   int host_error = remote_fileio_errno_to_host (errnum);
10517
10518   if (host_error == -1)
10519     error (_("Unknown remote I/O error %d"), errnum);
10520   else
10521     error (_("Remote I/O error: %s"), safe_strerror (host_error));
10522 }
10523
10524 static void
10525 remote_hostio_close_cleanup (void *opaque)
10526 {
10527   int fd = *(int *) opaque;
10528   int remote_errno;
10529
10530   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
10531 }
10532
10533 void
10534 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
10535 {
10536   struct cleanup *back_to, *close_cleanup;
10537   int retcode, fd, remote_errno, bytes, io_size;
10538   FILE *file;
10539   gdb_byte *buffer;
10540   int bytes_in_buffer;
10541   int saw_eof;
10542   ULONGEST offset;
10543   struct remote_state *rs = get_remote_state ();
10544
10545   if (!rs->remote_desc)
10546     error (_("command can only be used with remote target"));
10547
10548   file = gdb_fopen_cloexec (local_file, "rb");
10549   if (file == NULL)
10550     perror_with_name (local_file);
10551   back_to = make_cleanup_fclose (file);
10552
10553   fd = remote_hostio_open (find_target_at (process_stratum),
10554                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
10555                                          | FILEIO_O_TRUNC),
10556                            0700, &remote_errno);
10557   if (fd == -1)
10558     remote_hostio_error (remote_errno);
10559
10560   /* Send up to this many bytes at once.  They won't all fit in the
10561      remote packet limit, so we'll transfer slightly fewer.  */
10562   io_size = get_remote_packet_size ();
10563   buffer = xmalloc (io_size);
10564   make_cleanup (xfree, buffer);
10565
10566   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10567
10568   bytes_in_buffer = 0;
10569   saw_eof = 0;
10570   offset = 0;
10571   while (bytes_in_buffer || !saw_eof)
10572     {
10573       if (!saw_eof)
10574         {
10575           bytes = fread (buffer + bytes_in_buffer, 1,
10576                          io_size - bytes_in_buffer,
10577                          file);
10578           if (bytes == 0)
10579             {
10580               if (ferror (file))
10581                 error (_("Error reading %s."), local_file);
10582               else
10583                 {
10584                   /* EOF.  Unless there is something still in the
10585                      buffer from the last iteration, we are done.  */
10586                   saw_eof = 1;
10587                   if (bytes_in_buffer == 0)
10588                     break;
10589                 }
10590             }
10591         }
10592       else
10593         bytes = 0;
10594
10595       bytes += bytes_in_buffer;
10596       bytes_in_buffer = 0;
10597
10598       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
10599                                       fd, buffer, bytes,
10600                                       offset, &remote_errno);
10601
10602       if (retcode < 0)
10603         remote_hostio_error (remote_errno);
10604       else if (retcode == 0)
10605         error (_("Remote write of %d bytes returned 0!"), bytes);
10606       else if (retcode < bytes)
10607         {
10608           /* Short write.  Save the rest of the read data for the next
10609              write.  */
10610           bytes_in_buffer = bytes - retcode;
10611           memmove (buffer, buffer + retcode, bytes_in_buffer);
10612         }
10613
10614       offset += retcode;
10615     }
10616
10617   discard_cleanups (close_cleanup);
10618   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10619     remote_hostio_error (remote_errno);
10620
10621   if (from_tty)
10622     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
10623   do_cleanups (back_to);
10624 }
10625
10626 void
10627 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
10628 {
10629   struct cleanup *back_to, *close_cleanup;
10630   int fd, remote_errno, bytes, io_size;
10631   FILE *file;
10632   gdb_byte *buffer;
10633   ULONGEST offset;
10634   struct remote_state *rs = get_remote_state ();
10635
10636   if (!rs->remote_desc)
10637     error (_("command can only be used with remote target"));
10638
10639   fd = remote_hostio_open (find_target_at (process_stratum),
10640                            remote_file, FILEIO_O_RDONLY, 0, &remote_errno);
10641   if (fd == -1)
10642     remote_hostio_error (remote_errno);
10643
10644   file = gdb_fopen_cloexec (local_file, "wb");
10645   if (file == NULL)
10646     perror_with_name (local_file);
10647   back_to = make_cleanup_fclose (file);
10648
10649   /* Send up to this many bytes at once.  They won't all fit in the
10650      remote packet limit, so we'll transfer slightly fewer.  */
10651   io_size = get_remote_packet_size ();
10652   buffer = xmalloc (io_size);
10653   make_cleanup (xfree, buffer);
10654
10655   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
10656
10657   offset = 0;
10658   while (1)
10659     {
10660       bytes = remote_hostio_pread (find_target_at (process_stratum),
10661                                    fd, buffer, io_size, offset, &remote_errno);
10662       if (bytes == 0)
10663         /* Success, but no bytes, means end-of-file.  */
10664         break;
10665       if (bytes == -1)
10666         remote_hostio_error (remote_errno);
10667
10668       offset += bytes;
10669
10670       bytes = fwrite (buffer, 1, bytes, file);
10671       if (bytes == 0)
10672         perror_with_name (local_file);
10673     }
10674
10675   discard_cleanups (close_cleanup);
10676   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
10677     remote_hostio_error (remote_errno);
10678
10679   if (from_tty)
10680     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
10681   do_cleanups (back_to);
10682 }
10683
10684 void
10685 remote_file_delete (const char *remote_file, int from_tty)
10686 {
10687   int retcode, remote_errno;
10688   struct remote_state *rs = get_remote_state ();
10689
10690   if (!rs->remote_desc)
10691     error (_("command can only be used with remote target"));
10692
10693   retcode = remote_hostio_unlink (find_target_at (process_stratum),
10694                                   remote_file, &remote_errno);
10695   if (retcode == -1)
10696     remote_hostio_error (remote_errno);
10697
10698   if (from_tty)
10699     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
10700 }
10701
10702 static void
10703 remote_put_command (char *args, int from_tty)
10704 {
10705   struct cleanup *back_to;
10706   char **argv;
10707
10708   if (args == NULL)
10709     error_no_arg (_("file to put"));
10710
10711   argv = gdb_buildargv (args);
10712   back_to = make_cleanup_freeargv (argv);
10713   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10714     error (_("Invalid parameters to remote put"));
10715
10716   remote_file_put (argv[0], argv[1], from_tty);
10717
10718   do_cleanups (back_to);
10719 }
10720
10721 static void
10722 remote_get_command (char *args, int from_tty)
10723 {
10724   struct cleanup *back_to;
10725   char **argv;
10726
10727   if (args == NULL)
10728     error_no_arg (_("file to get"));
10729
10730   argv = gdb_buildargv (args);
10731   back_to = make_cleanup_freeargv (argv);
10732   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
10733     error (_("Invalid parameters to remote get"));
10734
10735   remote_file_get (argv[0], argv[1], from_tty);
10736
10737   do_cleanups (back_to);
10738 }
10739
10740 static void
10741 remote_delete_command (char *args, int from_tty)
10742 {
10743   struct cleanup *back_to;
10744   char **argv;
10745
10746   if (args == NULL)
10747     error_no_arg (_("file to delete"));
10748
10749   argv = gdb_buildargv (args);
10750   back_to = make_cleanup_freeargv (argv);
10751   if (argv[0] == NULL || argv[1] != NULL)
10752     error (_("Invalid parameters to remote delete"));
10753
10754   remote_file_delete (argv[0], from_tty);
10755
10756   do_cleanups (back_to);
10757 }
10758
10759 static void
10760 remote_command (char *args, int from_tty)
10761 {
10762   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
10763 }
10764
10765 static int
10766 remote_can_execute_reverse (struct target_ops *self)
10767 {
10768   if (packet_support (PACKET_bs) == PACKET_ENABLE
10769       || packet_support (PACKET_bc) == PACKET_ENABLE)
10770     return 1;
10771   else
10772     return 0;
10773 }
10774
10775 static int
10776 remote_supports_non_stop (struct target_ops *self)
10777 {
10778   return 1;
10779 }
10780
10781 static int
10782 remote_supports_disable_randomization (struct target_ops *self)
10783 {
10784   /* Only supported in extended mode.  */
10785   return 0;
10786 }
10787
10788 static int
10789 remote_supports_multi_process (struct target_ops *self)
10790 {
10791   struct remote_state *rs = get_remote_state ();
10792
10793   /* Only extended-remote handles being attached to multiple
10794      processes, even though plain remote can use the multi-process
10795      thread id extensions, so that GDB knows the target process's
10796      PID.  */
10797   return rs->extended && remote_multi_process_p (rs);
10798 }
10799
10800 static int
10801 remote_supports_cond_tracepoints (void)
10802 {
10803   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
10804 }
10805
10806 static int
10807 remote_supports_cond_breakpoints (struct target_ops *self)
10808 {
10809   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
10810 }
10811
10812 static int
10813 remote_supports_fast_tracepoints (void)
10814 {
10815   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
10816 }
10817
10818 static int
10819 remote_supports_static_tracepoints (void)
10820 {
10821   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
10822 }
10823
10824 static int
10825 remote_supports_install_in_trace (void)
10826 {
10827   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
10828 }
10829
10830 static int
10831 remote_supports_enable_disable_tracepoint (struct target_ops *self)
10832 {
10833   return (packet_support (PACKET_EnableDisableTracepoints_feature)
10834           == PACKET_ENABLE);
10835 }
10836
10837 static int
10838 remote_supports_string_tracing (struct target_ops *self)
10839 {
10840   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
10841 }
10842
10843 static int
10844 remote_can_run_breakpoint_commands (struct target_ops *self)
10845 {
10846   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
10847 }
10848
10849 static void
10850 remote_trace_init (struct target_ops *self)
10851 {
10852   putpkt ("QTinit");
10853   remote_get_noisy_reply (&target_buf, &target_buf_size);
10854   if (strcmp (target_buf, "OK") != 0)
10855     error (_("Target does not support this command."));
10856 }
10857
10858 static void free_actions_list (char **actions_list);
10859 static void free_actions_list_cleanup_wrapper (void *);
10860 static void
10861 free_actions_list_cleanup_wrapper (void *al)
10862 {
10863   free_actions_list (al);
10864 }
10865
10866 static void
10867 free_actions_list (char **actions_list)
10868 {
10869   int ndx;
10870
10871   if (actions_list == 0)
10872     return;
10873
10874   for (ndx = 0; actions_list[ndx]; ndx++)
10875     xfree (actions_list[ndx]);
10876
10877   xfree (actions_list);
10878 }
10879
10880 /* Recursive routine to walk through command list including loops, and
10881    download packets for each command.  */
10882
10883 static void
10884 remote_download_command_source (int num, ULONGEST addr,
10885                                 struct command_line *cmds)
10886 {
10887   struct remote_state *rs = get_remote_state ();
10888   struct command_line *cmd;
10889
10890   for (cmd = cmds; cmd; cmd = cmd->next)
10891     {
10892       QUIT;     /* Allow user to bail out with ^C.  */
10893       strcpy (rs->buf, "QTDPsrc:");
10894       encode_source_string (num, addr, "cmd", cmd->line,
10895                             rs->buf + strlen (rs->buf),
10896                             rs->buf_size - strlen (rs->buf));
10897       putpkt (rs->buf);
10898       remote_get_noisy_reply (&target_buf, &target_buf_size);
10899       if (strcmp (target_buf, "OK"))
10900         warning (_("Target does not support source download."));
10901
10902       if (cmd->control_type == while_control
10903           || cmd->control_type == while_stepping_control)
10904         {
10905           remote_download_command_source (num, addr, *cmd->body_list);
10906
10907           QUIT; /* Allow user to bail out with ^C.  */
10908           strcpy (rs->buf, "QTDPsrc:");
10909           encode_source_string (num, addr, "cmd", "end",
10910                                 rs->buf + strlen (rs->buf),
10911                                 rs->buf_size - strlen (rs->buf));
10912           putpkt (rs->buf);
10913           remote_get_noisy_reply (&target_buf, &target_buf_size);
10914           if (strcmp (target_buf, "OK"))
10915             warning (_("Target does not support source download."));
10916         }
10917     }
10918 }
10919
10920 static void
10921 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
10922 {
10923 #define BUF_SIZE 2048
10924
10925   CORE_ADDR tpaddr;
10926   char addrbuf[40];
10927   char buf[BUF_SIZE];
10928   char **tdp_actions;
10929   char **stepping_actions;
10930   int ndx;
10931   struct cleanup *old_chain = NULL;
10932   struct agent_expr *aexpr;
10933   struct cleanup *aexpr_chain = NULL;
10934   char *pkt;
10935   struct breakpoint *b = loc->owner;
10936   struct tracepoint *t = (struct tracepoint *) b;
10937
10938   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
10939   old_chain = make_cleanup (free_actions_list_cleanup_wrapper,
10940                             tdp_actions);
10941   (void) make_cleanup (free_actions_list_cleanup_wrapper,
10942                        stepping_actions);
10943
10944   tpaddr = loc->address;
10945   sprintf_vma (addrbuf, tpaddr);
10946   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
10947              addrbuf, /* address */
10948              (b->enable_state == bp_enabled ? 'E' : 'D'),
10949              t->step_count, t->pass_count);
10950   /* Fast tracepoints are mostly handled by the target, but we can
10951      tell the target how big of an instruction block should be moved
10952      around.  */
10953   if (b->type == bp_fast_tracepoint)
10954     {
10955       /* Only test for support at download time; we may not know
10956          target capabilities at definition time.  */
10957       if (remote_supports_fast_tracepoints ())
10958         {
10959           int isize;
10960
10961           if (gdbarch_fast_tracepoint_valid_at (target_gdbarch (),
10962                                                 tpaddr, &isize, NULL))
10963             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
10964                        isize);
10965           else
10966             /* If it passed validation at definition but fails now,
10967                something is very wrong.  */
10968             internal_error (__FILE__, __LINE__,
10969                             _("Fast tracepoint not "
10970                               "valid during download"));
10971         }
10972       else
10973         /* Fast tracepoints are functionally identical to regular
10974            tracepoints, so don't take lack of support as a reason to
10975            give up on the trace run.  */
10976         warning (_("Target does not support fast tracepoints, "
10977                    "downloading %d as regular tracepoint"), b->number);
10978     }
10979   else if (b->type == bp_static_tracepoint)
10980     {
10981       /* Only test for support at download time; we may not know
10982          target capabilities at definition time.  */
10983       if (remote_supports_static_tracepoints ())
10984         {
10985           struct static_tracepoint_marker marker;
10986
10987           if (target_static_tracepoint_marker_at (tpaddr, &marker))
10988             strcat (buf, ":S");
10989           else
10990             error (_("Static tracepoint not valid during download"));
10991         }
10992       else
10993         /* Fast tracepoints are functionally identical to regular
10994            tracepoints, so don't take lack of support as a reason
10995            to give up on the trace run.  */
10996         error (_("Target does not support static tracepoints"));
10997     }
10998   /* If the tracepoint has a conditional, make it into an agent
10999      expression and append to the definition.  */
11000   if (loc->cond)
11001     {
11002       /* Only test support at download time, we may not know target
11003          capabilities at definition time.  */
11004       if (remote_supports_cond_tracepoints ())
11005         {
11006           aexpr = gen_eval_for_expr (tpaddr, loc->cond);
11007           aexpr_chain = make_cleanup_free_agent_expr (aexpr);
11008           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
11009                      aexpr->len);
11010           pkt = buf + strlen (buf);
11011           for (ndx = 0; ndx < aexpr->len; ++ndx)
11012             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
11013           *pkt = '\0';
11014           do_cleanups (aexpr_chain);
11015         }
11016       else
11017         warning (_("Target does not support conditional tracepoints, "
11018                    "ignoring tp %d cond"), b->number);
11019     }
11020
11021   if (b->commands || *default_collect)
11022     strcat (buf, "-");
11023   putpkt (buf);
11024   remote_get_noisy_reply (&target_buf, &target_buf_size);
11025   if (strcmp (target_buf, "OK"))
11026     error (_("Target does not support tracepoints."));
11027
11028   /* do_single_steps (t); */
11029   if (tdp_actions)
11030     {
11031       for (ndx = 0; tdp_actions[ndx]; ndx++)
11032         {
11033           QUIT; /* Allow user to bail out with ^C.  */
11034           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
11035                      b->number, addrbuf, /* address */
11036                      tdp_actions[ndx],
11037                      ((tdp_actions[ndx + 1] || stepping_actions)
11038                       ? '-' : 0));
11039           putpkt (buf);
11040           remote_get_noisy_reply (&target_buf,
11041                                   &target_buf_size);
11042           if (strcmp (target_buf, "OK"))
11043             error (_("Error on target while setting tracepoints."));
11044         }
11045     }
11046   if (stepping_actions)
11047     {
11048       for (ndx = 0; stepping_actions[ndx]; ndx++)
11049         {
11050           QUIT; /* Allow user to bail out with ^C.  */
11051           xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
11052                      b->number, addrbuf, /* address */
11053                      ((ndx == 0) ? "S" : ""),
11054                      stepping_actions[ndx],
11055                      (stepping_actions[ndx + 1] ? "-" : ""));
11056           putpkt (buf);
11057           remote_get_noisy_reply (&target_buf,
11058                                   &target_buf_size);
11059           if (strcmp (target_buf, "OK"))
11060             error (_("Error on target while setting tracepoints."));
11061         }
11062     }
11063
11064   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
11065     {
11066       if (b->addr_string)
11067         {
11068           strcpy (buf, "QTDPsrc:");
11069           encode_source_string (b->number, loc->address,
11070                                 "at", b->addr_string, buf + strlen (buf),
11071                                 2048 - strlen (buf));
11072
11073           putpkt (buf);
11074           remote_get_noisy_reply (&target_buf, &target_buf_size);
11075           if (strcmp (target_buf, "OK"))
11076             warning (_("Target does not support source download."));
11077         }
11078       if (b->cond_string)
11079         {
11080           strcpy (buf, "QTDPsrc:");
11081           encode_source_string (b->number, loc->address,
11082                                 "cond", b->cond_string, buf + strlen (buf),
11083                                 2048 - strlen (buf));
11084           putpkt (buf);
11085           remote_get_noisy_reply (&target_buf, &target_buf_size);
11086           if (strcmp (target_buf, "OK"))
11087             warning (_("Target does not support source download."));
11088         }
11089       remote_download_command_source (b->number, loc->address,
11090                                       breakpoint_commands (b));
11091     }
11092
11093   do_cleanups (old_chain);
11094 }
11095
11096 static int
11097 remote_can_download_tracepoint (struct target_ops *self)
11098 {
11099   struct remote_state *rs = get_remote_state ();
11100   struct trace_status *ts;
11101   int status;
11102
11103   /* Don't try to install tracepoints until we've relocated our
11104      symbols, and fetched and merged the target's tracepoint list with
11105      ours.  */
11106   if (rs->starting_up)
11107     return 0;
11108
11109   ts = current_trace_status ();
11110   status = remote_get_trace_status (self, ts);
11111
11112   if (status == -1 || !ts->running_known || !ts->running)
11113     return 0;
11114
11115   /* If we are in a tracing experiment, but remote stub doesn't support
11116      installing tracepoint in trace, we have to return.  */
11117   if (!remote_supports_install_in_trace ())
11118     return 0;
11119
11120   return 1;
11121 }
11122
11123
11124 static void
11125 remote_download_trace_state_variable (struct target_ops *self,
11126                                       struct trace_state_variable *tsv)
11127 {
11128   struct remote_state *rs = get_remote_state ();
11129   char *p;
11130
11131   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
11132              tsv->number, phex ((ULONGEST) tsv->initial_value, 8),
11133              tsv->builtin);
11134   p = rs->buf + strlen (rs->buf);
11135   if ((p - rs->buf) + strlen (tsv->name) * 2 >= get_remote_packet_size ())
11136     error (_("Trace state variable name too long for tsv definition packet"));
11137   p += 2 * bin2hex ((gdb_byte *) (tsv->name), p, strlen (tsv->name));
11138   *p++ = '\0';
11139   putpkt (rs->buf);
11140   remote_get_noisy_reply (&target_buf, &target_buf_size);
11141   if (*target_buf == '\0')
11142     error (_("Target does not support this command."));
11143   if (strcmp (target_buf, "OK") != 0)
11144     error (_("Error on target while downloading trace state variable."));
11145 }
11146
11147 static void
11148 remote_enable_tracepoint (struct target_ops *self,
11149                           struct bp_location *location)
11150 {
11151   struct remote_state *rs = get_remote_state ();
11152   char addr_buf[40];
11153
11154   sprintf_vma (addr_buf, location->address);
11155   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
11156              location->owner->number, addr_buf);
11157   putpkt (rs->buf);
11158   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11159   if (*rs->buf == '\0')
11160     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
11161   if (strcmp (rs->buf, "OK") != 0)
11162     error (_("Error on target while enabling tracepoint."));
11163 }
11164
11165 static void
11166 remote_disable_tracepoint (struct target_ops *self,
11167                            struct bp_location *location)
11168 {
11169   struct remote_state *rs = get_remote_state ();
11170   char addr_buf[40];
11171
11172   sprintf_vma (addr_buf, location->address);
11173   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
11174              location->owner->number, addr_buf);
11175   putpkt (rs->buf);
11176   remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11177   if (*rs->buf == '\0')
11178     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
11179   if (strcmp (rs->buf, "OK") != 0)
11180     error (_("Error on target while disabling tracepoint."));
11181 }
11182
11183 static void
11184 remote_trace_set_readonly_regions (struct target_ops *self)
11185 {
11186   asection *s;
11187   bfd *abfd = NULL;
11188   bfd_size_type size;
11189   bfd_vma vma;
11190   int anysecs = 0;
11191   int offset = 0;
11192
11193   if (!exec_bfd)
11194     return;                     /* No information to give.  */
11195
11196   strcpy (target_buf, "QTro");
11197   offset = strlen (target_buf);
11198   for (s = exec_bfd->sections; s; s = s->next)
11199     {
11200       char tmp1[40], tmp2[40];
11201       int sec_length;
11202
11203       if ((s->flags & SEC_LOAD) == 0 ||
11204       /*  (s->flags & SEC_CODE) == 0 || */
11205           (s->flags & SEC_READONLY) == 0)
11206         continue;
11207
11208       anysecs = 1;
11209       vma = bfd_get_section_vma (abfd, s);
11210       size = bfd_get_section_size (s);
11211       sprintf_vma (tmp1, vma);
11212       sprintf_vma (tmp2, vma + size);
11213       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
11214       if (offset + sec_length + 1 > target_buf_size)
11215         {
11216           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
11217             warning (_("\
11218 Too many sections for read-only sections definition packet."));
11219           break;
11220         }
11221       xsnprintf (target_buf + offset, target_buf_size - offset, ":%s,%s",
11222                  tmp1, tmp2);
11223       offset += sec_length;
11224     }
11225   if (anysecs)
11226     {
11227       putpkt (target_buf);
11228       getpkt (&target_buf, &target_buf_size, 0);
11229     }
11230 }
11231
11232 static void
11233 remote_trace_start (struct target_ops *self)
11234 {
11235   putpkt ("QTStart");
11236   remote_get_noisy_reply (&target_buf, &target_buf_size);
11237   if (*target_buf == '\0')
11238     error (_("Target does not support this command."));
11239   if (strcmp (target_buf, "OK") != 0)
11240     error (_("Bogus reply from target: %s"), target_buf);
11241 }
11242
11243 static int
11244 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
11245 {
11246   /* Initialize it just to avoid a GCC false warning.  */
11247   char *p = NULL;
11248   /* FIXME we need to get register block size some other way.  */
11249   extern int trace_regblock_size;
11250   enum packet_result result;
11251
11252   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
11253     return -1;
11254
11255   trace_regblock_size = get_remote_arch_state ()->sizeof_g_packet;
11256
11257   putpkt ("qTStatus");
11258
11259   TRY
11260     {
11261       p = remote_get_noisy_reply (&target_buf, &target_buf_size);
11262     }
11263   CATCH (ex, RETURN_MASK_ERROR)
11264     {
11265       if (ex.error != TARGET_CLOSE_ERROR)
11266         {
11267           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
11268           return -1;
11269         }
11270       throw_exception (ex);
11271     }
11272   END_CATCH
11273
11274   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
11275
11276   /* If the remote target doesn't do tracing, flag it.  */
11277   if (result == PACKET_UNKNOWN)
11278     return -1;
11279
11280   /* We're working with a live target.  */
11281   ts->filename = NULL;
11282
11283   if (*p++ != 'T')
11284     error (_("Bogus trace status reply from target: %s"), target_buf);
11285
11286   /* Function 'parse_trace_status' sets default value of each field of
11287      'ts' at first, so we don't have to do it here.  */
11288   parse_trace_status (p, ts);
11289
11290   return ts->running;
11291 }
11292
11293 static void
11294 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
11295                               struct uploaded_tp *utp)
11296 {
11297   struct remote_state *rs = get_remote_state ();
11298   char *reply;
11299   struct bp_location *loc;
11300   struct tracepoint *tp = (struct tracepoint *) bp;
11301   size_t size = get_remote_packet_size ();
11302
11303   if (tp)
11304     {
11305       tp->base.hit_count = 0;
11306       tp->traceframe_usage = 0;
11307       for (loc = tp->base.loc; loc; loc = loc->next)
11308         {
11309           /* If the tracepoint was never downloaded, don't go asking for
11310              any status.  */
11311           if (tp->number_on_target == 0)
11312             continue;
11313           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
11314                      phex_nz (loc->address, 0));
11315           putpkt (rs->buf);
11316           reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11317           if (reply && *reply)
11318             {
11319               if (*reply == 'V')
11320                 parse_tracepoint_status (reply + 1, bp, utp);
11321             }
11322         }
11323     }
11324   else if (utp)
11325     {
11326       utp->hit_count = 0;
11327       utp->traceframe_usage = 0;
11328       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
11329                  phex_nz (utp->addr, 0));
11330       putpkt (rs->buf);
11331       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11332       if (reply && *reply)
11333         {
11334           if (*reply == 'V')
11335             parse_tracepoint_status (reply + 1, bp, utp);
11336         }
11337     }
11338 }
11339
11340 static void
11341 remote_trace_stop (struct target_ops *self)
11342 {
11343   putpkt ("QTStop");
11344   remote_get_noisy_reply (&target_buf, &target_buf_size);
11345   if (*target_buf == '\0')
11346     error (_("Target does not support this command."));
11347   if (strcmp (target_buf, "OK") != 0)
11348     error (_("Bogus reply from target: %s"), target_buf);
11349 }
11350
11351 static int
11352 remote_trace_find (struct target_ops *self,
11353                    enum trace_find_type type, int num,
11354                    CORE_ADDR addr1, CORE_ADDR addr2,
11355                    int *tpp)
11356 {
11357   struct remote_state *rs = get_remote_state ();
11358   char *endbuf = rs->buf + get_remote_packet_size ();
11359   char *p, *reply;
11360   int target_frameno = -1, target_tracept = -1;
11361
11362   /* Lookups other than by absolute frame number depend on the current
11363      trace selected, so make sure it is correct on the remote end
11364      first.  */
11365   if (type != tfind_number)
11366     set_remote_traceframe ();
11367
11368   p = rs->buf;
11369   strcpy (p, "QTFrame:");
11370   p = strchr (p, '\0');
11371   switch (type)
11372     {
11373     case tfind_number:
11374       xsnprintf (p, endbuf - p, "%x", num);
11375       break;
11376     case tfind_pc:
11377       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
11378       break;
11379     case tfind_tp:
11380       xsnprintf (p, endbuf - p, "tdp:%x", num);
11381       break;
11382     case tfind_range:
11383       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
11384                  phex_nz (addr2, 0));
11385       break;
11386     case tfind_outside:
11387       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
11388                  phex_nz (addr2, 0));
11389       break;
11390     default:
11391       error (_("Unknown trace find type %d"), type);
11392     }
11393
11394   putpkt (rs->buf);
11395   reply = remote_get_noisy_reply (&(rs->buf), &rs->buf_size);
11396   if (*reply == '\0')
11397     error (_("Target does not support this command."));
11398
11399   while (reply && *reply)
11400     switch (*reply)
11401       {
11402       case 'F':
11403         p = ++reply;
11404         target_frameno = (int) strtol (p, &reply, 16);
11405         if (reply == p)
11406           error (_("Unable to parse trace frame number"));
11407         /* Don't update our remote traceframe number cache on failure
11408            to select a remote traceframe.  */
11409         if (target_frameno == -1)
11410           return -1;
11411         break;
11412       case 'T':
11413         p = ++reply;
11414         target_tracept = (int) strtol (p, &reply, 16);
11415         if (reply == p)
11416           error (_("Unable to parse tracepoint number"));
11417         break;
11418       case 'O':         /* "OK"? */
11419         if (reply[1] == 'K' && reply[2] == '\0')
11420           reply += 2;
11421         else
11422           error (_("Bogus reply from target: %s"), reply);
11423         break;
11424       default:
11425         error (_("Bogus reply from target: %s"), reply);
11426       }
11427   if (tpp)
11428     *tpp = target_tracept;
11429
11430   rs->remote_traceframe_number = target_frameno;
11431   return target_frameno;
11432 }
11433
11434 static int
11435 remote_get_trace_state_variable_value (struct target_ops *self,
11436                                        int tsvnum, LONGEST *val)
11437 {
11438   struct remote_state *rs = get_remote_state ();
11439   char *reply;
11440   ULONGEST uval;
11441
11442   set_remote_traceframe ();
11443
11444   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
11445   putpkt (rs->buf);
11446   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11447   if (reply && *reply)
11448     {
11449       if (*reply == 'V')
11450         {
11451           unpack_varlen_hex (reply + 1, &uval);
11452           *val = (LONGEST) uval;
11453           return 1;
11454         }
11455     }
11456   return 0;
11457 }
11458
11459 static int
11460 remote_save_trace_data (struct target_ops *self, const char *filename)
11461 {
11462   struct remote_state *rs = get_remote_state ();
11463   char *p, *reply;
11464
11465   p = rs->buf;
11466   strcpy (p, "QTSave:");
11467   p += strlen (p);
11468   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
11469     error (_("Remote file name too long for trace save packet"));
11470   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
11471   *p++ = '\0';
11472   putpkt (rs->buf);
11473   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11474   if (*reply == '\0')
11475     error (_("Target does not support this command."));
11476   if (strcmp (reply, "OK") != 0)
11477     error (_("Bogus reply from target: %s"), reply);
11478   return 0;
11479 }
11480
11481 /* This is basically a memory transfer, but needs to be its own packet
11482    because we don't know how the target actually organizes its trace
11483    memory, plus we want to be able to ask for as much as possible, but
11484    not be unhappy if we don't get as much as we ask for.  */
11485
11486 static LONGEST
11487 remote_get_raw_trace_data (struct target_ops *self,
11488                            gdb_byte *buf, ULONGEST offset, LONGEST len)
11489 {
11490   struct remote_state *rs = get_remote_state ();
11491   char *reply;
11492   char *p;
11493   int rslt;
11494
11495   p = rs->buf;
11496   strcpy (p, "qTBuffer:");
11497   p += strlen (p);
11498   p += hexnumstr (p, offset);
11499   *p++ = ',';
11500   p += hexnumstr (p, len);
11501   *p++ = '\0';
11502
11503   putpkt (rs->buf);
11504   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11505   if (reply && *reply)
11506     {
11507       /* 'l' by itself means we're at the end of the buffer and
11508          there is nothing more to get.  */
11509       if (*reply == 'l')
11510         return 0;
11511
11512       /* Convert the reply into binary.  Limit the number of bytes to
11513          convert according to our passed-in buffer size, rather than
11514          what was returned in the packet; if the target is
11515          unexpectedly generous and gives us a bigger reply than we
11516          asked for, we don't want to crash.  */
11517       rslt = hex2bin (target_buf, buf, len);
11518       return rslt;
11519     }
11520
11521   /* Something went wrong, flag as an error.  */
11522   return -1;
11523 }
11524
11525 static void
11526 remote_set_disconnected_tracing (struct target_ops *self, int val)
11527 {
11528   struct remote_state *rs = get_remote_state ();
11529
11530   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
11531     {
11532       char *reply;
11533
11534       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
11535       putpkt (rs->buf);
11536       reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11537       if (*reply == '\0')
11538         error (_("Target does not support this command."));
11539       if (strcmp (reply, "OK") != 0)
11540         error (_("Bogus reply from target: %s"), reply);
11541     }
11542   else if (val)
11543     warning (_("Target does not support disconnected tracing."));
11544 }
11545
11546 static int
11547 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
11548 {
11549   struct thread_info *info = find_thread_ptid (ptid);
11550
11551   if (info && info->priv)
11552     return info->priv->core;
11553   return -1;
11554 }
11555
11556 static void
11557 remote_set_circular_trace_buffer (struct target_ops *self, int val)
11558 {
11559   struct remote_state *rs = get_remote_state ();
11560   char *reply;
11561
11562   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
11563   putpkt (rs->buf);
11564   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11565   if (*reply == '\0')
11566     error (_("Target does not support this command."));
11567   if (strcmp (reply, "OK") != 0)
11568     error (_("Bogus reply from target: %s"), reply);
11569 }
11570
11571 static struct traceframe_info *
11572 remote_traceframe_info (struct target_ops *self)
11573 {
11574   char *text;
11575
11576   text = target_read_stralloc (&current_target,
11577                                TARGET_OBJECT_TRACEFRAME_INFO, NULL);
11578   if (text != NULL)
11579     {
11580       struct traceframe_info *info;
11581       struct cleanup *back_to = make_cleanup (xfree, text);
11582
11583       info = parse_traceframe_info (text);
11584       do_cleanups (back_to);
11585       return info;
11586     }
11587
11588   return NULL;
11589 }
11590
11591 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
11592    instruction on which a fast tracepoint may be placed.  Returns -1
11593    if the packet is not supported, and 0 if the minimum instruction
11594    length is unknown.  */
11595
11596 static int
11597 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
11598 {
11599   struct remote_state *rs = get_remote_state ();
11600   char *reply;
11601
11602   /* If we're not debugging a process yet, the IPA can't be
11603      loaded.  */
11604   if (!target_has_execution)
11605     return 0;
11606
11607   /* Make sure the remote is pointing at the right process.  */
11608   set_general_process ();
11609
11610   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
11611   putpkt (rs->buf);
11612   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11613   if (*reply == '\0')
11614     return -1;
11615   else
11616     {
11617       ULONGEST min_insn_len;
11618
11619       unpack_varlen_hex (reply, &min_insn_len);
11620
11621       return (int) min_insn_len;
11622     }
11623 }
11624
11625 static void
11626 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
11627 {
11628   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
11629     {
11630       struct remote_state *rs = get_remote_state ();
11631       char *buf = rs->buf;
11632       char *endbuf = rs->buf + get_remote_packet_size ();
11633       enum packet_result result;
11634
11635       gdb_assert (val >= 0 || val == -1);
11636       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
11637       /* Send -1 as literal "-1" to avoid host size dependency.  */
11638       if (val < 0)
11639         {
11640           *buf++ = '-';
11641           buf += hexnumstr (buf, (ULONGEST) -val);
11642         }
11643       else
11644         buf += hexnumstr (buf, (ULONGEST) val);
11645
11646       putpkt (rs->buf);
11647       remote_get_noisy_reply (&rs->buf, &rs->buf_size);
11648       result = packet_ok (rs->buf,
11649                   &remote_protocol_packets[PACKET_QTBuffer_size]);
11650
11651       if (result != PACKET_OK)
11652         warning (_("Bogus reply from target: %s"), rs->buf);
11653     }
11654 }
11655
11656 static int
11657 remote_set_trace_notes (struct target_ops *self,
11658                         const char *user, const char *notes,
11659                         const char *stop_notes)
11660 {
11661   struct remote_state *rs = get_remote_state ();
11662   char *reply;
11663   char *buf = rs->buf;
11664   char *endbuf = rs->buf + get_remote_packet_size ();
11665   int nbytes;
11666
11667   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
11668   if (user)
11669     {
11670       buf += xsnprintf (buf, endbuf - buf, "user:");
11671       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
11672       buf += 2 * nbytes;
11673       *buf++ = ';';
11674     }
11675   if (notes)
11676     {
11677       buf += xsnprintf (buf, endbuf - buf, "notes:");
11678       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
11679       buf += 2 * nbytes;
11680       *buf++ = ';';
11681     }
11682   if (stop_notes)
11683     {
11684       buf += xsnprintf (buf, endbuf - buf, "tstop:");
11685       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
11686       buf += 2 * nbytes;
11687       *buf++ = ';';
11688     }
11689   /* Ensure the buffer is terminated.  */
11690   *buf = '\0';
11691
11692   putpkt (rs->buf);
11693   reply = remote_get_noisy_reply (&target_buf, &target_buf_size);
11694   if (*reply == '\0')
11695     return 0;
11696
11697   if (strcmp (reply, "OK") != 0)
11698     error (_("Bogus reply from target: %s"), reply);
11699
11700   return 1;
11701 }
11702
11703 static int
11704 remote_use_agent (struct target_ops *self, int use)
11705 {
11706   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
11707     {
11708       struct remote_state *rs = get_remote_state ();
11709
11710       /* If the stub supports QAgent.  */
11711       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
11712       putpkt (rs->buf);
11713       getpkt (&rs->buf, &rs->buf_size, 0);
11714
11715       if (strcmp (rs->buf, "OK") == 0)
11716         {
11717           use_agent = use;
11718           return 1;
11719         }
11720     }
11721
11722   return 0;
11723 }
11724
11725 static int
11726 remote_can_use_agent (struct target_ops *self)
11727 {
11728   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
11729 }
11730
11731 struct btrace_target_info
11732 {
11733   /* The ptid of the traced thread.  */
11734   ptid_t ptid;
11735
11736   /* The obtained branch trace configuration.  */
11737   struct btrace_config conf;
11738 };
11739
11740 /* Reset our idea of our target's btrace configuration.  */
11741
11742 static void
11743 remote_btrace_reset (void)
11744 {
11745   struct remote_state *rs = get_remote_state ();
11746
11747   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
11748 }
11749
11750 /* Check whether the target supports branch tracing.  */
11751
11752 static int
11753 remote_supports_btrace (struct target_ops *self, enum btrace_format format)
11754 {
11755   if (packet_support (PACKET_Qbtrace_off) != PACKET_ENABLE)
11756     return 0;
11757   if (packet_support (PACKET_qXfer_btrace) != PACKET_ENABLE)
11758     return 0;
11759
11760   switch (format)
11761     {
11762       case BTRACE_FORMAT_NONE:
11763         return 0;
11764
11765       case BTRACE_FORMAT_BTS:
11766         return (packet_support (PACKET_Qbtrace_bts) == PACKET_ENABLE);
11767     }
11768
11769   internal_error (__FILE__, __LINE__, _("Unknown branch trace format"));
11770 }
11771
11772 /* Synchronize the configuration with the target.  */
11773
11774 static void
11775 btrace_sync_conf (const struct btrace_config *conf)
11776 {
11777   struct packet_config *packet;
11778   struct remote_state *rs;
11779   char *buf, *pos, *endbuf;
11780
11781   rs = get_remote_state ();
11782   buf = rs->buf;
11783   endbuf = buf + get_remote_packet_size ();
11784
11785   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
11786   if (packet_config_support (packet) == PACKET_ENABLE
11787       && conf->bts.size != rs->btrace_config.bts.size)
11788     {
11789       pos = buf;
11790       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
11791                         conf->bts.size);
11792
11793       putpkt (buf);
11794       getpkt (&buf, &rs->buf_size, 0);
11795
11796       if (packet_ok (buf, packet) == PACKET_ERROR)
11797         {
11798           if (buf[0] == 'E' && buf[1] == '.')
11799             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
11800           else
11801             error (_("Failed to configure the BTS buffer size."));
11802         }
11803
11804       rs->btrace_config.bts.size = conf->bts.size;
11805     }
11806 }
11807
11808 /* Read the current thread's btrace configuration from the target and
11809    store it into CONF.  */
11810
11811 static void
11812 btrace_read_config (struct btrace_config *conf)
11813 {
11814   char *xml;
11815
11816   xml = target_read_stralloc (&current_target,
11817                               TARGET_OBJECT_BTRACE_CONF, "");
11818   if (xml != NULL)
11819     {
11820       struct cleanup *cleanup;
11821
11822       cleanup = make_cleanup (xfree, xml);
11823       parse_xml_btrace_conf (conf, xml);
11824       do_cleanups (cleanup);
11825     }
11826 }
11827
11828 /* Enable branch tracing.  */
11829
11830 static struct btrace_target_info *
11831 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
11832                       const struct btrace_config *conf)
11833 {
11834   struct btrace_target_info *tinfo = NULL;
11835   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
11836   struct remote_state *rs = get_remote_state ();
11837   char *buf = rs->buf;
11838   char *endbuf = rs->buf + get_remote_packet_size ();
11839
11840   if (packet_config_support (packet) != PACKET_ENABLE)
11841     error (_("Target does not support branch tracing."));
11842
11843   btrace_sync_conf (conf);
11844
11845   set_general_thread (ptid);
11846
11847   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11848   putpkt (rs->buf);
11849   getpkt (&rs->buf, &rs->buf_size, 0);
11850
11851   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11852     {
11853       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11854         error (_("Could not enable branch tracing for %s: %s"),
11855                target_pid_to_str (ptid), rs->buf + 2);
11856       else
11857         error (_("Could not enable branch tracing for %s."),
11858                target_pid_to_str (ptid));
11859     }
11860
11861   tinfo = xzalloc (sizeof (*tinfo));
11862   tinfo->ptid = ptid;
11863
11864   /* If we fail to read the configuration, we lose some information, but the
11865      tracing itself is not impacted.  */
11866   TRY
11867     {
11868       btrace_read_config (&tinfo->conf);
11869     }
11870   CATCH (err, RETURN_MASK_ERROR)
11871     {
11872       if (err.message != NULL)
11873         warning ("%s", err.message);
11874     }
11875   END_CATCH
11876
11877   return tinfo;
11878 }
11879
11880 /* Disable branch tracing.  */
11881
11882 static void
11883 remote_disable_btrace (struct target_ops *self,
11884                        struct btrace_target_info *tinfo)
11885 {
11886   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
11887   struct remote_state *rs = get_remote_state ();
11888   char *buf = rs->buf;
11889   char *endbuf = rs->buf + get_remote_packet_size ();
11890
11891   if (packet_config_support (packet) != PACKET_ENABLE)
11892     error (_("Target does not support branch tracing."));
11893
11894   set_general_thread (tinfo->ptid);
11895
11896   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
11897   putpkt (rs->buf);
11898   getpkt (&rs->buf, &rs->buf_size, 0);
11899
11900   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
11901     {
11902       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
11903         error (_("Could not disable branch tracing for %s: %s"),
11904                target_pid_to_str (tinfo->ptid), rs->buf + 2);
11905       else
11906         error (_("Could not disable branch tracing for %s."),
11907                target_pid_to_str (tinfo->ptid));
11908     }
11909
11910   xfree (tinfo);
11911 }
11912
11913 /* Teardown branch tracing.  */
11914
11915 static void
11916 remote_teardown_btrace (struct target_ops *self,
11917                         struct btrace_target_info *tinfo)
11918 {
11919   /* We must not talk to the target during teardown.  */
11920   xfree (tinfo);
11921 }
11922
11923 /* Read the branch trace.  */
11924
11925 static enum btrace_error
11926 remote_read_btrace (struct target_ops *self,
11927                     struct btrace_data *btrace,
11928                     struct btrace_target_info *tinfo,
11929                     enum btrace_read_type type)
11930 {
11931   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
11932   struct remote_state *rs = get_remote_state ();
11933   struct cleanup *cleanup;
11934   const char *annex;
11935   char *xml;
11936
11937   if (packet_config_support (packet) != PACKET_ENABLE)
11938     error (_("Target does not support branch tracing."));
11939
11940 #if !defined(HAVE_LIBEXPAT)
11941   error (_("Cannot process branch tracing result. XML parsing not supported."));
11942 #endif
11943
11944   switch (type)
11945     {
11946     case BTRACE_READ_ALL:
11947       annex = "all";
11948       break;
11949     case BTRACE_READ_NEW:
11950       annex = "new";
11951       break;
11952     case BTRACE_READ_DELTA:
11953       annex = "delta";
11954       break;
11955     default:
11956       internal_error (__FILE__, __LINE__,
11957                       _("Bad branch tracing read type: %u."),
11958                       (unsigned int) type);
11959     }
11960
11961   xml = target_read_stralloc (&current_target,
11962                               TARGET_OBJECT_BTRACE, annex);
11963   if (xml == NULL)
11964     return BTRACE_ERR_UNKNOWN;
11965
11966   cleanup = make_cleanup (xfree, xml);
11967   parse_xml_btrace (btrace, xml);
11968   do_cleanups (cleanup);
11969
11970   return BTRACE_ERR_NONE;
11971 }
11972
11973 static const struct btrace_config *
11974 remote_btrace_conf (struct target_ops *self,
11975                     const struct btrace_target_info *tinfo)
11976 {
11977   return &tinfo->conf;
11978 }
11979
11980 static int
11981 remote_augmented_libraries_svr4_read (struct target_ops *self)
11982 {
11983   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
11984           == PACKET_ENABLE);
11985 }
11986
11987 /* Implementation of to_load.  */
11988
11989 static void
11990 remote_load (struct target_ops *self, const char *name, int from_tty)
11991 {
11992   generic_load (name, from_tty);
11993 }
11994
11995 /* Accepts an integer PID; returns a string representing a file that
11996    can be opened on the remote side to get the symbols for the child
11997    process.  Returns NULL if the operation is not supported.  */
11998
11999 static char *
12000 remote_pid_to_exec_file (struct target_ops *self, int pid)
12001 {
12002   static char *filename = NULL;
12003   struct inferior *inf;
12004   char *annex = NULL;
12005
12006   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
12007     return NULL;
12008
12009   if (filename != NULL)
12010     xfree (filename);
12011
12012   inf = find_inferior_pid (pid);
12013   if (inf == NULL)
12014     internal_error (__FILE__, __LINE__,
12015                     _("not currently attached to process %d"), pid);
12016
12017   if (!inf->fake_pid_p)
12018     {
12019       const int annex_size = 9;
12020
12021       annex = alloca (annex_size);
12022       xsnprintf (annex, annex_size, "%x", pid);
12023     }
12024
12025   filename = target_read_stralloc (&current_target,
12026                                    TARGET_OBJECT_EXEC_FILE, annex);
12027
12028   return filename;
12029 }
12030
12031 static void
12032 init_remote_ops (void)
12033 {
12034   remote_ops.to_shortname = "remote";
12035   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
12036   remote_ops.to_doc =
12037     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12038 Specify the serial device it is connected to\n\
12039 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
12040   remote_ops.to_open = remote_open;
12041   remote_ops.to_close = remote_close;
12042   remote_ops.to_detach = remote_detach;
12043   remote_ops.to_disconnect = remote_disconnect;
12044   remote_ops.to_resume = remote_resume;
12045   remote_ops.to_wait = remote_wait;
12046   remote_ops.to_fetch_registers = remote_fetch_registers;
12047   remote_ops.to_store_registers = remote_store_registers;
12048   remote_ops.to_prepare_to_store = remote_prepare_to_store;
12049   remote_ops.to_files_info = remote_files_info;
12050   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
12051   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
12052   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
12053   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
12054   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
12055   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
12056   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
12057   remote_ops.to_stopped_data_address = remote_stopped_data_address;
12058   remote_ops.to_watchpoint_addr_within_range =
12059     remote_watchpoint_addr_within_range;
12060   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
12061   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
12062   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
12063   remote_ops.to_region_ok_for_hw_watchpoint
12064      = remote_region_ok_for_hw_watchpoint;
12065   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
12066   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
12067   remote_ops.to_kill = remote_kill;
12068   remote_ops.to_load = remote_load;
12069   remote_ops.to_mourn_inferior = remote_mourn;
12070   remote_ops.to_pass_signals = remote_pass_signals;
12071   remote_ops.to_program_signals = remote_program_signals;
12072   remote_ops.to_thread_alive = remote_thread_alive;
12073   remote_ops.to_update_thread_list = remote_update_thread_list;
12074   remote_ops.to_pid_to_str = remote_pid_to_str;
12075   remote_ops.to_extra_thread_info = remote_threads_extra_info;
12076   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
12077   remote_ops.to_stop = remote_stop;
12078   remote_ops.to_xfer_partial = remote_xfer_partial;
12079   remote_ops.to_rcmd = remote_rcmd;
12080   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
12081   remote_ops.to_log_command = serial_log_command;
12082   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
12083   remote_ops.to_stratum = process_stratum;
12084   remote_ops.to_has_all_memory = default_child_has_all_memory;
12085   remote_ops.to_has_memory = default_child_has_memory;
12086   remote_ops.to_has_stack = default_child_has_stack;
12087   remote_ops.to_has_registers = default_child_has_registers;
12088   remote_ops.to_has_execution = default_child_has_execution;
12089   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
12090   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
12091   remote_ops.to_magic = OPS_MAGIC;
12092   remote_ops.to_memory_map = remote_memory_map;
12093   remote_ops.to_flash_erase = remote_flash_erase;
12094   remote_ops.to_flash_done = remote_flash_done;
12095   remote_ops.to_read_description = remote_read_description;
12096   remote_ops.to_search_memory = remote_search_memory;
12097   remote_ops.to_can_async_p = remote_can_async_p;
12098   remote_ops.to_is_async_p = remote_is_async_p;
12099   remote_ops.to_async = remote_async;
12100   remote_ops.to_terminal_inferior = remote_terminal_inferior;
12101   remote_ops.to_terminal_ours = remote_terminal_ours;
12102   remote_ops.to_supports_non_stop = remote_supports_non_stop;
12103   remote_ops.to_supports_multi_process = remote_supports_multi_process;
12104   remote_ops.to_supports_disable_randomization
12105     = remote_supports_disable_randomization;
12106   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
12107   remote_ops.to_fileio_open = remote_hostio_open;
12108   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
12109   remote_ops.to_fileio_pread = remote_hostio_pread;
12110   remote_ops.to_fileio_fstat = remote_hostio_fstat;
12111   remote_ops.to_fileio_close = remote_hostio_close;
12112   remote_ops.to_fileio_unlink = remote_hostio_unlink;
12113   remote_ops.to_fileio_readlink = remote_hostio_readlink;
12114   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
12115   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
12116   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
12117   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
12118   remote_ops.to_trace_init = remote_trace_init;
12119   remote_ops.to_download_tracepoint = remote_download_tracepoint;
12120   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
12121   remote_ops.to_download_trace_state_variable
12122     = remote_download_trace_state_variable;
12123   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
12124   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
12125   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
12126   remote_ops.to_trace_start = remote_trace_start;
12127   remote_ops.to_get_trace_status = remote_get_trace_status;
12128   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
12129   remote_ops.to_trace_stop = remote_trace_stop;
12130   remote_ops.to_trace_find = remote_trace_find;
12131   remote_ops.to_get_trace_state_variable_value
12132     = remote_get_trace_state_variable_value;
12133   remote_ops.to_save_trace_data = remote_save_trace_data;
12134   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
12135   remote_ops.to_upload_trace_state_variables
12136     = remote_upload_trace_state_variables;
12137   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
12138   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
12139   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
12140   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
12141   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
12142   remote_ops.to_set_trace_notes = remote_set_trace_notes;
12143   remote_ops.to_core_of_thread = remote_core_of_thread;
12144   remote_ops.to_verify_memory = remote_verify_memory;
12145   remote_ops.to_get_tib_address = remote_get_tib_address;
12146   remote_ops.to_set_permissions = remote_set_permissions;
12147   remote_ops.to_static_tracepoint_marker_at
12148     = remote_static_tracepoint_marker_at;
12149   remote_ops.to_static_tracepoint_markers_by_strid
12150     = remote_static_tracepoint_markers_by_strid;
12151   remote_ops.to_traceframe_info = remote_traceframe_info;
12152   remote_ops.to_use_agent = remote_use_agent;
12153   remote_ops.to_can_use_agent = remote_can_use_agent;
12154   remote_ops.to_supports_btrace = remote_supports_btrace;
12155   remote_ops.to_enable_btrace = remote_enable_btrace;
12156   remote_ops.to_disable_btrace = remote_disable_btrace;
12157   remote_ops.to_teardown_btrace = remote_teardown_btrace;
12158   remote_ops.to_read_btrace = remote_read_btrace;
12159   remote_ops.to_btrace_conf = remote_btrace_conf;
12160   remote_ops.to_augmented_libraries_svr4_read =
12161     remote_augmented_libraries_svr4_read;
12162 }
12163
12164 /* Set up the extended remote vector by making a copy of the standard
12165    remote vector and adding to it.  */
12166
12167 static void
12168 init_extended_remote_ops (void)
12169 {
12170   extended_remote_ops = remote_ops;
12171
12172   extended_remote_ops.to_shortname = "extended-remote";
12173   extended_remote_ops.to_longname =
12174     "Extended remote serial target in gdb-specific protocol";
12175   extended_remote_ops.to_doc =
12176     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
12177 Specify the serial device it is connected to (e.g. /dev/ttya).";
12178   extended_remote_ops.to_open = extended_remote_open;
12179   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
12180   extended_remote_ops.to_mourn_inferior = extended_remote_mourn;
12181   extended_remote_ops.to_detach = extended_remote_detach;
12182   extended_remote_ops.to_attach = extended_remote_attach;
12183   extended_remote_ops.to_post_attach = extended_remote_post_attach;
12184   extended_remote_ops.to_kill = extended_remote_kill;
12185   extended_remote_ops.to_supports_disable_randomization
12186     = extended_remote_supports_disable_randomization;
12187   extended_remote_ops.to_follow_fork = remote_follow_fork;
12188   extended_remote_ops.to_insert_fork_catchpoint
12189     = remote_insert_fork_catchpoint;
12190   extended_remote_ops.to_remove_fork_catchpoint
12191     = remote_remove_fork_catchpoint;
12192   extended_remote_ops.to_insert_vfork_catchpoint
12193     = remote_insert_vfork_catchpoint;
12194   extended_remote_ops.to_remove_vfork_catchpoint
12195     = remote_remove_vfork_catchpoint;
12196 }
12197
12198 static int
12199 remote_can_async_p (struct target_ops *ops)
12200 {
12201   struct remote_state *rs = get_remote_state ();
12202
12203   if (!target_async_permitted)
12204     /* We only enable async when the user specifically asks for it.  */
12205     return 0;
12206
12207   /* We're async whenever the serial device is.  */
12208   return serial_can_async_p (rs->remote_desc);
12209 }
12210
12211 static int
12212 remote_is_async_p (struct target_ops *ops)
12213 {
12214   struct remote_state *rs = get_remote_state ();
12215
12216   if (!target_async_permitted)
12217     /* We only enable async when the user specifically asks for it.  */
12218     return 0;
12219
12220   /* We're async whenever the serial device is.  */
12221   return serial_is_async_p (rs->remote_desc);
12222 }
12223
12224 /* Pass the SERIAL event on and up to the client.  One day this code
12225    will be able to delay notifying the client of an event until the
12226    point where an entire packet has been received.  */
12227
12228 static serial_event_ftype remote_async_serial_handler;
12229
12230 static void
12231 remote_async_serial_handler (struct serial *scb, void *context)
12232 {
12233   struct remote_state *rs = context;
12234
12235   /* Don't propogate error information up to the client.  Instead let
12236      the client find out about the error by querying the target.  */
12237   inferior_event_handler (INF_REG_EVENT, NULL);
12238 }
12239
12240 static void
12241 remote_async_inferior_event_handler (gdb_client_data data)
12242 {
12243   inferior_event_handler (INF_REG_EVENT, NULL);
12244 }
12245
12246 static void
12247 remote_async (struct target_ops *ops, int enable)
12248 {
12249   struct remote_state *rs = get_remote_state ();
12250
12251   if (enable)
12252     {
12253       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
12254
12255       /* If there are pending events in the stop reply queue tell the
12256          event loop to process them.  */
12257       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
12258         mark_async_event_handler (remote_async_inferior_event_token);
12259     }
12260   else
12261     {
12262       serial_async (rs->remote_desc, NULL, NULL);
12263       clear_async_event_handler (remote_async_inferior_event_token);
12264     }
12265 }
12266
12267 static void
12268 set_remote_cmd (char *args, int from_tty)
12269 {
12270   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
12271 }
12272
12273 static void
12274 show_remote_cmd (char *args, int from_tty)
12275 {
12276   /* We can't just use cmd_show_list here, because we want to skip
12277      the redundant "show remote Z-packet" and the legacy aliases.  */
12278   struct cleanup *showlist_chain;
12279   struct cmd_list_element *list = remote_show_cmdlist;
12280   struct ui_out *uiout = current_uiout;
12281
12282   showlist_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "showlist");
12283   for (; list != NULL; list = list->next)
12284     if (strcmp (list->name, "Z-packet") == 0)
12285       continue;
12286     else if (list->type == not_set_cmd)
12287       /* Alias commands are exactly like the original, except they
12288          don't have the normal type.  */
12289       continue;
12290     else
12291       {
12292         struct cleanup *option_chain
12293           = make_cleanup_ui_out_tuple_begin_end (uiout, "option");
12294
12295         ui_out_field_string (uiout, "name", list->name);
12296         ui_out_text (uiout, ":  ");
12297         if (list->type == show_cmd)
12298           do_show_command ((char *) NULL, from_tty, list);
12299         else
12300           cmd_func (list, NULL, from_tty);
12301         /* Close the tuple.  */
12302         do_cleanups (option_chain);
12303       }
12304
12305   /* Close the tuple.  */
12306   do_cleanups (showlist_chain);
12307 }
12308
12309
12310 /* Function to be called whenever a new objfile (shlib) is detected.  */
12311 static void
12312 remote_new_objfile (struct objfile *objfile)
12313 {
12314   struct remote_state *rs = get_remote_state ();
12315
12316   if (rs->remote_desc != 0)             /* Have a remote connection.  */
12317     remote_check_symbols ();
12318 }
12319
12320 /* Pull all the tracepoints defined on the target and create local
12321    data structures representing them.  We don't want to create real
12322    tracepoints yet, we don't want to mess up the user's existing
12323    collection.  */
12324   
12325 static int
12326 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
12327 {
12328   struct remote_state *rs = get_remote_state ();
12329   char *p;
12330
12331   /* Ask for a first packet of tracepoint definition.  */
12332   putpkt ("qTfP");
12333   getpkt (&rs->buf, &rs->buf_size, 0);
12334   p = rs->buf;
12335   while (*p && *p != 'l')
12336     {
12337       parse_tracepoint_definition (p, utpp);
12338       /* Ask for another packet of tracepoint definition.  */
12339       putpkt ("qTsP");
12340       getpkt (&rs->buf, &rs->buf_size, 0);
12341       p = rs->buf;
12342     }
12343   return 0;
12344 }
12345
12346 static int
12347 remote_upload_trace_state_variables (struct target_ops *self,
12348                                      struct uploaded_tsv **utsvp)
12349 {
12350   struct remote_state *rs = get_remote_state ();
12351   char *p;
12352
12353   /* Ask for a first packet of variable definition.  */
12354   putpkt ("qTfV");
12355   getpkt (&rs->buf, &rs->buf_size, 0);
12356   p = rs->buf;
12357   while (*p && *p != 'l')
12358     {
12359       parse_tsv_definition (p, utsvp);
12360       /* Ask for another packet of variable definition.  */
12361       putpkt ("qTsV");
12362       getpkt (&rs->buf, &rs->buf_size, 0);
12363       p = rs->buf;
12364     }
12365   return 0;
12366 }
12367
12368 /* The "set/show range-stepping" show hook.  */
12369
12370 static void
12371 show_range_stepping (struct ui_file *file, int from_tty,
12372                      struct cmd_list_element *c,
12373                      const char *value)
12374 {
12375   fprintf_filtered (file,
12376                     _("Debugger's willingness to use range stepping "
12377                       "is %s.\n"), value);
12378 }
12379
12380 /* The "set/show range-stepping" set hook.  */
12381
12382 static void
12383 set_range_stepping (char *ignore_args, int from_tty,
12384                     struct cmd_list_element *c)
12385 {
12386   struct remote_state *rs = get_remote_state ();
12387
12388   /* Whene enabling, check whether range stepping is actually
12389      supported by the target, and warn if not.  */
12390   if (use_range_stepping)
12391     {
12392       if (rs->remote_desc != NULL)
12393         {
12394           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
12395             remote_vcont_probe (rs);
12396
12397           if (packet_support (PACKET_vCont) == PACKET_ENABLE
12398               && rs->supports_vCont.r)
12399             return;
12400         }
12401
12402       warning (_("Range stepping is not supported by the current target"));
12403     }
12404 }
12405
12406 void
12407 _initialize_remote (void)
12408 {
12409   struct remote_state *rs;
12410   struct cmd_list_element *cmd;
12411   const char *cmd_name;
12412
12413   /* architecture specific data */
12414   remote_gdbarch_data_handle =
12415     gdbarch_data_register_post_init (init_remote_state);
12416   remote_g_packet_data_handle =
12417     gdbarch_data_register_pre_init (remote_g_packet_data_init);
12418
12419   /* Initialize the per-target state.  At the moment there is only one
12420      of these, not one per target.  Only one target is active at a
12421      time.  */
12422   remote_state = new_remote_state ();
12423
12424   init_remote_ops ();
12425   add_target (&remote_ops);
12426
12427   init_extended_remote_ops ();
12428   add_target (&extended_remote_ops);
12429
12430   /* Hook into new objfile notification.  */
12431   observer_attach_new_objfile (remote_new_objfile);
12432   /* We're no longer interested in notification events of an inferior
12433      when it exits.  */
12434   observer_attach_inferior_exit (discard_pending_stop_replies);
12435
12436   /* Set up signal handlers.  */
12437   async_sigint_remote_token =
12438     create_async_signal_handler (async_remote_interrupt, NULL);
12439   async_sigint_remote_twice_token =
12440     create_async_signal_handler (async_remote_interrupt_twice, NULL);
12441
12442 #if 0
12443   init_remote_threadtests ();
12444 #endif
12445
12446   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
12447   /* set/show remote ...  */
12448
12449   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
12450 Remote protocol specific variables\n\
12451 Configure various remote-protocol specific variables such as\n\
12452 the packets being used"),
12453                   &remote_set_cmdlist, "set remote ",
12454                   0 /* allow-unknown */, &setlist);
12455   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
12456 Remote protocol specific variables\n\
12457 Configure various remote-protocol specific variables such as\n\
12458 the packets being used"),
12459                   &remote_show_cmdlist, "show remote ",
12460                   0 /* allow-unknown */, &showlist);
12461
12462   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
12463 Compare section data on target to the exec file.\n\
12464 Argument is a single section name (default: all loaded sections).\n\
12465 To compare only read-only loaded sections, specify the -r option."),
12466            &cmdlist);
12467
12468   add_cmd ("packet", class_maintenance, packet_command, _("\
12469 Send an arbitrary packet to a remote target.\n\
12470    maintenance packet TEXT\n\
12471 If GDB is talking to an inferior via the GDB serial protocol, then\n\
12472 this command sends the string TEXT to the inferior, and displays the\n\
12473 response packet.  GDB supplies the initial `$' character, and the\n\
12474 terminating `#' character and checksum."),
12475            &maintenancelist);
12476
12477   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
12478 Set whether to send break if interrupted."), _("\
12479 Show whether to send break if interrupted."), _("\
12480 If set, a break, instead of a cntrl-c, is sent to the remote target."),
12481                            set_remotebreak, show_remotebreak,
12482                            &setlist, &showlist);
12483   cmd_name = "remotebreak";
12484   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
12485   deprecate_cmd (cmd, "set remote interrupt-sequence");
12486   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
12487   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
12488   deprecate_cmd (cmd, "show remote interrupt-sequence");
12489
12490   add_setshow_enum_cmd ("interrupt-sequence", class_support,
12491                         interrupt_sequence_modes, &interrupt_sequence_mode,
12492                         _("\
12493 Set interrupt sequence to remote target."), _("\
12494 Show interrupt sequence to remote target."), _("\
12495 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
12496                         NULL, show_interrupt_sequence,
12497                         &remote_set_cmdlist,
12498                         &remote_show_cmdlist);
12499
12500   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
12501                            &interrupt_on_connect, _("\
12502 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
12503 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
12504 If set, interrupt sequence is sent to remote target."),
12505                            NULL, NULL,
12506                            &remote_set_cmdlist, &remote_show_cmdlist);
12507
12508   /* Install commands for configuring memory read/write packets.  */
12509
12510   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
12511 Set the maximum number of bytes per memory write packet (deprecated)."),
12512            &setlist);
12513   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
12514 Show the maximum number of bytes per memory write packet (deprecated)."),
12515            &showlist);
12516   add_cmd ("memory-write-packet-size", no_class,
12517            set_memory_write_packet_size, _("\
12518 Set the maximum number of bytes per memory-write packet.\n\
12519 Specify the number of bytes in a packet or 0 (zero) for the\n\
12520 default packet size.  The actual limit is further reduced\n\
12521 dependent on the target.  Specify ``fixed'' to disable the\n\
12522 further restriction and ``limit'' to enable that restriction."),
12523            &remote_set_cmdlist);
12524   add_cmd ("memory-read-packet-size", no_class,
12525            set_memory_read_packet_size, _("\
12526 Set the maximum number of bytes per memory-read packet.\n\
12527 Specify the number of bytes in a packet or 0 (zero) for the\n\
12528 default packet size.  The actual limit is further reduced\n\
12529 dependent on the target.  Specify ``fixed'' to disable the\n\
12530 further restriction and ``limit'' to enable that restriction."),
12531            &remote_set_cmdlist);
12532   add_cmd ("memory-write-packet-size", no_class,
12533            show_memory_write_packet_size,
12534            _("Show the maximum number of bytes per memory-write packet."),
12535            &remote_show_cmdlist);
12536   add_cmd ("memory-read-packet-size", no_class,
12537            show_memory_read_packet_size,
12538            _("Show the maximum number of bytes per memory-read packet."),
12539            &remote_show_cmdlist);
12540
12541   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
12542                             &remote_hw_watchpoint_limit, _("\
12543 Set the maximum number of target hardware watchpoints."), _("\
12544 Show the maximum number of target hardware watchpoints."), _("\
12545 Specify a negative limit for unlimited."),
12546                             NULL, NULL, /* FIXME: i18n: The maximum
12547                                            number of target hardware
12548                                            watchpoints is %s.  */
12549                             &remote_set_cmdlist, &remote_show_cmdlist);
12550   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
12551                             &remote_hw_watchpoint_length_limit, _("\
12552 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
12553 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
12554 Specify a negative limit for unlimited."),
12555                             NULL, NULL, /* FIXME: i18n: The maximum
12556                                            length (in bytes) of a target
12557                                            hardware watchpoint is %s.  */
12558                             &remote_set_cmdlist, &remote_show_cmdlist);
12559   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
12560                             &remote_hw_breakpoint_limit, _("\
12561 Set the maximum number of target hardware breakpoints."), _("\
12562 Show the maximum number of target hardware breakpoints."), _("\
12563 Specify a negative limit for unlimited."),
12564                             NULL, NULL, /* FIXME: i18n: The maximum
12565                                            number of target hardware
12566                                            breakpoints is %s.  */
12567                             &remote_set_cmdlist, &remote_show_cmdlist);
12568
12569   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
12570                              &remote_address_size, _("\
12571 Set the maximum size of the address (in bits) in a memory packet."), _("\
12572 Show the maximum size of the address (in bits) in a memory packet."), NULL,
12573                              NULL,
12574                              NULL, /* FIXME: i18n: */
12575                              &setlist, &showlist);
12576
12577   init_all_packet_configs ();
12578
12579   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
12580                          "X", "binary-download", 1);
12581
12582   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
12583                          "vCont", "verbose-resume", 0);
12584
12585   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
12586                          "QPassSignals", "pass-signals", 0);
12587
12588   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
12589                          "QProgramSignals", "program-signals", 0);
12590
12591   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
12592                          "qSymbol", "symbol-lookup", 0);
12593
12594   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
12595                          "P", "set-register", 1);
12596
12597   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
12598                          "p", "fetch-register", 1);
12599
12600   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
12601                          "Z0", "software-breakpoint", 0);
12602
12603   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
12604                          "Z1", "hardware-breakpoint", 0);
12605
12606   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
12607                          "Z2", "write-watchpoint", 0);
12608
12609   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
12610                          "Z3", "read-watchpoint", 0);
12611
12612   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
12613                          "Z4", "access-watchpoint", 0);
12614
12615   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
12616                          "qXfer:auxv:read", "read-aux-vector", 0);
12617
12618   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
12619                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
12620
12621   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
12622                          "qXfer:features:read", "target-features", 0);
12623
12624   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
12625                          "qXfer:libraries:read", "library-info", 0);
12626
12627   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
12628                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
12629
12630   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
12631                          "qXfer:memory-map:read", "memory-map", 0);
12632
12633   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
12634                          "qXfer:spu:read", "read-spu-object", 0);
12635
12636   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
12637                          "qXfer:spu:write", "write-spu-object", 0);
12638
12639   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
12640                         "qXfer:osdata:read", "osdata", 0);
12641
12642   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
12643                          "qXfer:threads:read", "threads", 0);
12644
12645   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
12646                          "qXfer:siginfo:read", "read-siginfo-object", 0);
12647
12648   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
12649                          "qXfer:siginfo:write", "write-siginfo-object", 0);
12650
12651   add_packet_config_cmd
12652     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
12653      "qXfer:traceframe-info:read", "traceframe-info", 0);
12654
12655   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
12656                          "qXfer:uib:read", "unwind-info-block", 0);
12657
12658   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
12659                          "qGetTLSAddr", "get-thread-local-storage-address",
12660                          0);
12661
12662   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
12663                          "qGetTIBAddr", "get-thread-information-block-address",
12664                          0);
12665
12666   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
12667                          "bc", "reverse-continue", 0);
12668
12669   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
12670                          "bs", "reverse-step", 0);
12671
12672   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
12673                          "qSupported", "supported-packets", 0);
12674
12675   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
12676                          "qSearch:memory", "search-memory", 0);
12677
12678   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
12679                          "qTStatus", "trace-status", 0);
12680
12681   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
12682                          "vFile:open", "hostio-open", 0);
12683
12684   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
12685                          "vFile:pread", "hostio-pread", 0);
12686
12687   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
12688                          "vFile:pwrite", "hostio-pwrite", 0);
12689
12690   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
12691                          "vFile:close", "hostio-close", 0);
12692
12693   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
12694                          "vFile:unlink", "hostio-unlink", 0);
12695
12696   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
12697                          "vFile:readlink", "hostio-readlink", 0);
12698
12699   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
12700                          "vFile:fstat", "hostio-fstat", 0);
12701
12702   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
12703                          "vAttach", "attach", 0);
12704
12705   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
12706                          "vRun", "run", 0);
12707
12708   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
12709                          "QStartNoAckMode", "noack", 0);
12710
12711   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
12712                          "vKill", "kill", 0);
12713
12714   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
12715                          "qAttached", "query-attached", 0);
12716
12717   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
12718                          "ConditionalTracepoints",
12719                          "conditional-tracepoints", 0);
12720
12721   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
12722                          "ConditionalBreakpoints",
12723                          "conditional-breakpoints", 0);
12724
12725   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
12726                          "BreakpointCommands",
12727                          "breakpoint-commands", 0);
12728
12729   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
12730                          "FastTracepoints", "fast-tracepoints", 0);
12731
12732   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
12733                          "TracepointSource", "TracepointSource", 0);
12734
12735   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
12736                          "QAllow", "allow", 0);
12737
12738   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
12739                          "StaticTracepoints", "static-tracepoints", 0);
12740
12741   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
12742                          "InstallInTrace", "install-in-trace", 0);
12743
12744   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
12745                          "qXfer:statictrace:read", "read-sdata-object", 0);
12746
12747   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
12748                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
12749
12750   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
12751                          "QDisableRandomization", "disable-randomization", 0);
12752
12753   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
12754                          "QAgent", "agent", 0);
12755
12756   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
12757                          "QTBuffer:size", "trace-buffer-size", 0);
12758
12759   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
12760        "Qbtrace:off", "disable-btrace", 0);
12761
12762   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
12763        "Qbtrace:bts", "enable-btrace", 0);
12764
12765   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
12766        "qXfer:btrace", "read-btrace", 0);
12767
12768   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
12769        "qXfer:btrace-conf", "read-btrace-conf", 0);
12770
12771   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
12772        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
12773
12774   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
12775                          "swbreak-feature", "swbreak-feature", 0);
12776
12777   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
12778                          "hwbreak-feature", "hwbreak-feature", 0);
12779
12780   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
12781                          "fork-event-feature", "fork-event-feature", 0);
12782
12783   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
12784                          "vfork-event-feature", "vfork-event-feature", 0);
12785
12786   /* Assert that we've registered "set remote foo-packet" commands
12787      for all packet configs.  */
12788   {
12789     int i;
12790
12791     for (i = 0; i < PACKET_MAX; i++)
12792       {
12793         /* Ideally all configs would have a command associated.  Some
12794            still don't though.  */
12795         int excepted;
12796
12797         switch (i)
12798           {
12799           case PACKET_QNonStop:
12800           case PACKET_multiprocess_feature:
12801           case PACKET_EnableDisableTracepoints_feature:
12802           case PACKET_tracenz_feature:
12803           case PACKET_DisconnectedTracing_feature:
12804           case PACKET_augmented_libraries_svr4_read_feature:
12805           case PACKET_qCRC:
12806             /* Additions to this list need to be well justified:
12807                pre-existing packets are OK; new packets are not.  */
12808             excepted = 1;
12809             break;
12810           default:
12811             excepted = 0;
12812             break;
12813           }
12814
12815         /* This catches both forgetting to add a config command, and
12816            forgetting to remove a packet from the exception list.  */
12817         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
12818       }
12819   }
12820
12821   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
12822      Z sub-packet has its own set and show commands, but users may
12823      have sets to this variable in their .gdbinit files (or in their
12824      documentation).  */
12825   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
12826                                 &remote_Z_packet_detect, _("\
12827 Set use of remote protocol `Z' packets"), _("\
12828 Show use of remote protocol `Z' packets "), _("\
12829 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
12830 packets."),
12831                                 set_remote_protocol_Z_packet_cmd,
12832                                 show_remote_protocol_Z_packet_cmd,
12833                                 /* FIXME: i18n: Use of remote protocol
12834                                    `Z' packets is %s.  */
12835                                 &remote_set_cmdlist, &remote_show_cmdlist);
12836
12837   add_prefix_cmd ("remote", class_files, remote_command, _("\
12838 Manipulate files on the remote system\n\
12839 Transfer files to and from the remote target system."),
12840                   &remote_cmdlist, "remote ",
12841                   0 /* allow-unknown */, &cmdlist);
12842
12843   add_cmd ("put", class_files, remote_put_command,
12844            _("Copy a local file to the remote system."),
12845            &remote_cmdlist);
12846
12847   add_cmd ("get", class_files, remote_get_command,
12848            _("Copy a remote file to the local system."),
12849            &remote_cmdlist);
12850
12851   add_cmd ("delete", class_files, remote_delete_command,
12852            _("Delete a remote file."),
12853            &remote_cmdlist);
12854
12855   remote_exec_file = xstrdup ("");
12856   add_setshow_string_noescape_cmd ("exec-file", class_files,
12857                                    &remote_exec_file, _("\
12858 Set the remote pathname for \"run\""), _("\
12859 Show the remote pathname for \"run\""), NULL, NULL, NULL,
12860                                    &remote_set_cmdlist, &remote_show_cmdlist);
12861
12862   add_setshow_boolean_cmd ("range-stepping", class_run,
12863                            &use_range_stepping, _("\
12864 Enable or disable range stepping."), _("\
12865 Show whether target-assisted range stepping is enabled."), _("\
12866 If on, and the target supports it, when stepping a source line, GDB\n\
12867 tells the target to step the corresponding range of addresses itself instead\n\
12868 of issuing multiple single-steps.  This speeds up source level\n\
12869 stepping.  If off, GDB always issues single-steps, even if range\n\
12870 stepping is supported by the target.  The default is on."),
12871                            set_range_stepping,
12872                            show_range_stepping,
12873                            &setlist,
12874                            &showlist);
12875
12876   /* Eventually initialize fileio.  See fileio.c */
12877   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
12878
12879   /* Take advantage of the fact that the TID field is not used, to tag
12880      special ptids with it set to != 0.  */
12881   magic_null_ptid = ptid_build (42000, -1, 1);
12882   not_sent_ptid = ptid_build (42000, -2, 1);
12883   any_thread_ptid = ptid_build (42000, 0, 1);
12884
12885   target_buf_size = 2048;
12886   target_buf = xmalloc (target_buf_size);
12887 }
12888