Fix remote 'g' command error handling (PR remote/9665)
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2018 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 "observable.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 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "common/scoped_restore.h"
76 #include "environ.h"
77 #include "common/byte-vector.h"
78
79 /* Per-program-space data key.  */
80 static const struct program_space_data *remote_pspace_data;
81
82 /* The variable registered as the control variable used by the
83    remote exec-file commands.  While the remote exec-file setting is
84    per-program-space, the set/show machinery uses this as the 
85    location of the remote exec-file value.  */
86 static char *remote_exec_file_var;
87
88 /* The size to align memory write packets, when practical.  The protocol
89    does not guarantee any alignment, and gdb will generate short
90    writes and unaligned writes, but even as a best-effort attempt this
91    can improve bulk transfers.  For instance, if a write is misaligned
92    relative to the target's data bus, the stub may need to make an extra
93    round trip fetching data from the target.  This doesn't make a
94    huge difference, but it's easy to do, so we try to be helpful.
95
96    The alignment chosen is arbitrary; usually data bus width is
97    important here, not the possibly larger cache line size.  */
98 enum { REMOTE_ALIGN_WRITES = 16 };
99
100 /* Prototypes for local functions.  */
101 static int getpkt_sane (char **buf, long *sizeof_buf, int forever);
102 static int getpkt_or_notif_sane (char **buf, long *sizeof_buf,
103                                  int forever, int *is_notif);
104
105 static void remote_files_info (struct target_ops *ignore);
106
107 static void remote_prepare_to_store (struct target_ops *self,
108                                      struct regcache *regcache);
109
110 static void remote_open_1 (const char *, int, struct target_ops *,
111                            int extended_p);
112
113 static void remote_close (struct target_ops *self);
114
115 struct remote_state;
116
117 static int remote_vkill (int pid, struct remote_state *rs);
118
119 static void remote_kill_k (void);
120
121 static void remote_mourn (struct target_ops *ops);
122
123 static void extended_remote_restart (void);
124
125 static int readchar (int timeout);
126
127 static void remote_serial_write (const char *str, int len);
128
129 static void remote_kill (struct target_ops *ops);
130
131 static int remote_can_async_p (struct target_ops *);
132
133 static int remote_is_async_p (struct target_ops *);
134
135 static void remote_async (struct target_ops *ops, int enable);
136
137 static void remote_thread_events (struct target_ops *ops, int enable);
138
139 static void interrupt_query (void);
140
141 static void set_general_thread (ptid_t ptid);
142 static void set_continue_thread (ptid_t ptid);
143
144 static void get_offsets (void);
145
146 static void skip_frame (void);
147
148 static long read_frame (char **buf_p, long *sizeof_buf);
149
150 static int hexnumlen (ULONGEST num);
151
152 static void init_remote_ops (void);
153
154 static void init_extended_remote_ops (void);
155
156 static void remote_stop (struct target_ops *self, ptid_t);
157
158 static int stubhex (int ch);
159
160 static int hexnumstr (char *, ULONGEST);
161
162 static int hexnumnstr (char *, ULONGEST, int);
163
164 static CORE_ADDR remote_address_masked (CORE_ADDR);
165
166 static void print_packet (const char *);
167
168 static int stub_unpack_int (char *buff, int fieldlength);
169
170 static ptid_t remote_current_thread (ptid_t oldptid);
171
172 static int putpkt_binary (const char *buf, int cnt);
173
174 static void check_binary_download (CORE_ADDR addr);
175
176 struct packet_config;
177
178 static void show_packet_config_cmd (struct packet_config *config);
179
180 static void show_remote_protocol_packet_cmd (struct ui_file *file,
181                                              int from_tty,
182                                              struct cmd_list_element *c,
183                                              const char *value);
184
185 static char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
186 static ptid_t read_ptid (const char *buf, const char **obuf);
187
188 static void remote_set_permissions (struct target_ops *self);
189
190 static int remote_get_trace_status (struct target_ops *self,
191                                     struct trace_status *ts);
192
193 static int remote_upload_tracepoints (struct target_ops *self,
194                                       struct uploaded_tp **utpp);
195
196 static int remote_upload_trace_state_variables (struct target_ops *self,
197                                                 struct uploaded_tsv **utsvp);
198   
199 static void remote_query_supported (void);
200
201 static void remote_check_symbols (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 static void remote_btrace_maybe_reopen (void);
228
229 static int stop_reply_queue_length (void);
230
231 static void readahead_cache_invalidate (void);
232
233 static void remote_unpush_and_throw (void);
234
235 static struct remote_state *get_remote_state (void);
236
237 /* For "remote".  */
238
239 static struct cmd_list_element *remote_cmdlist;
240
241 /* For "set remote" and "show remote".  */
242
243 static struct cmd_list_element *remote_set_cmdlist;
244 static struct cmd_list_element *remote_show_cmdlist;
245
246 /* Stub vCont actions support.
247
248    Each field is a boolean flag indicating whether the stub reports
249    support for the corresponding action.  */
250
251 struct vCont_action_support
252 {
253   /* vCont;t */
254   int t;
255
256   /* vCont;r */
257   int r;
258
259   /* vCont;s */
260   int s;
261
262   /* vCont;S */
263   int S;
264 };
265
266 /* Controls whether GDB is willing to use range stepping.  */
267
268 static int use_range_stepping = 1;
269
270 #define OPAQUETHREADBYTES 8
271
272 /* a 64 bit opaque identifier */
273 typedef unsigned char threadref[OPAQUETHREADBYTES];
274
275 /* About this many threadisds fit in a packet.  */
276
277 #define MAXTHREADLISTRESULTS 32
278
279 /* The max number of chars in debug output.  The rest of chars are
280    omitted.  */
281
282 #define REMOTE_DEBUG_MAX_CHAR 512
283
284 /* Data for the vFile:pread readahead cache.  */
285
286 struct readahead_cache
287 {
288   /* The file descriptor for the file that is being cached.  -1 if the
289      cache is invalid.  */
290   int fd;
291
292   /* The offset into the file that the cache buffer corresponds
293      to.  */
294   ULONGEST offset;
295
296   /* The buffer holding the cache contents.  */
297   gdb_byte *buf;
298   /* The buffer's size.  We try to read as much as fits into a packet
299      at a time.  */
300   size_t bufsize;
301
302   /* Cache hit and miss counters.  */
303   ULONGEST hit_count;
304   ULONGEST miss_count;
305 };
306
307 /* Description of the remote protocol state for the currently
308    connected target.  This is per-target state, and independent of the
309    selected architecture.  */
310
311 struct remote_state
312 {
313   /* A buffer to use for incoming packets, and its current size.  The
314      buffer is grown dynamically for larger incoming packets.
315      Outgoing packets may also be constructed in this buffer.
316      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
317      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
318      packets.  */
319   char *buf;
320   long buf_size;
321
322   /* True if we're going through initial connection setup (finding out
323      about the remote side's threads, relocating symbols, etc.).  */
324   int starting_up;
325
326   /* If we negotiated packet size explicitly (and thus can bypass
327      heuristics for the largest packet size that will not overflow
328      a buffer in the stub), this will be set to that packet size.
329      Otherwise zero, meaning to use the guessed size.  */
330   long explicit_packet_size;
331
332   /* remote_wait is normally called when the target is running and
333      waits for a stop reply packet.  But sometimes we need to call it
334      when the target is already stopped.  We can send a "?" packet
335      and have remote_wait read the response.  Or, if we already have
336      the response, we can stash it in BUF and tell remote_wait to
337      skip calling getpkt.  This flag is set when BUF contains a
338      stop reply packet and the target is not waiting.  */
339   int cached_wait_status;
340
341   /* True, if in no ack mode.  That is, neither GDB nor the stub will
342      expect acks from each other.  The connection is assumed to be
343      reliable.  */
344   int noack_mode;
345
346   /* True if we're connected in extended remote mode.  */
347   int extended;
348
349   /* True if we resumed the target and we're waiting for the target to
350      stop.  In the mean time, we can't start another command/query.
351      The remote server wouldn't be ready to process it, so we'd
352      timeout waiting for a reply that would never come and eventually
353      we'd close the connection.  This can happen in asynchronous mode
354      because we allow GDB commands while the target is running.  */
355   int waiting_for_stop_reply;
356
357   /* The status of the stub support for the various vCont actions.  */
358   struct vCont_action_support supports_vCont;
359
360   /* Nonzero if the user has pressed Ctrl-C, but the target hasn't
361      responded to that.  */
362   int ctrlc_pending_p;
363
364   /* True if we saw a Ctrl-C while reading or writing from/to the
365      remote descriptor.  At that point it is not safe to send a remote
366      interrupt packet, so we instead remember we saw the Ctrl-C and
367      process it once we're done with sending/receiving the current
368      packet, which should be shortly.  If however that takes too long,
369      and the user presses Ctrl-C again, we offer to disconnect.  */
370   int got_ctrlc_during_io;
371
372   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
373      remote_open knows that we don't have a file open when the program
374      starts.  */
375   struct serial *remote_desc;
376
377   /* These are the threads which we last sent to the remote system.  The
378      TID member will be -1 for all or -2 for not sent yet.  */
379   ptid_t general_thread;
380   ptid_t continue_thread;
381
382   /* This is the traceframe which we last selected on the remote system.
383      It will be -1 if no traceframe is selected.  */
384   int remote_traceframe_number;
385
386   char *last_pass_packet;
387
388   /* The last QProgramSignals packet sent to the target.  We bypass
389      sending a new program signals list down to the target if the new
390      packet is exactly the same as the last we sent.  IOW, we only let
391      the target know about program signals list changes.  */
392   char *last_program_signals_packet;
393
394   enum gdb_signal last_sent_signal;
395
396   int last_sent_step;
397
398   /* The execution direction of the last resume we got.  */
399   enum exec_direction_kind last_resume_exec_dir;
400
401   char *finished_object;
402   char *finished_annex;
403   ULONGEST finished_offset;
404
405   /* Should we try the 'ThreadInfo' query packet?
406
407      This variable (NOT available to the user: auto-detect only!)
408      determines whether GDB will use the new, simpler "ThreadInfo"
409      query or the older, more complex syntax for thread queries.
410      This is an auto-detect variable (set to true at each connect,
411      and set to false when the target fails to recognize it).  */
412   int use_threadinfo_query;
413   int use_threadextra_query;
414
415   threadref echo_nextthread;
416   threadref nextthread;
417   threadref resultthreadlist[MAXTHREADLISTRESULTS];
418
419   /* The state of remote notification.  */
420   struct remote_notif_state *notif_state;
421
422   /* The branch trace configuration.  */
423   struct btrace_config btrace_config;
424
425   /* The argument to the last "vFile:setfs:" packet we sent, used
426      to avoid sending repeated unnecessary "vFile:setfs:" packets.
427      Initialized to -1 to indicate that no "vFile:setfs:" packet
428      has yet been sent.  */
429   int fs_pid;
430
431   /* A readahead cache for vFile:pread.  Often, reading a binary
432      involves a sequence of small reads.  E.g., when parsing an ELF
433      file.  A readahead cache helps mostly the case of remote
434      debugging on a connection with higher latency, due to the
435      request/reply nature of the RSP.  We only cache data for a single
436      file descriptor at a time.  */
437   struct readahead_cache readahead_cache;
438 };
439
440 /* Private data that we'll store in (struct thread_info)->priv.  */
441 struct remote_thread_info : public private_thread_info
442 {
443   std::string extra;
444   std::string name;
445   int core = -1;
446
447   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
448      sequence of bytes.  */
449   gdb::byte_vector thread_handle;
450
451   /* Whether the target stopped for a breakpoint/watchpoint.  */
452   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
453
454   /* This is set to the data address of the access causing the target
455      to stop for a watchpoint.  */
456   CORE_ADDR watch_data_address = 0;
457
458   /* Fields used by the vCont action coalescing implemented in
459      remote_resume / remote_commit_resume.  remote_resume stores each
460      thread's last resume request in these fields, so that a later
461      remote_commit_resume knows which is the proper action for this
462      thread to include in the vCont packet.  */
463
464   /* True if the last target_resume call for this thread was a step
465      request, false if a continue request.  */
466   int last_resume_step = 0;
467
468   /* The signal specified in the last target_resume call for this
469      thread.  */
470   gdb_signal last_resume_sig = GDB_SIGNAL_0;
471
472   /* Whether this thread was already vCont-resumed on the remote
473      side.  */
474   int vcont_resumed = 0;
475 };
476
477 /* This data could be associated with a target, but we do not always
478    have access to the current target when we need it, so for now it is
479    static.  This will be fine for as long as only one target is in use
480    at a time.  */
481 static struct remote_state *remote_state;
482
483 static struct remote_state *
484 get_remote_state_raw (void)
485 {
486   return remote_state;
487 }
488
489 /* Allocate a new struct remote_state with xmalloc, initialize it, and
490    return it.  */
491
492 static struct remote_state *
493 new_remote_state (void)
494 {
495   struct remote_state *result = XCNEW (struct remote_state);
496
497   /* The default buffer size is unimportant; it will be expanded
498      whenever a larger buffer is needed. */
499   result->buf_size = 400;
500   result->buf = (char *) xmalloc (result->buf_size);
501   result->remote_traceframe_number = -1;
502   result->last_sent_signal = GDB_SIGNAL_0;
503   result->last_resume_exec_dir = EXEC_FORWARD;
504   result->fs_pid = -1;
505
506   return result;
507 }
508
509 /* Description of the remote protocol for a given architecture.  */
510
511 struct packet_reg
512 {
513   long offset; /* Offset into G packet.  */
514   long regnum; /* GDB's internal register number.  */
515   LONGEST pnum; /* Remote protocol register number.  */
516   int in_g_packet; /* Always part of G packet.  */
517   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
518      at present.  */
519   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
520      at present.  */
521 };
522
523 struct remote_arch_state
524 {
525   /* Description of the remote protocol registers.  */
526   long sizeof_g_packet;
527
528   /* Description of the remote protocol registers indexed by REGNUM
529      (making an array gdbarch_num_regs in size).  */
530   struct packet_reg *regs;
531
532   /* This is the size (in chars) of the first response to the ``g''
533      packet.  It is used as a heuristic when determining the maximum
534      size of memory-read and memory-write packets.  A target will
535      typically only reserve a buffer large enough to hold the ``g''
536      packet.  The size does not include packet overhead (headers and
537      trailers).  */
538   long actual_register_packet_size;
539
540   /* This is the maximum size (in chars) of a non read/write packet.
541      It is also used as a cap on the size of read/write packets.  */
542   long remote_packet_size;
543 };
544
545 /* Utility: generate error from an incoming stub packet.  */
546 static void
547 trace_error (char *buf)
548 {
549   if (*buf++ != 'E')
550     return;                     /* not an error msg */
551   switch (*buf)
552     {
553     case '1':                   /* malformed packet error */
554       if (*++buf == '0')        /*   general case: */
555         error (_("remote.c: error in outgoing packet."));
556       else
557         error (_("remote.c: error in outgoing packet at field #%ld."),
558                strtol (buf, NULL, 16));
559     default:
560       error (_("Target returns error code '%s'."), buf);
561     }
562 }
563
564 /* Utility: wait for reply from stub, while accepting "O" packets.  */
565
566 static char *
567 remote_get_noisy_reply ()
568 {
569   struct remote_state *rs = get_remote_state ();
570
571   do                            /* Loop on reply from remote stub.  */
572     {
573       char *buf;
574
575       QUIT;                     /* Allow user to bail out with ^C.  */
576       getpkt (&rs->buf, &rs->buf_size, 0);
577       buf = rs->buf;
578       if (buf[0] == 'E')
579         trace_error (buf);
580       else if (startswith (buf, "qRelocInsn:"))
581         {
582           ULONGEST ul;
583           CORE_ADDR from, to, org_to;
584           const char *p, *pp;
585           int adjusted_size = 0;
586           int relocated = 0;
587
588           p = buf + strlen ("qRelocInsn:");
589           pp = unpack_varlen_hex (p, &ul);
590           if (*pp != ';')
591             error (_("invalid qRelocInsn packet: %s"), buf);
592           from = ul;
593
594           p = pp + 1;
595           unpack_varlen_hex (p, &ul);
596           to = ul;
597
598           org_to = to;
599
600           TRY
601             {
602               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
603               relocated = 1;
604             }
605           CATCH (ex, RETURN_MASK_ALL)
606             {
607               if (ex.error == MEMORY_ERROR)
608                 {
609                   /* Propagate memory errors silently back to the
610                      target.  The stub may have limited the range of
611                      addresses we can write to, for example.  */
612                 }
613               else
614                 {
615                   /* Something unexpectedly bad happened.  Be verbose
616                      so we can tell what, and propagate the error back
617                      to the stub, so it doesn't get stuck waiting for
618                      a response.  */
619                   exception_fprintf (gdb_stderr, ex,
620                                      _("warning: relocating instruction: "));
621                 }
622               putpkt ("E01");
623             }
624           END_CATCH
625
626           if (relocated)
627             {
628               adjusted_size = to - org_to;
629
630               xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
631               putpkt (buf);
632             }
633         }
634       else if (buf[0] == 'O' && buf[1] != 'K')
635         remote_console_output (buf + 1);        /* 'O' message from stub */
636       else
637         return buf;             /* Here's the actual reply.  */
638     }
639   while (1);
640 }
641
642 /* Handle for retreving the remote protocol data from gdbarch.  */
643 static struct gdbarch_data *remote_gdbarch_data_handle;
644
645 static struct remote_arch_state *
646 get_remote_arch_state (struct gdbarch *gdbarch)
647 {
648   gdb_assert (gdbarch != NULL);
649   return ((struct remote_arch_state *)
650           gdbarch_data (gdbarch, remote_gdbarch_data_handle));
651 }
652
653 /* Fetch the global remote target state.  */
654
655 static struct remote_state *
656 get_remote_state (void)
657 {
658   /* Make sure that the remote architecture state has been
659      initialized, because doing so might reallocate rs->buf.  Any
660      function which calls getpkt also needs to be mindful of changes
661      to rs->buf, but this call limits the number of places which run
662      into trouble.  */
663   get_remote_arch_state (target_gdbarch ());
664
665   return get_remote_state_raw ();
666 }
667
668 /* Cleanup routine for the remote module's pspace data.  */
669
670 static void
671 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
672 {
673   char *remote_exec_file = (char *) arg;
674
675   xfree (remote_exec_file);
676 }
677
678 /* Fetch the remote exec-file from the current program space.  */
679
680 static const char *
681 get_remote_exec_file (void)
682 {
683   char *remote_exec_file;
684
685   remote_exec_file
686     = (char *) program_space_data (current_program_space,
687                                    remote_pspace_data);
688   if (remote_exec_file == NULL)
689     return "";
690
691   return remote_exec_file;
692 }
693
694 /* Set the remote exec file for PSPACE.  */
695
696 static void
697 set_pspace_remote_exec_file (struct program_space *pspace,
698                         char *remote_exec_file)
699 {
700   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
701
702   xfree (old_file);
703   set_program_space_data (pspace, remote_pspace_data,
704                           xstrdup (remote_exec_file));
705 }
706
707 /* The "set/show remote exec-file" set command hook.  */
708
709 static void
710 set_remote_exec_file (const char *ignored, int from_tty,
711                       struct cmd_list_element *c)
712 {
713   gdb_assert (remote_exec_file_var != NULL);
714   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
715 }
716
717 /* The "set/show remote exec-file" show command hook.  */
718
719 static void
720 show_remote_exec_file (struct ui_file *file, int from_tty,
721                        struct cmd_list_element *cmd, const char *value)
722 {
723   fprintf_filtered (file, "%s\n", remote_exec_file_var);
724 }
725
726 static int
727 compare_pnums (const void *lhs_, const void *rhs_)
728 {
729   const struct packet_reg * const *lhs
730     = (const struct packet_reg * const *) lhs_;
731   const struct packet_reg * const *rhs
732     = (const struct packet_reg * const *) rhs_;
733
734   if ((*lhs)->pnum < (*rhs)->pnum)
735     return -1;
736   else if ((*lhs)->pnum == (*rhs)->pnum)
737     return 0;
738   else
739     return 1;
740 }
741
742 static int
743 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
744 {
745   int regnum, num_remote_regs, offset;
746   struct packet_reg **remote_regs;
747
748   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
749     {
750       struct packet_reg *r = &regs[regnum];
751
752       if (register_size (gdbarch, regnum) == 0)
753         /* Do not try to fetch zero-sized (placeholder) registers.  */
754         r->pnum = -1;
755       else
756         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
757
758       r->regnum = regnum;
759     }
760
761   /* Define the g/G packet format as the contents of each register
762      with a remote protocol number, in order of ascending protocol
763      number.  */
764
765   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
766   for (num_remote_regs = 0, regnum = 0;
767        regnum < gdbarch_num_regs (gdbarch);
768        regnum++)
769     if (regs[regnum].pnum != -1)
770       remote_regs[num_remote_regs++] = &regs[regnum];
771
772   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
773          compare_pnums);
774
775   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
776     {
777       remote_regs[regnum]->in_g_packet = 1;
778       remote_regs[regnum]->offset = offset;
779       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
780     }
781
782   return offset;
783 }
784
785 /* Given the architecture described by GDBARCH, return the remote
786    protocol register's number and the register's offset in the g/G
787    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
788    If the target does not have a mapping for REGNUM, return false,
789    otherwise, return true.  */
790
791 int
792 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
793                                    int *pnum, int *poffset)
794 {
795   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
796
797   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
798
799   map_regcache_remote_table (gdbarch, regs.data ());
800
801   *pnum = regs[regnum].pnum;
802   *poffset = regs[regnum].offset;
803
804   return *pnum != -1;
805 }
806
807 static void *
808 init_remote_state (struct gdbarch *gdbarch)
809 {
810   struct remote_state *rs = get_remote_state_raw ();
811   struct remote_arch_state *rsa;
812
813   rsa = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct remote_arch_state);
814
815   /* Use the architecture to build a regnum<->pnum table, which will be
816      1:1 unless a feature set specifies otherwise.  */
817   rsa->regs = GDBARCH_OBSTACK_CALLOC (gdbarch,
818                                       gdbarch_num_regs (gdbarch),
819                                       struct packet_reg);
820
821   /* Record the maximum possible size of the g packet - it may turn out
822      to be smaller.  */
823   rsa->sizeof_g_packet = map_regcache_remote_table (gdbarch, rsa->regs);
824
825   /* Default maximum number of characters in a packet body.  Many
826      remote stubs have a hardwired buffer size of 400 bytes
827      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
828      as the maximum packet-size to ensure that the packet and an extra
829      NUL character can always fit in the buffer.  This stops GDB
830      trashing stubs that try to squeeze an extra NUL into what is
831      already a full buffer (As of 1999-12-04 that was most stubs).  */
832   rsa->remote_packet_size = 400 - 1;
833
834   /* This one is filled in when a ``g'' packet is received.  */
835   rsa->actual_register_packet_size = 0;
836
837   /* Should rsa->sizeof_g_packet needs more space than the
838      default, adjust the size accordingly.  Remember that each byte is
839      encoded as two characters.  32 is the overhead for the packet
840      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
841      (``$NN:G...#NN'') is a better guess, the below has been padded a
842      little.  */
843   if (rsa->sizeof_g_packet > ((rsa->remote_packet_size - 32) / 2))
844     rsa->remote_packet_size = (rsa->sizeof_g_packet * 2 + 32);
845
846   /* Make sure that the packet buffer is plenty big enough for
847      this architecture.  */
848   if (rs->buf_size < rsa->remote_packet_size)
849     {
850       rs->buf_size = 2 * rsa->remote_packet_size;
851       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
852     }
853
854   return rsa;
855 }
856
857 /* Return the current allowed size of a remote packet.  This is
858    inferred from the current architecture, and should be used to
859    limit the length of outgoing packets.  */
860 static long
861 get_remote_packet_size (void)
862 {
863   struct remote_state *rs = get_remote_state ();
864   remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
865
866   if (rs->explicit_packet_size)
867     return rs->explicit_packet_size;
868
869   return rsa->remote_packet_size;
870 }
871
872 static struct packet_reg *
873 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
874                         long regnum)
875 {
876   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
877     return NULL;
878   else
879     {
880       struct packet_reg *r = &rsa->regs[regnum];
881
882       gdb_assert (r->regnum == regnum);
883       return r;
884     }
885 }
886
887 static struct packet_reg *
888 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
889                       LONGEST pnum)
890 {
891   int i;
892
893   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
894     {
895       struct packet_reg *r = &rsa->regs[i];
896
897       if (r->pnum == pnum)
898         return r;
899     }
900   return NULL;
901 }
902
903 static struct target_ops remote_ops;
904
905 static struct target_ops extended_remote_ops;
906
907 /* FIXME: cagney/1999-09-23: Even though getpkt was called with
908    ``forever'' still use the normal timeout mechanism.  This is
909    currently used by the ASYNC code to guarentee that target reads
910    during the initial connect always time-out.  Once getpkt has been
911    modified to return a timeout indication and, in turn
912    remote_wait()/wait_for_inferior() have gained a timeout parameter
913    this can go away.  */
914 static int wait_forever_enabled_p = 1;
915
916 /* Allow the user to specify what sequence to send to the remote
917    when he requests a program interruption: Although ^C is usually
918    what remote systems expect (this is the default, here), it is
919    sometimes preferable to send a break.  On other systems such
920    as the Linux kernel, a break followed by g, which is Magic SysRq g
921    is required in order to interrupt the execution.  */
922 const char interrupt_sequence_control_c[] = "Ctrl-C";
923 const char interrupt_sequence_break[] = "BREAK";
924 const char interrupt_sequence_break_g[] = "BREAK-g";
925 static const char *const interrupt_sequence_modes[] =
926   {
927     interrupt_sequence_control_c,
928     interrupt_sequence_break,
929     interrupt_sequence_break_g,
930     NULL
931   };
932 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
933
934 static void
935 show_interrupt_sequence (struct ui_file *file, int from_tty,
936                          struct cmd_list_element *c,
937                          const char *value)
938 {
939   if (interrupt_sequence_mode == interrupt_sequence_control_c)
940     fprintf_filtered (file,
941                       _("Send the ASCII ETX character (Ctrl-c) "
942                         "to the remote target to interrupt the "
943                         "execution of the program.\n"));
944   else if (interrupt_sequence_mode == interrupt_sequence_break)
945     fprintf_filtered (file,
946                       _("send a break signal to the remote target "
947                         "to interrupt the execution of the program.\n"));
948   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
949     fprintf_filtered (file,
950                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
951                         "the remote target to interrupt the execution "
952                         "of Linux kernel.\n"));
953   else
954     internal_error (__FILE__, __LINE__,
955                     _("Invalid value for interrupt_sequence_mode: %s."),
956                     interrupt_sequence_mode);
957 }
958
959 /* This boolean variable specifies whether interrupt_sequence is sent
960    to the remote target when gdb connects to it.
961    This is mostly needed when you debug the Linux kernel: The Linux kernel
962    expects BREAK g which is Magic SysRq g for connecting gdb.  */
963 static int interrupt_on_connect = 0;
964
965 /* This variable is used to implement the "set/show remotebreak" commands.
966    Since these commands are now deprecated in favor of "set/show remote
967    interrupt-sequence", it no longer has any effect on the code.  */
968 static int remote_break;
969
970 static void
971 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
972 {
973   if (remote_break)
974     interrupt_sequence_mode = interrupt_sequence_break;
975   else
976     interrupt_sequence_mode = interrupt_sequence_control_c;
977 }
978
979 static void
980 show_remotebreak (struct ui_file *file, int from_tty,
981                   struct cmd_list_element *c,
982                   const char *value)
983 {
984 }
985
986 /* This variable sets the number of bits in an address that are to be
987    sent in a memory ("M" or "m") packet.  Normally, after stripping
988    leading zeros, the entire address would be sent.  This variable
989    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
990    initial implementation of remote.c restricted the address sent in
991    memory packets to ``host::sizeof long'' bytes - (typically 32
992    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
993    address was never sent.  Since fixing this bug may cause a break in
994    some remote targets this variable is principly provided to
995    facilitate backward compatibility.  */
996
997 static unsigned int remote_address_size;
998
999 \f
1000 /* User configurable variables for the number of characters in a
1001    memory read/write packet.  MIN (rsa->remote_packet_size,
1002    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1003    values (fifo overruns, et.al.) and some users need larger values
1004    (speed up transfers).  The variables ``preferred_*'' (the user
1005    request), ``current_*'' (what was actually set) and ``forced_*''
1006    (Positive - a soft limit, negative - a hard limit).  */
1007
1008 struct memory_packet_config
1009 {
1010   const char *name;
1011   long size;
1012   int fixed_p;
1013 };
1014
1015 /* The default max memory-write-packet-size.  The 16k is historical.
1016    (It came from older GDB's using alloca for buffers and the
1017    knowledge (folklore?) that some hosts don't cope very well with
1018    large alloca calls.)  */
1019 #define DEFAULT_MAX_MEMORY_PACKET_SIZE 16384
1020
1021 /* The minimum remote packet size for memory transfers.  Ensures we
1022    can write at least one byte.  */
1023 #define MIN_MEMORY_PACKET_SIZE 20
1024
1025 /* Compute the current size of a read/write packet.  Since this makes
1026    use of ``actual_register_packet_size'' the computation is dynamic.  */
1027
1028 static long
1029 get_memory_packet_size (struct memory_packet_config *config)
1030 {
1031   struct remote_state *rs = get_remote_state ();
1032   remote_arch_state *rsa = get_remote_arch_state (target_gdbarch ());
1033
1034   long what_they_get;
1035   if (config->fixed_p)
1036     {
1037       if (config->size <= 0)
1038         what_they_get = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1039       else
1040         what_they_get = config->size;
1041     }
1042   else
1043     {
1044       what_they_get = get_remote_packet_size ();
1045       /* Limit the packet to the size specified by the user.  */
1046       if (config->size > 0
1047           && what_they_get > config->size)
1048         what_they_get = config->size;
1049
1050       /* Limit it to the size of the targets ``g'' response unless we have
1051          permission from the stub to use a larger packet size.  */
1052       if (rs->explicit_packet_size == 0
1053           && rsa->actual_register_packet_size > 0
1054           && what_they_get > rsa->actual_register_packet_size)
1055         what_they_get = rsa->actual_register_packet_size;
1056     }
1057   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1058     what_they_get = MIN_MEMORY_PACKET_SIZE;
1059
1060   /* Make sure there is room in the global buffer for this packet
1061      (including its trailing NUL byte).  */
1062   if (rs->buf_size < what_they_get + 1)
1063     {
1064       rs->buf_size = 2 * what_they_get;
1065       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1066     }
1067
1068   return what_they_get;
1069 }
1070
1071 /* Update the size of a read/write packet.  If they user wants
1072    something really big then do a sanity check.  */
1073
1074 static void
1075 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1076 {
1077   int fixed_p = config->fixed_p;
1078   long size = config->size;
1079
1080   if (args == NULL)
1081     error (_("Argument required (integer, `fixed' or `limited')."));
1082   else if (strcmp (args, "hard") == 0
1083       || strcmp (args, "fixed") == 0)
1084     fixed_p = 1;
1085   else if (strcmp (args, "soft") == 0
1086            || strcmp (args, "limit") == 0)
1087     fixed_p = 0;
1088   else
1089     {
1090       char *end;
1091
1092       size = strtoul (args, &end, 0);
1093       if (args == end)
1094         error (_("Invalid %s (bad syntax)."), config->name);
1095
1096       /* Instead of explicitly capping the size of a packet to or
1097          disallowing it, the user is allowed to set the size to
1098          something arbitrarily large.  */
1099     }
1100
1101   /* So that the query shows the correct value.  */
1102   if (size <= 0)
1103     size = DEFAULT_MAX_MEMORY_PACKET_SIZE;
1104
1105   /* Extra checks?  */
1106   if (fixed_p && !config->fixed_p)
1107     {
1108       if (! query (_("The target may not be able to correctly handle a %s\n"
1109                    "of %ld bytes. Change the packet size? "),
1110                    config->name, size))
1111         error (_("Packet size not changed."));
1112     }
1113   /* Update the config.  */
1114   config->fixed_p = fixed_p;
1115   config->size = size;
1116 }
1117
1118 static void
1119 show_memory_packet_size (struct memory_packet_config *config)
1120 {
1121   printf_filtered (_("The %s is %ld. "), config->name, config->size);
1122   if (config->fixed_p)
1123     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1124                      get_memory_packet_size (config));
1125   else
1126     printf_filtered (_("Packets are limited to %ld bytes.\n"),
1127                      get_memory_packet_size (config));
1128 }
1129
1130 static struct memory_packet_config memory_write_packet_config =
1131 {
1132   "memory-write-packet-size",
1133 };
1134
1135 static void
1136 set_memory_write_packet_size (const char *args, int from_tty)
1137 {
1138   set_memory_packet_size (args, &memory_write_packet_config);
1139 }
1140
1141 static void
1142 show_memory_write_packet_size (const char *args, int from_tty)
1143 {
1144   show_memory_packet_size (&memory_write_packet_config);
1145 }
1146
1147 static long
1148 get_memory_write_packet_size (void)
1149 {
1150   return get_memory_packet_size (&memory_write_packet_config);
1151 }
1152
1153 static struct memory_packet_config memory_read_packet_config =
1154 {
1155   "memory-read-packet-size",
1156 };
1157
1158 static void
1159 set_memory_read_packet_size (const char *args, int from_tty)
1160 {
1161   set_memory_packet_size (args, &memory_read_packet_config);
1162 }
1163
1164 static void
1165 show_memory_read_packet_size (const char *args, int from_tty)
1166 {
1167   show_memory_packet_size (&memory_read_packet_config);
1168 }
1169
1170 static long
1171 get_memory_read_packet_size (void)
1172 {
1173   long size = get_memory_packet_size (&memory_read_packet_config);
1174
1175   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1176      extra buffer size argument before the memory read size can be
1177      increased beyond this.  */
1178   if (size > get_remote_packet_size ())
1179     size = get_remote_packet_size ();
1180   return size;
1181 }
1182
1183 \f
1184 /* Generic configuration support for packets the stub optionally
1185    supports.  Allows the user to specify the use of the packet as well
1186    as allowing GDB to auto-detect support in the remote stub.  */
1187
1188 enum packet_support
1189   {
1190     PACKET_SUPPORT_UNKNOWN = 0,
1191     PACKET_ENABLE,
1192     PACKET_DISABLE
1193   };
1194
1195 struct packet_config
1196   {
1197     const char *name;
1198     const char *title;
1199
1200     /* If auto, GDB auto-detects support for this packet or feature,
1201        either through qSupported, or by trying the packet and looking
1202        at the response.  If true, GDB assumes the target supports this
1203        packet.  If false, the packet is disabled.  Configs that don't
1204        have an associated command always have this set to auto.  */
1205     enum auto_boolean detect;
1206
1207     /* Does the target support this packet?  */
1208     enum packet_support support;
1209   };
1210
1211 /* Analyze a packet's return value and update the packet config
1212    accordingly.  */
1213
1214 enum packet_result
1215 {
1216   PACKET_ERROR,
1217   PACKET_OK,
1218   PACKET_UNKNOWN
1219 };
1220
1221 static enum packet_support packet_config_support (struct packet_config *config);
1222 static enum packet_support packet_support (int packet);
1223
1224 static void
1225 show_packet_config_cmd (struct packet_config *config)
1226 {
1227   const char *support = "internal-error";
1228
1229   switch (packet_config_support (config))
1230     {
1231     case PACKET_ENABLE:
1232       support = "enabled";
1233       break;
1234     case PACKET_DISABLE:
1235       support = "disabled";
1236       break;
1237     case PACKET_SUPPORT_UNKNOWN:
1238       support = "unknown";
1239       break;
1240     }
1241   switch (config->detect)
1242     {
1243     case AUTO_BOOLEAN_AUTO:
1244       printf_filtered (_("Support for the `%s' packet "
1245                          "is auto-detected, currently %s.\n"),
1246                        config->name, support);
1247       break;
1248     case AUTO_BOOLEAN_TRUE:
1249     case AUTO_BOOLEAN_FALSE:
1250       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1251                        config->name, support);
1252       break;
1253     }
1254 }
1255
1256 static void
1257 add_packet_config_cmd (struct packet_config *config, const char *name,
1258                        const char *title, int legacy)
1259 {
1260   char *set_doc;
1261   char *show_doc;
1262   char *cmd_name;
1263
1264   config->name = name;
1265   config->title = title;
1266   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1267                         name, title);
1268   show_doc = xstrprintf ("Show current use of remote "
1269                          "protocol `%s' (%s) packet",
1270                          name, title);
1271   /* set/show TITLE-packet {auto,on,off} */
1272   cmd_name = xstrprintf ("%s-packet", title);
1273   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1274                                 &config->detect, set_doc,
1275                                 show_doc, NULL, /* help_doc */
1276                                 NULL,
1277                                 show_remote_protocol_packet_cmd,
1278                                 &remote_set_cmdlist, &remote_show_cmdlist);
1279   /* The command code copies the documentation strings.  */
1280   xfree (set_doc);
1281   xfree (show_doc);
1282   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1283   if (legacy)
1284     {
1285       char *legacy_name;
1286
1287       legacy_name = xstrprintf ("%s-packet", name);
1288       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1289                      &remote_set_cmdlist);
1290       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1291                      &remote_show_cmdlist);
1292     }
1293 }
1294
1295 static enum packet_result
1296 packet_check_result (const char *buf)
1297 {
1298   if (buf[0] != '\0')
1299     {
1300       /* The stub recognized the packet request.  Check that the
1301          operation succeeded.  */
1302       if (buf[0] == 'E'
1303           && isxdigit (buf[1]) && isxdigit (buf[2])
1304           && buf[3] == '\0')
1305         /* "Enn"  - definitly an error.  */
1306         return PACKET_ERROR;
1307
1308       /* Always treat "E." as an error.  This will be used for
1309          more verbose error messages, such as E.memtypes.  */
1310       if (buf[0] == 'E' && buf[1] == '.')
1311         return PACKET_ERROR;
1312
1313       /* The packet may or may not be OK.  Just assume it is.  */
1314       return PACKET_OK;
1315     }
1316   else
1317     /* The stub does not support the packet.  */
1318     return PACKET_UNKNOWN;
1319 }
1320
1321 static enum packet_result
1322 packet_ok (const char *buf, struct packet_config *config)
1323 {
1324   enum packet_result result;
1325
1326   if (config->detect != AUTO_BOOLEAN_TRUE
1327       && config->support == PACKET_DISABLE)
1328     internal_error (__FILE__, __LINE__,
1329                     _("packet_ok: attempt to use a disabled packet"));
1330
1331   result = packet_check_result (buf);
1332   switch (result)
1333     {
1334     case PACKET_OK:
1335     case PACKET_ERROR:
1336       /* The stub recognized the packet request.  */
1337       if (config->support == PACKET_SUPPORT_UNKNOWN)
1338         {
1339           if (remote_debug)
1340             fprintf_unfiltered (gdb_stdlog,
1341                                 "Packet %s (%s) is supported\n",
1342                                 config->name, config->title);
1343           config->support = PACKET_ENABLE;
1344         }
1345       break;
1346     case PACKET_UNKNOWN:
1347       /* The stub does not support the packet.  */
1348       if (config->detect == AUTO_BOOLEAN_AUTO
1349           && config->support == PACKET_ENABLE)
1350         {
1351           /* If the stub previously indicated that the packet was
1352              supported then there is a protocol error.  */
1353           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1354                  config->name, config->title);
1355         }
1356       else if (config->detect == AUTO_BOOLEAN_TRUE)
1357         {
1358           /* The user set it wrong.  */
1359           error (_("Enabled packet %s (%s) not recognized by stub"),
1360                  config->name, config->title);
1361         }
1362
1363       if (remote_debug)
1364         fprintf_unfiltered (gdb_stdlog,
1365                             "Packet %s (%s) is NOT supported\n",
1366                             config->name, config->title);
1367       config->support = PACKET_DISABLE;
1368       break;
1369     }
1370
1371   return result;
1372 }
1373
1374 enum {
1375   PACKET_vCont = 0,
1376   PACKET_X,
1377   PACKET_qSymbol,
1378   PACKET_P,
1379   PACKET_p,
1380   PACKET_Z0,
1381   PACKET_Z1,
1382   PACKET_Z2,
1383   PACKET_Z3,
1384   PACKET_Z4,
1385   PACKET_vFile_setfs,
1386   PACKET_vFile_open,
1387   PACKET_vFile_pread,
1388   PACKET_vFile_pwrite,
1389   PACKET_vFile_close,
1390   PACKET_vFile_unlink,
1391   PACKET_vFile_readlink,
1392   PACKET_vFile_fstat,
1393   PACKET_qXfer_auxv,
1394   PACKET_qXfer_features,
1395   PACKET_qXfer_exec_file,
1396   PACKET_qXfer_libraries,
1397   PACKET_qXfer_libraries_svr4,
1398   PACKET_qXfer_memory_map,
1399   PACKET_qXfer_spu_read,
1400   PACKET_qXfer_spu_write,
1401   PACKET_qXfer_osdata,
1402   PACKET_qXfer_threads,
1403   PACKET_qXfer_statictrace_read,
1404   PACKET_qXfer_traceframe_info,
1405   PACKET_qXfer_uib,
1406   PACKET_qGetTIBAddr,
1407   PACKET_qGetTLSAddr,
1408   PACKET_qSupported,
1409   PACKET_qTStatus,
1410   PACKET_QPassSignals,
1411   PACKET_QCatchSyscalls,
1412   PACKET_QProgramSignals,
1413   PACKET_QSetWorkingDir,
1414   PACKET_QStartupWithShell,
1415   PACKET_QEnvironmentHexEncoded,
1416   PACKET_QEnvironmentReset,
1417   PACKET_QEnvironmentUnset,
1418   PACKET_qCRC,
1419   PACKET_qSearch_memory,
1420   PACKET_vAttach,
1421   PACKET_vRun,
1422   PACKET_QStartNoAckMode,
1423   PACKET_vKill,
1424   PACKET_qXfer_siginfo_read,
1425   PACKET_qXfer_siginfo_write,
1426   PACKET_qAttached,
1427
1428   /* Support for conditional tracepoints.  */
1429   PACKET_ConditionalTracepoints,
1430
1431   /* Support for target-side breakpoint conditions.  */
1432   PACKET_ConditionalBreakpoints,
1433
1434   /* Support for target-side breakpoint commands.  */
1435   PACKET_BreakpointCommands,
1436
1437   /* Support for fast tracepoints.  */
1438   PACKET_FastTracepoints,
1439
1440   /* Support for static tracepoints.  */
1441   PACKET_StaticTracepoints,
1442
1443   /* Support for installing tracepoints while a trace experiment is
1444      running.  */
1445   PACKET_InstallInTrace,
1446
1447   PACKET_bc,
1448   PACKET_bs,
1449   PACKET_TracepointSource,
1450   PACKET_QAllow,
1451   PACKET_qXfer_fdpic,
1452   PACKET_QDisableRandomization,
1453   PACKET_QAgent,
1454   PACKET_QTBuffer_size,
1455   PACKET_Qbtrace_off,
1456   PACKET_Qbtrace_bts,
1457   PACKET_Qbtrace_pt,
1458   PACKET_qXfer_btrace,
1459
1460   /* Support for the QNonStop packet.  */
1461   PACKET_QNonStop,
1462
1463   /* Support for the QThreadEvents packet.  */
1464   PACKET_QThreadEvents,
1465
1466   /* Support for multi-process extensions.  */
1467   PACKET_multiprocess_feature,
1468
1469   /* Support for enabling and disabling tracepoints while a trace
1470      experiment is running.  */
1471   PACKET_EnableDisableTracepoints_feature,
1472
1473   /* Support for collecting strings using the tracenz bytecode.  */
1474   PACKET_tracenz_feature,
1475
1476   /* Support for continuing to run a trace experiment while GDB is
1477      disconnected.  */
1478   PACKET_DisconnectedTracing_feature,
1479
1480   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
1481   PACKET_augmented_libraries_svr4_read_feature,
1482
1483   /* Support for the qXfer:btrace-conf:read packet.  */
1484   PACKET_qXfer_btrace_conf,
1485
1486   /* Support for the Qbtrace-conf:bts:size packet.  */
1487   PACKET_Qbtrace_conf_bts_size,
1488
1489   /* Support for swbreak+ feature.  */
1490   PACKET_swbreak_feature,
1491
1492   /* Support for hwbreak+ feature.  */
1493   PACKET_hwbreak_feature,
1494
1495   /* Support for fork events.  */
1496   PACKET_fork_event_feature,
1497
1498   /* Support for vfork events.  */
1499   PACKET_vfork_event_feature,
1500
1501   /* Support for the Qbtrace-conf:pt:size packet.  */
1502   PACKET_Qbtrace_conf_pt_size,
1503
1504   /* Support for exec events.  */
1505   PACKET_exec_event_feature,
1506
1507   /* Support for query supported vCont actions.  */
1508   PACKET_vContSupported,
1509
1510   /* Support remote CTRL-C.  */
1511   PACKET_vCtrlC,
1512
1513   /* Support TARGET_WAITKIND_NO_RESUMED.  */
1514   PACKET_no_resumed,
1515
1516   PACKET_MAX
1517 };
1518
1519 static struct packet_config remote_protocol_packets[PACKET_MAX];
1520
1521 /* Returns the packet's corresponding "set remote foo-packet" command
1522    state.  See struct packet_config for more details.  */
1523
1524 static enum auto_boolean
1525 packet_set_cmd_state (int packet)
1526 {
1527   return remote_protocol_packets[packet].detect;
1528 }
1529
1530 /* Returns whether a given packet or feature is supported.  This takes
1531    into account the state of the corresponding "set remote foo-packet"
1532    command, which may be used to bypass auto-detection.  */
1533
1534 static enum packet_support
1535 packet_config_support (struct packet_config *config)
1536 {
1537   switch (config->detect)
1538     {
1539     case AUTO_BOOLEAN_TRUE:
1540       return PACKET_ENABLE;
1541     case AUTO_BOOLEAN_FALSE:
1542       return PACKET_DISABLE;
1543     case AUTO_BOOLEAN_AUTO:
1544       return config->support;
1545     default:
1546       gdb_assert_not_reached (_("bad switch"));
1547     }
1548 }
1549
1550 /* Same as packet_config_support, but takes the packet's enum value as
1551    argument.  */
1552
1553 static enum packet_support
1554 packet_support (int packet)
1555 {
1556   struct packet_config *config = &remote_protocol_packets[packet];
1557
1558   return packet_config_support (config);
1559 }
1560
1561 static void
1562 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
1563                                  struct cmd_list_element *c,
1564                                  const char *value)
1565 {
1566   struct packet_config *packet;
1567
1568   for (packet = remote_protocol_packets;
1569        packet < &remote_protocol_packets[PACKET_MAX];
1570        packet++)
1571     {
1572       if (&packet->detect == c->var)
1573         {
1574           show_packet_config_cmd (packet);
1575           return;
1576         }
1577     }
1578   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
1579                   c->name);
1580 }
1581
1582 /* Should we try one of the 'Z' requests?  */
1583
1584 enum Z_packet_type
1585 {
1586   Z_PACKET_SOFTWARE_BP,
1587   Z_PACKET_HARDWARE_BP,
1588   Z_PACKET_WRITE_WP,
1589   Z_PACKET_READ_WP,
1590   Z_PACKET_ACCESS_WP,
1591   NR_Z_PACKET_TYPES
1592 };
1593
1594 /* For compatibility with older distributions.  Provide a ``set remote
1595    Z-packet ...'' command that updates all the Z packet types.  */
1596
1597 static enum auto_boolean remote_Z_packet_detect;
1598
1599 static void
1600 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
1601                                   struct cmd_list_element *c)
1602 {
1603   int i;
1604
1605   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1606     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
1607 }
1608
1609 static void
1610 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
1611                                    struct cmd_list_element *c,
1612                                    const char *value)
1613 {
1614   int i;
1615
1616   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
1617     {
1618       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
1619     }
1620 }
1621
1622 /* Returns true if the multi-process extensions are in effect.  */
1623
1624 static int
1625 remote_multi_process_p (struct remote_state *rs)
1626 {
1627   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
1628 }
1629
1630 /* Returns true if fork events are supported.  */
1631
1632 static int
1633 remote_fork_event_p (struct remote_state *rs)
1634 {
1635   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
1636 }
1637
1638 /* Returns true if vfork events are supported.  */
1639
1640 static int
1641 remote_vfork_event_p (struct remote_state *rs)
1642 {
1643   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
1644 }
1645
1646 /* Returns true if exec events are supported.  */
1647
1648 static int
1649 remote_exec_event_p (struct remote_state *rs)
1650 {
1651   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
1652 }
1653
1654 /* Insert fork catchpoint target routine.  If fork events are enabled
1655    then return success, nothing more to do.  */
1656
1657 static int
1658 remote_insert_fork_catchpoint (struct target_ops *ops, int pid)
1659 {
1660   struct remote_state *rs = get_remote_state ();
1661
1662   return !remote_fork_event_p (rs);
1663 }
1664
1665 /* Remove fork catchpoint target routine.  Nothing to do, just
1666    return success.  */
1667
1668 static int
1669 remote_remove_fork_catchpoint (struct target_ops *ops, int pid)
1670 {
1671   return 0;
1672 }
1673
1674 /* Insert vfork catchpoint target routine.  If vfork events are enabled
1675    then return success, nothing more to do.  */
1676
1677 static int
1678 remote_insert_vfork_catchpoint (struct target_ops *ops, int pid)
1679 {
1680   struct remote_state *rs = get_remote_state ();
1681
1682   return !remote_vfork_event_p (rs);
1683 }
1684
1685 /* Remove vfork catchpoint target routine.  Nothing to do, just
1686    return success.  */
1687
1688 static int
1689 remote_remove_vfork_catchpoint (struct target_ops *ops, int pid)
1690 {
1691   return 0;
1692 }
1693
1694 /* Insert exec catchpoint target routine.  If exec events are
1695    enabled, just return success.  */
1696
1697 static int
1698 remote_insert_exec_catchpoint (struct target_ops *ops, int pid)
1699 {
1700   struct remote_state *rs = get_remote_state ();
1701
1702   return !remote_exec_event_p (rs);
1703 }
1704
1705 /* Remove exec catchpoint target routine.  Nothing to do, just
1706    return success.  */
1707
1708 static int
1709 remote_remove_exec_catchpoint (struct target_ops *ops, int pid)
1710 {
1711   return 0;
1712 }
1713
1714 \f
1715 /* Asynchronous signal handle registered as event loop source for
1716    when we have pending events ready to be passed to the core.  */
1717
1718 static struct async_event_handler *remote_async_inferior_event_token;
1719
1720 \f
1721
1722 static ptid_t magic_null_ptid;
1723 static ptid_t not_sent_ptid;
1724 static ptid_t any_thread_ptid;
1725
1726 /* Find out if the stub attached to PID (and hence GDB should offer to
1727    detach instead of killing it when bailing out).  */
1728
1729 static int
1730 remote_query_attached (int pid)
1731 {
1732   struct remote_state *rs = get_remote_state ();
1733   size_t size = get_remote_packet_size ();
1734
1735   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
1736     return 0;
1737
1738   if (remote_multi_process_p (rs))
1739     xsnprintf (rs->buf, size, "qAttached:%x", pid);
1740   else
1741     xsnprintf (rs->buf, size, "qAttached");
1742
1743   putpkt (rs->buf);
1744   getpkt (&rs->buf, &rs->buf_size, 0);
1745
1746   switch (packet_ok (rs->buf,
1747                      &remote_protocol_packets[PACKET_qAttached]))
1748     {
1749     case PACKET_OK:
1750       if (strcmp (rs->buf, "1") == 0)
1751         return 1;
1752       break;
1753     case PACKET_ERROR:
1754       warning (_("Remote failure reply: %s"), rs->buf);
1755       break;
1756     case PACKET_UNKNOWN:
1757       break;
1758     }
1759
1760   return 0;
1761 }
1762
1763 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
1764    has been invented by GDB, instead of reported by the target.  Since
1765    we can be connected to a remote system before before knowing about
1766    any inferior, mark the target with execution when we find the first
1767    inferior.  If ATTACHED is 1, then we had just attached to this
1768    inferior.  If it is 0, then we just created this inferior.  If it
1769    is -1, then try querying the remote stub to find out if it had
1770    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
1771    attempt to open this inferior's executable as the main executable
1772    if no main executable is open already.  */
1773
1774 static struct inferior *
1775 remote_add_inferior (int fake_pid_p, int pid, int attached,
1776                      int try_open_exec)
1777 {
1778   struct inferior *inf;
1779
1780   /* Check whether this process we're learning about is to be
1781      considered attached, or if is to be considered to have been
1782      spawned by the stub.  */
1783   if (attached == -1)
1784     attached = remote_query_attached (pid);
1785
1786   if (gdbarch_has_global_solist (target_gdbarch ()))
1787     {
1788       /* If the target shares code across all inferiors, then every
1789          attach adds a new inferior.  */
1790       inf = add_inferior (pid);
1791
1792       /* ... and every inferior is bound to the same program space.
1793          However, each inferior may still have its own address
1794          space.  */
1795       inf->aspace = maybe_new_address_space ();
1796       inf->pspace = current_program_space;
1797     }
1798   else
1799     {
1800       /* In the traditional debugging scenario, there's a 1-1 match
1801          between program/address spaces.  We simply bind the inferior
1802          to the program space's address space.  */
1803       inf = current_inferior ();
1804       inferior_appeared (inf, pid);
1805     }
1806
1807   inf->attach_flag = attached;
1808   inf->fake_pid_p = fake_pid_p;
1809
1810   /* If no main executable is currently open then attempt to
1811      open the file that was executed to create this inferior.  */
1812   if (try_open_exec && get_exec_file (0) == NULL)
1813     exec_file_locate_attach (pid, 0, 1);
1814
1815   return inf;
1816 }
1817
1818 static remote_thread_info *get_remote_thread_info (thread_info *thread);
1819
1820 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
1821    according to RUNNING.  */
1822
1823 static void
1824 remote_add_thread (ptid_t ptid, int running, int executing)
1825 {
1826   struct remote_state *rs = get_remote_state ();
1827   struct thread_info *thread;
1828
1829   /* GDB historically didn't pull threads in the initial connection
1830      setup.  If the remote target doesn't even have a concept of
1831      threads (e.g., a bare-metal target), even if internally we
1832      consider that a single-threaded target, mentioning a new thread
1833      might be confusing to the user.  Be silent then, preserving the
1834      age old behavior.  */
1835   if (rs->starting_up)
1836     thread = add_thread_silent (ptid);
1837   else
1838     thread = add_thread (ptid);
1839
1840   get_remote_thread_info (thread)->vcont_resumed = executing;
1841   set_executing (ptid, executing);
1842   set_running (ptid, running);
1843 }
1844
1845 /* Come here when we learn about a thread id from the remote target.
1846    It may be the first time we hear about such thread, so take the
1847    opportunity to add it to GDB's thread list.  In case this is the
1848    first time we're noticing its corresponding inferior, add it to
1849    GDB's inferior list as well.  EXECUTING indicates whether the
1850    thread is (internally) executing or stopped.  */
1851
1852 static void
1853 remote_notice_new_inferior (ptid_t currthread, int executing)
1854 {
1855   /* In non-stop mode, we assume new found threads are (externally)
1856      running until proven otherwise with a stop reply.  In all-stop,
1857      we can only get here if all threads are stopped.  */
1858   int running = target_is_non_stop_p () ? 1 : 0;
1859
1860   /* If this is a new thread, add it to GDB's thread list.
1861      If we leave it up to WFI to do this, bad things will happen.  */
1862
1863   if (in_thread_list (currthread) && is_exited (currthread))
1864     {
1865       /* We're seeing an event on a thread id we knew had exited.
1866          This has to be a new thread reusing the old id.  Add it.  */
1867       remote_add_thread (currthread, running, executing);
1868       return;
1869     }
1870
1871   if (!in_thread_list (currthread))
1872     {
1873       struct inferior *inf = NULL;
1874       int pid = ptid_get_pid (currthread);
1875
1876       if (ptid_is_pid (inferior_ptid)
1877           && pid == ptid_get_pid (inferior_ptid))
1878         {
1879           /* inferior_ptid has no thread member yet.  This can happen
1880              with the vAttach -> remote_wait,"TAAthread:" path if the
1881              stub doesn't support qC.  This is the first stop reported
1882              after an attach, so this is the main thread.  Update the
1883              ptid in the thread list.  */
1884           if (in_thread_list (pid_to_ptid (pid)))
1885             thread_change_ptid (inferior_ptid, currthread);
1886           else
1887             {
1888               remote_add_thread (currthread, running, executing);
1889               inferior_ptid = currthread;
1890             }
1891           return;
1892         }
1893
1894       if (ptid_equal (magic_null_ptid, inferior_ptid))
1895         {
1896           /* inferior_ptid is not set yet.  This can happen with the
1897              vRun -> remote_wait,"TAAthread:" path if the stub
1898              doesn't support qC.  This is the first stop reported
1899              after an attach, so this is the main thread.  Update the
1900              ptid in the thread list.  */
1901           thread_change_ptid (inferior_ptid, currthread);
1902           return;
1903         }
1904
1905       /* When connecting to a target remote, or to a target
1906          extended-remote which already was debugging an inferior, we
1907          may not know about it yet.  Add it before adding its child
1908          thread, so notifications are emitted in a sensible order.  */
1909       if (!in_inferior_list (ptid_get_pid (currthread)))
1910         {
1911           struct remote_state *rs = get_remote_state ();
1912           int fake_pid_p = !remote_multi_process_p (rs);
1913
1914           inf = remote_add_inferior (fake_pid_p,
1915                                      ptid_get_pid (currthread), -1, 1);
1916         }
1917
1918       /* This is really a new thread.  Add it.  */
1919       remote_add_thread (currthread, running, executing);
1920
1921       /* If we found a new inferior, let the common code do whatever
1922          it needs to with it (e.g., read shared libraries, insert
1923          breakpoints), unless we're just setting up an all-stop
1924          connection.  */
1925       if (inf != NULL)
1926         {
1927           struct remote_state *rs = get_remote_state ();
1928
1929           if (!rs->starting_up)
1930             notice_new_inferior (currthread, executing, 0);
1931         }
1932     }
1933 }
1934
1935 /* Return THREAD's private thread data, creating it if necessary.  */
1936
1937 static remote_thread_info *
1938 get_remote_thread_info (thread_info *thread)
1939 {
1940   gdb_assert (thread != NULL);
1941
1942   if (thread->priv == NULL)
1943     thread->priv.reset (new remote_thread_info);
1944
1945   return static_cast<remote_thread_info *> (thread->priv.get ());
1946 }
1947
1948 /* Return PTID's private thread data, creating it if necessary.  */
1949
1950 static remote_thread_info *
1951 get_remote_thread_info (ptid_t ptid)
1952 {
1953   struct thread_info *info = find_thread_ptid (ptid);
1954
1955   return get_remote_thread_info (info);
1956 }
1957
1958 /* Call this function as a result of
1959    1) A halt indication (T packet) containing a thread id
1960    2) A direct query of currthread
1961    3) Successful execution of set thread */
1962
1963 static void
1964 record_currthread (struct remote_state *rs, ptid_t currthread)
1965 {
1966   rs->general_thread = currthread;
1967 }
1968
1969 /* If 'QPassSignals' is supported, tell the remote stub what signals
1970    it can simply pass through to the inferior without reporting.  */
1971
1972 static void
1973 remote_pass_signals (struct target_ops *self,
1974                      int numsigs, unsigned char *pass_signals)
1975 {
1976   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
1977     {
1978       char *pass_packet, *p;
1979       int count = 0, i;
1980       struct remote_state *rs = get_remote_state ();
1981
1982       gdb_assert (numsigs < 256);
1983       for (i = 0; i < numsigs; i++)
1984         {
1985           if (pass_signals[i])
1986             count++;
1987         }
1988       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
1989       strcpy (pass_packet, "QPassSignals:");
1990       p = pass_packet + strlen (pass_packet);
1991       for (i = 0; i < numsigs; i++)
1992         {
1993           if (pass_signals[i])
1994             {
1995               if (i >= 16)
1996                 *p++ = tohex (i >> 4);
1997               *p++ = tohex (i & 15);
1998               if (count)
1999                 *p++ = ';';
2000               else
2001                 break;
2002               count--;
2003             }
2004         }
2005       *p = 0;
2006       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2007         {
2008           putpkt (pass_packet);
2009           getpkt (&rs->buf, &rs->buf_size, 0);
2010           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2011           if (rs->last_pass_packet)
2012             xfree (rs->last_pass_packet);
2013           rs->last_pass_packet = pass_packet;
2014         }
2015       else
2016         xfree (pass_packet);
2017     }
2018 }
2019
2020 /* If 'QCatchSyscalls' is supported, tell the remote stub
2021    to report syscalls to GDB.  */
2022
2023 static int
2024 remote_set_syscall_catchpoint (struct target_ops *self,
2025                                int pid, bool needed, int any_count,
2026                                gdb::array_view<const int> syscall_counts)
2027 {
2028   const char *catch_packet;
2029   enum packet_result result;
2030   int n_sysno = 0;
2031
2032   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2033     {
2034       /* Not supported.  */
2035       return 1;
2036     }
2037
2038   if (needed && any_count == 0)
2039     {
2040       /* Count how many syscalls are to be caught.  */
2041       for (size_t i = 0; i < syscall_counts.size (); i++)
2042         {
2043           if (syscall_counts[i] != 0)
2044             n_sysno++;
2045         }
2046     }
2047
2048   if (remote_debug)
2049     {
2050       fprintf_unfiltered (gdb_stdlog,
2051                           "remote_set_syscall_catchpoint "
2052                           "pid %d needed %d any_count %d n_sysno %d\n",
2053                           pid, needed, any_count, n_sysno);
2054     }
2055
2056   std::string built_packet;
2057   if (needed)
2058     {
2059       /* Prepare a packet with the sysno list, assuming max 8+1
2060          characters for a sysno.  If the resulting packet size is too
2061          big, fallback on the non-selective packet.  */
2062       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2063       built_packet.reserve (maxpktsz);
2064       built_packet = "QCatchSyscalls:1";
2065       if (any_count == 0)
2066         {
2067           /* Add in each syscall to be caught.  */
2068           for (size_t i = 0; i < syscall_counts.size (); i++)
2069             {
2070               if (syscall_counts[i] != 0)
2071                 string_appendf (built_packet, ";%zx", i);
2072             }
2073         }
2074       if (built_packet.size () > get_remote_packet_size ())
2075         {
2076           /* catch_packet too big.  Fallback to less efficient
2077              non selective mode, with GDB doing the filtering.  */
2078           catch_packet = "QCatchSyscalls:1";
2079         }
2080       else
2081         catch_packet = built_packet.c_str ();
2082     }
2083   else
2084     catch_packet = "QCatchSyscalls:0";
2085
2086   struct remote_state *rs = get_remote_state ();
2087
2088   putpkt (catch_packet);
2089   getpkt (&rs->buf, &rs->buf_size, 0);
2090   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2091   if (result == PACKET_OK)
2092     return 0;
2093   else
2094     return -1;
2095 }
2096
2097 /* If 'QProgramSignals' is supported, tell the remote stub what
2098    signals it should pass through to the inferior when detaching.  */
2099
2100 static void
2101 remote_program_signals (struct target_ops *self,
2102                         int numsigs, unsigned char *signals)
2103 {
2104   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2105     {
2106       char *packet, *p;
2107       int count = 0, i;
2108       struct remote_state *rs = get_remote_state ();
2109
2110       gdb_assert (numsigs < 256);
2111       for (i = 0; i < numsigs; i++)
2112         {
2113           if (signals[i])
2114             count++;
2115         }
2116       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2117       strcpy (packet, "QProgramSignals:");
2118       p = packet + strlen (packet);
2119       for (i = 0; i < numsigs; i++)
2120         {
2121           if (signal_pass_state (i))
2122             {
2123               if (i >= 16)
2124                 *p++ = tohex (i >> 4);
2125               *p++ = tohex (i & 15);
2126               if (count)
2127                 *p++ = ';';
2128               else
2129                 break;
2130               count--;
2131             }
2132         }
2133       *p = 0;
2134       if (!rs->last_program_signals_packet
2135           || strcmp (rs->last_program_signals_packet, packet) != 0)
2136         {
2137           putpkt (packet);
2138           getpkt (&rs->buf, &rs->buf_size, 0);
2139           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2140           xfree (rs->last_program_signals_packet);
2141           rs->last_program_signals_packet = packet;
2142         }
2143       else
2144         xfree (packet);
2145     }
2146 }
2147
2148 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2149    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2150    thread.  If GEN is set, set the general thread, if not, then set
2151    the step/continue thread.  */
2152 static void
2153 set_thread (ptid_t ptid, int gen)
2154 {
2155   struct remote_state *rs = get_remote_state ();
2156   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2157   char *buf = rs->buf;
2158   char *endbuf = rs->buf + get_remote_packet_size ();
2159
2160   if (ptid_equal (state, ptid))
2161     return;
2162
2163   *buf++ = 'H';
2164   *buf++ = gen ? 'g' : 'c';
2165   if (ptid_equal (ptid, magic_null_ptid))
2166     xsnprintf (buf, endbuf - buf, "0");
2167   else if (ptid_equal (ptid, any_thread_ptid))
2168     xsnprintf (buf, endbuf - buf, "0");
2169   else if (ptid_equal (ptid, minus_one_ptid))
2170     xsnprintf (buf, endbuf - buf, "-1");
2171   else
2172     write_ptid (buf, endbuf, ptid);
2173   putpkt (rs->buf);
2174   getpkt (&rs->buf, &rs->buf_size, 0);
2175   if (gen)
2176     rs->general_thread = ptid;
2177   else
2178     rs->continue_thread = ptid;
2179 }
2180
2181 static void
2182 set_general_thread (ptid_t ptid)
2183 {
2184   set_thread (ptid, 1);
2185 }
2186
2187 static void
2188 set_continue_thread (ptid_t ptid)
2189 {
2190   set_thread (ptid, 0);
2191 }
2192
2193 /* Change the remote current process.  Which thread within the process
2194    ends up selected isn't important, as long as it is the same process
2195    as what INFERIOR_PTID points to.
2196
2197    This comes from that fact that there is no explicit notion of
2198    "selected process" in the protocol.  The selected process for
2199    general operations is the process the selected general thread
2200    belongs to.  */
2201
2202 static void
2203 set_general_process (void)
2204 {
2205   struct remote_state *rs = get_remote_state ();
2206
2207   /* If the remote can't handle multiple processes, don't bother.  */
2208   if (!remote_multi_process_p (rs))
2209     return;
2210
2211   /* We only need to change the remote current thread if it's pointing
2212      at some other process.  */
2213   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2214     set_general_thread (inferior_ptid);
2215 }
2216
2217 \f
2218 /* Return nonzero if this is the main thread that we made up ourselves
2219    to model non-threaded targets as single-threaded.  */
2220
2221 static int
2222 remote_thread_always_alive (struct target_ops *ops, ptid_t ptid)
2223 {
2224   if (ptid_equal (ptid, magic_null_ptid))
2225     /* The main thread is always alive.  */
2226     return 1;
2227
2228   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2229     /* The main thread is always alive.  This can happen after a
2230        vAttach, if the remote side doesn't support
2231        multi-threading.  */
2232     return 1;
2233
2234   return 0;
2235 }
2236
2237 /* Return nonzero if the thread PTID is still alive on the remote
2238    system.  */
2239
2240 static int
2241 remote_thread_alive (struct target_ops *ops, ptid_t ptid)
2242 {
2243   struct remote_state *rs = get_remote_state ();
2244   char *p, *endp;
2245
2246   /* Check if this is a thread that we made up ourselves to model
2247      non-threaded targets as single-threaded.  */
2248   if (remote_thread_always_alive (ops, ptid))
2249     return 1;
2250
2251   p = rs->buf;
2252   endp = rs->buf + get_remote_packet_size ();
2253
2254   *p++ = 'T';
2255   write_ptid (p, endp, ptid);
2256
2257   putpkt (rs->buf);
2258   getpkt (&rs->buf, &rs->buf_size, 0);
2259   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2260 }
2261
2262 /* Return a pointer to a thread name if we know it and NULL otherwise.
2263    The thread_info object owns the memory for the name.  */
2264
2265 static const char *
2266 remote_thread_name (struct target_ops *ops, struct thread_info *info)
2267 {
2268   if (info->priv != NULL)
2269     {
2270       const std::string &name = get_remote_thread_info (info)->name;
2271       return !name.empty () ? name.c_str () : NULL;
2272     }
2273
2274   return NULL;
2275 }
2276
2277 /* About these extended threadlist and threadinfo packets.  They are
2278    variable length packets but, the fields within them are often fixed
2279    length.  They are redundent enough to send over UDP as is the
2280    remote protocol in general.  There is a matching unit test module
2281    in libstub.  */
2282
2283 /* WARNING: This threadref data structure comes from the remote O.S.,
2284    libstub protocol encoding, and remote.c.  It is not particularly
2285    changable.  */
2286
2287 /* Right now, the internal structure is int. We want it to be bigger.
2288    Plan to fix this.  */
2289
2290 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2291
2292 /* gdb_ext_thread_info is an internal GDB data structure which is
2293    equivalent to the reply of the remote threadinfo packet.  */
2294
2295 struct gdb_ext_thread_info
2296   {
2297     threadref threadid;         /* External form of thread reference.  */
2298     int active;                 /* Has state interesting to GDB?
2299                                    regs, stack.  */
2300     char display[256];          /* Brief state display, name,
2301                                    blocked/suspended.  */
2302     char shortname[32];         /* To be used to name threads.  */
2303     char more_display[256];     /* Long info, statistics, queue depth,
2304                                    whatever.  */
2305   };
2306
2307 /* The volume of remote transfers can be limited by submitting
2308    a mask containing bits specifying the desired information.
2309    Use a union of these values as the 'selection' parameter to
2310    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2311
2312 #define TAG_THREADID 1
2313 #define TAG_EXISTS 2
2314 #define TAG_DISPLAY 4
2315 #define TAG_THREADNAME 8
2316 #define TAG_MOREDISPLAY 16
2317
2318 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2319
2320 static char *unpack_nibble (char *buf, int *val);
2321
2322 static char *unpack_byte (char *buf, int *value);
2323
2324 static char *pack_int (char *buf, int value);
2325
2326 static char *unpack_int (char *buf, int *value);
2327
2328 static char *unpack_string (char *src, char *dest, int length);
2329
2330 static char *pack_threadid (char *pkt, threadref *id);
2331
2332 static char *unpack_threadid (char *inbuf, threadref *id);
2333
2334 void int_to_threadref (threadref *id, int value);
2335
2336 static int threadref_to_int (threadref *ref);
2337
2338 static void copy_threadref (threadref *dest, threadref *src);
2339
2340 static int threadmatch (threadref *dest, threadref *src);
2341
2342 static char *pack_threadinfo_request (char *pkt, int mode,
2343                                       threadref *id);
2344
2345 static int remote_unpack_thread_info_response (char *pkt,
2346                                                threadref *expectedref,
2347                                                struct gdb_ext_thread_info
2348                                                *info);
2349
2350
2351 static int remote_get_threadinfo (threadref *threadid,
2352                                   int fieldset, /*TAG mask */
2353                                   struct gdb_ext_thread_info *info);
2354
2355 static char *pack_threadlist_request (char *pkt, int startflag,
2356                                       int threadcount,
2357                                       threadref *nextthread);
2358
2359 static int parse_threadlist_response (char *pkt,
2360                                       int result_limit,
2361                                       threadref *original_echo,
2362                                       threadref *resultlist,
2363                                       int *doneflag);
2364
2365 static int remote_get_threadlist (int startflag,
2366                                   threadref *nextthread,
2367                                   int result_limit,
2368                                   int *done,
2369                                   int *result_count,
2370                                   threadref *threadlist);
2371
2372 typedef int (*rmt_thread_action) (threadref *ref, void *context);
2373
2374 static int remote_threadlist_iterator (rmt_thread_action stepfunction,
2375                                        void *context, int looplimit);
2376
2377 static int remote_newthread_step (threadref *ref, void *context);
2378
2379
2380 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2381    buffer we're allowed to write to.  Returns
2382    BUF+CHARACTERS_WRITTEN.  */
2383
2384 static char *
2385 write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2386 {
2387   int pid, tid;
2388   struct remote_state *rs = get_remote_state ();
2389
2390   if (remote_multi_process_p (rs))
2391     {
2392       pid = ptid_get_pid (ptid);
2393       if (pid < 0)
2394         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2395       else
2396         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2397     }
2398   tid = ptid_get_lwp (ptid);
2399   if (tid < 0)
2400     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2401   else
2402     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2403
2404   return buf;
2405 }
2406
2407 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2408    last parsed char.  Returns null_ptid if no thread id is found, and
2409    throws an error if the thread id has an invalid format.  */
2410
2411 static ptid_t
2412 read_ptid (const char *buf, const char **obuf)
2413 {
2414   const char *p = buf;
2415   const char *pp;
2416   ULONGEST pid = 0, tid = 0;
2417
2418   if (*p == 'p')
2419     {
2420       /* Multi-process ptid.  */
2421       pp = unpack_varlen_hex (p + 1, &pid);
2422       if (*pp != '.')
2423         error (_("invalid remote ptid: %s"), p);
2424
2425       p = pp;
2426       pp = unpack_varlen_hex (p + 1, &tid);
2427       if (obuf)
2428         *obuf = pp;
2429       return ptid_build (pid, tid, 0);
2430     }
2431
2432   /* No multi-process.  Just a tid.  */
2433   pp = unpack_varlen_hex (p, &tid);
2434
2435   /* Return null_ptid when no thread id is found.  */
2436   if (p == pp)
2437     {
2438       if (obuf)
2439         *obuf = pp;
2440       return null_ptid;
2441     }
2442
2443   /* Since the stub is not sending a process id, then default to
2444      what's in inferior_ptid, unless it's null at this point.  If so,
2445      then since there's no way to know the pid of the reported
2446      threads, use the magic number.  */
2447   if (ptid_equal (inferior_ptid, null_ptid))
2448     pid = ptid_get_pid (magic_null_ptid);
2449   else
2450     pid = ptid_get_pid (inferior_ptid);
2451
2452   if (obuf)
2453     *obuf = pp;
2454   return ptid_build (pid, tid, 0);
2455 }
2456
2457 static int
2458 stubhex (int ch)
2459 {
2460   if (ch >= 'a' && ch <= 'f')
2461     return ch - 'a' + 10;
2462   if (ch >= '0' && ch <= '9')
2463     return ch - '0';
2464   if (ch >= 'A' && ch <= 'F')
2465     return ch - 'A' + 10;
2466   return -1;
2467 }
2468
2469 static int
2470 stub_unpack_int (char *buff, int fieldlength)
2471 {
2472   int nibble;
2473   int retval = 0;
2474
2475   while (fieldlength)
2476     {
2477       nibble = stubhex (*buff++);
2478       retval |= nibble;
2479       fieldlength--;
2480       if (fieldlength)
2481         retval = retval << 4;
2482     }
2483   return retval;
2484 }
2485
2486 static char *
2487 unpack_nibble (char *buf, int *val)
2488 {
2489   *val = fromhex (*buf++);
2490   return buf;
2491 }
2492
2493 static char *
2494 unpack_byte (char *buf, int *value)
2495 {
2496   *value = stub_unpack_int (buf, 2);
2497   return buf + 2;
2498 }
2499
2500 static char *
2501 pack_int (char *buf, int value)
2502 {
2503   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
2504   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
2505   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
2506   buf = pack_hex_byte (buf, (value & 0xff));
2507   return buf;
2508 }
2509
2510 static char *
2511 unpack_int (char *buf, int *value)
2512 {
2513   *value = stub_unpack_int (buf, 8);
2514   return buf + 8;
2515 }
2516
2517 #if 0                   /* Currently unused, uncomment when needed.  */
2518 static char *pack_string (char *pkt, char *string);
2519
2520 static char *
2521 pack_string (char *pkt, char *string)
2522 {
2523   char ch;
2524   int len;
2525
2526   len = strlen (string);
2527   if (len > 200)
2528     len = 200;          /* Bigger than most GDB packets, junk???  */
2529   pkt = pack_hex_byte (pkt, len);
2530   while (len-- > 0)
2531     {
2532       ch = *string++;
2533       if ((ch == '\0') || (ch == '#'))
2534         ch = '*';               /* Protect encapsulation.  */
2535       *pkt++ = ch;
2536     }
2537   return pkt;
2538 }
2539 #endif /* 0 (unused) */
2540
2541 static char *
2542 unpack_string (char *src, char *dest, int length)
2543 {
2544   while (length--)
2545     *dest++ = *src++;
2546   *dest = '\0';
2547   return src;
2548 }
2549
2550 static char *
2551 pack_threadid (char *pkt, threadref *id)
2552 {
2553   char *limit;
2554   unsigned char *altid;
2555
2556   altid = (unsigned char *) id;
2557   limit = pkt + BUF_THREAD_ID_SIZE;
2558   while (pkt < limit)
2559     pkt = pack_hex_byte (pkt, *altid++);
2560   return pkt;
2561 }
2562
2563
2564 static char *
2565 unpack_threadid (char *inbuf, threadref *id)
2566 {
2567   char *altref;
2568   char *limit = inbuf + BUF_THREAD_ID_SIZE;
2569   int x, y;
2570
2571   altref = (char *) id;
2572
2573   while (inbuf < limit)
2574     {
2575       x = stubhex (*inbuf++);
2576       y = stubhex (*inbuf++);
2577       *altref++ = (x << 4) | y;
2578     }
2579   return inbuf;
2580 }
2581
2582 /* Externally, threadrefs are 64 bits but internally, they are still
2583    ints.  This is due to a mismatch of specifications.  We would like
2584    to use 64bit thread references internally.  This is an adapter
2585    function.  */
2586
2587 void
2588 int_to_threadref (threadref *id, int value)
2589 {
2590   unsigned char *scan;
2591
2592   scan = (unsigned char *) id;
2593   {
2594     int i = 4;
2595     while (i--)
2596       *scan++ = 0;
2597   }
2598   *scan++ = (value >> 24) & 0xff;
2599   *scan++ = (value >> 16) & 0xff;
2600   *scan++ = (value >> 8) & 0xff;
2601   *scan++ = (value & 0xff);
2602 }
2603
2604 static int
2605 threadref_to_int (threadref *ref)
2606 {
2607   int i, value = 0;
2608   unsigned char *scan;
2609
2610   scan = *ref;
2611   scan += 4;
2612   i = 4;
2613   while (i-- > 0)
2614     value = (value << 8) | ((*scan++) & 0xff);
2615   return value;
2616 }
2617
2618 static void
2619 copy_threadref (threadref *dest, threadref *src)
2620 {
2621   int i;
2622   unsigned char *csrc, *cdest;
2623
2624   csrc = (unsigned char *) src;
2625   cdest = (unsigned char *) dest;
2626   i = 8;
2627   while (i--)
2628     *cdest++ = *csrc++;
2629 }
2630
2631 static int
2632 threadmatch (threadref *dest, threadref *src)
2633 {
2634   /* Things are broken right now, so just assume we got a match.  */
2635 #if 0
2636   unsigned char *srcp, *destp;
2637   int i, result;
2638   srcp = (char *) src;
2639   destp = (char *) dest;
2640
2641   result = 1;
2642   while (i-- > 0)
2643     result &= (*srcp++ == *destp++) ? 1 : 0;
2644   return result;
2645 #endif
2646   return 1;
2647 }
2648
2649 /*
2650    threadid:1,        # always request threadid
2651    context_exists:2,
2652    display:4,
2653    unique_name:8,
2654    more_display:16
2655  */
2656
2657 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
2658
2659 static char *
2660 pack_threadinfo_request (char *pkt, int mode, threadref *id)
2661 {
2662   *pkt++ = 'q';                         /* Info Query */
2663   *pkt++ = 'P';                         /* process or thread info */
2664   pkt = pack_int (pkt, mode);           /* mode */
2665   pkt = pack_threadid (pkt, id);        /* threadid */
2666   *pkt = '\0';                          /* terminate */
2667   return pkt;
2668 }
2669
2670 /* These values tag the fields in a thread info response packet.  */
2671 /* Tagging the fields allows us to request specific fields and to
2672    add more fields as time goes by.  */
2673
2674 #define TAG_THREADID 1          /* Echo the thread identifier.  */
2675 #define TAG_EXISTS 2            /* Is this process defined enough to
2676                                    fetch registers and its stack?  */
2677 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
2678 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
2679 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
2680                                    the process.  */
2681
2682 static int
2683 remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
2684                                     struct gdb_ext_thread_info *info)
2685 {
2686   struct remote_state *rs = get_remote_state ();
2687   int mask, length;
2688   int tag;
2689   threadref ref;
2690   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
2691   int retval = 1;
2692
2693   /* info->threadid = 0; FIXME: implement zero_threadref.  */
2694   info->active = 0;
2695   info->display[0] = '\0';
2696   info->shortname[0] = '\0';
2697   info->more_display[0] = '\0';
2698
2699   /* Assume the characters indicating the packet type have been
2700      stripped.  */
2701   pkt = unpack_int (pkt, &mask);        /* arg mask */
2702   pkt = unpack_threadid (pkt, &ref);
2703
2704   if (mask == 0)
2705     warning (_("Incomplete response to threadinfo request."));
2706   if (!threadmatch (&ref, expectedref))
2707     {                   /* This is an answer to a different request.  */
2708       warning (_("ERROR RMT Thread info mismatch."));
2709       return 0;
2710     }
2711   copy_threadref (&info->threadid, &ref);
2712
2713   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
2714
2715   /* Packets are terminated with nulls.  */
2716   while ((pkt < limit) && mask && *pkt)
2717     {
2718       pkt = unpack_int (pkt, &tag);     /* tag */
2719       pkt = unpack_byte (pkt, &length); /* length */
2720       if (!(tag & mask))                /* Tags out of synch with mask.  */
2721         {
2722           warning (_("ERROR RMT: threadinfo tag mismatch."));
2723           retval = 0;
2724           break;
2725         }
2726       if (tag == TAG_THREADID)
2727         {
2728           if (length != 16)
2729             {
2730               warning (_("ERROR RMT: length of threadid is not 16."));
2731               retval = 0;
2732               break;
2733             }
2734           pkt = unpack_threadid (pkt, &ref);
2735           mask = mask & ~TAG_THREADID;
2736           continue;
2737         }
2738       if (tag == TAG_EXISTS)
2739         {
2740           info->active = stub_unpack_int (pkt, length);
2741           pkt += length;
2742           mask = mask & ~(TAG_EXISTS);
2743           if (length > 8)
2744             {
2745               warning (_("ERROR RMT: 'exists' length too long."));
2746               retval = 0;
2747               break;
2748             }
2749           continue;
2750         }
2751       if (tag == TAG_THREADNAME)
2752         {
2753           pkt = unpack_string (pkt, &info->shortname[0], length);
2754           mask = mask & ~TAG_THREADNAME;
2755           continue;
2756         }
2757       if (tag == TAG_DISPLAY)
2758         {
2759           pkt = unpack_string (pkt, &info->display[0], length);
2760           mask = mask & ~TAG_DISPLAY;
2761           continue;
2762         }
2763       if (tag == TAG_MOREDISPLAY)
2764         {
2765           pkt = unpack_string (pkt, &info->more_display[0], length);
2766           mask = mask & ~TAG_MOREDISPLAY;
2767           continue;
2768         }
2769       warning (_("ERROR RMT: unknown thread info tag."));
2770       break;                    /* Not a tag we know about.  */
2771     }
2772   return retval;
2773 }
2774
2775 static int
2776 remote_get_threadinfo (threadref *threadid, int fieldset,       /* TAG mask */
2777                        struct gdb_ext_thread_info *info)
2778 {
2779   struct remote_state *rs = get_remote_state ();
2780   int result;
2781
2782   pack_threadinfo_request (rs->buf, fieldset, threadid);
2783   putpkt (rs->buf);
2784   getpkt (&rs->buf, &rs->buf_size, 0);
2785
2786   if (rs->buf[0] == '\0')
2787     return 0;
2788
2789   result = remote_unpack_thread_info_response (rs->buf + 2,
2790                                                threadid, info);
2791   return result;
2792 }
2793
2794 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
2795
2796 static char *
2797 pack_threadlist_request (char *pkt, int startflag, int threadcount,
2798                          threadref *nextthread)
2799 {
2800   *pkt++ = 'q';                 /* info query packet */
2801   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
2802   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
2803   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
2804   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
2805   *pkt = '\0';
2806   return pkt;
2807 }
2808
2809 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
2810
2811 static int
2812 parse_threadlist_response (char *pkt, int result_limit,
2813                            threadref *original_echo, threadref *resultlist,
2814                            int *doneflag)
2815 {
2816   struct remote_state *rs = get_remote_state ();
2817   char *limit;
2818   int count, resultcount, done;
2819
2820   resultcount = 0;
2821   /* Assume the 'q' and 'M chars have been stripped.  */
2822   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
2823   /* done parse past here */
2824   pkt = unpack_byte (pkt, &count);      /* count field */
2825   pkt = unpack_nibble (pkt, &done);
2826   /* The first threadid is the argument threadid.  */
2827   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
2828   while ((count-- > 0) && (pkt < limit))
2829     {
2830       pkt = unpack_threadid (pkt, resultlist++);
2831       if (resultcount++ >= result_limit)
2832         break;
2833     }
2834   if (doneflag)
2835     *doneflag = done;
2836   return resultcount;
2837 }
2838
2839 /* Fetch the next batch of threads from the remote.  Returns -1 if the
2840    qL packet is not supported, 0 on error and 1 on success.  */
2841
2842 static int
2843 remote_get_threadlist (int startflag, threadref *nextthread, int result_limit,
2844                        int *done, int *result_count, threadref *threadlist)
2845 {
2846   struct remote_state *rs = get_remote_state ();
2847   int result = 1;
2848
2849   /* Trancate result limit to be smaller than the packet size.  */
2850   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
2851       >= get_remote_packet_size ())
2852     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
2853
2854   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
2855   putpkt (rs->buf);
2856   getpkt (&rs->buf, &rs->buf_size, 0);
2857   if (*rs->buf == '\0')
2858     {
2859       /* Packet not supported.  */
2860       return -1;
2861     }
2862
2863   *result_count =
2864     parse_threadlist_response (rs->buf + 2, result_limit,
2865                                &rs->echo_nextthread, threadlist, done);
2866
2867   if (!threadmatch (&rs->echo_nextthread, nextthread))
2868     {
2869       /* FIXME: This is a good reason to drop the packet.  */
2870       /* Possably, there is a duplicate response.  */
2871       /* Possabilities :
2872          retransmit immediatly - race conditions
2873          retransmit after timeout - yes
2874          exit
2875          wait for packet, then exit
2876        */
2877       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
2878       return 0;                 /* I choose simply exiting.  */
2879     }
2880   if (*result_count <= 0)
2881     {
2882       if (*done != 1)
2883         {
2884           warning (_("RMT ERROR : failed to get remote thread list."));
2885           result = 0;
2886         }
2887       return result;            /* break; */
2888     }
2889   if (*result_count > result_limit)
2890     {
2891       *result_count = 0;
2892       warning (_("RMT ERROR: threadlist response longer than requested."));
2893       return 0;
2894     }
2895   return result;
2896 }
2897
2898 /* Fetch the list of remote threads, with the qL packet, and call
2899    STEPFUNCTION for each thread found.  Stops iterating and returns 1
2900    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
2901    STEPFUNCTION returns false.  If the packet is not supported,
2902    returns -1.  */
2903
2904 static int
2905 remote_threadlist_iterator (rmt_thread_action stepfunction, void *context,
2906                             int looplimit)
2907 {
2908   struct remote_state *rs = get_remote_state ();
2909   int done, i, result_count;
2910   int startflag = 1;
2911   int result = 1;
2912   int loopcount = 0;
2913
2914   done = 0;
2915   while (!done)
2916     {
2917       if (loopcount++ > looplimit)
2918         {
2919           result = 0;
2920           warning (_("Remote fetch threadlist -infinite loop-."));
2921           break;
2922         }
2923       result = remote_get_threadlist (startflag, &rs->nextthread,
2924                                       MAXTHREADLISTRESULTS,
2925                                       &done, &result_count,
2926                                       rs->resultthreadlist);
2927       if (result <= 0)
2928         break;
2929       /* Clear for later iterations.  */
2930       startflag = 0;
2931       /* Setup to resume next batch of thread references, set nextthread.  */
2932       if (result_count >= 1)
2933         copy_threadref (&rs->nextthread,
2934                         &rs->resultthreadlist[result_count - 1]);
2935       i = 0;
2936       while (result_count--)
2937         {
2938           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
2939             {
2940               result = 0;
2941               break;
2942             }
2943         }
2944     }
2945   return result;
2946 }
2947
2948 /* A thread found on the remote target.  */
2949
2950 struct thread_item
2951 {
2952   explicit thread_item (ptid_t ptid_)
2953   : ptid (ptid_)
2954   {}
2955
2956   thread_item (thread_item &&other) = default;
2957   thread_item &operator= (thread_item &&other) = default;
2958
2959   DISABLE_COPY_AND_ASSIGN (thread_item);
2960
2961   /* The thread's PTID.  */
2962   ptid_t ptid;
2963
2964   /* The thread's extra info.  */
2965   std::string extra;
2966
2967   /* The thread's name.  */
2968   std::string name;
2969
2970   /* The core the thread was running on.  -1 if not known.  */
2971   int core = -1;
2972
2973   /* The thread handle associated with the thread.  */
2974   gdb::byte_vector thread_handle;
2975 };
2976
2977 /* Context passed around to the various methods listing remote
2978    threads.  As new threads are found, they're added to the ITEMS
2979    vector.  */
2980
2981 struct threads_listing_context
2982 {
2983   /* Return true if this object contains an entry for a thread with ptid
2984      PTID.  */
2985
2986   bool contains_thread (ptid_t ptid) const
2987   {
2988     auto match_ptid = [&] (const thread_item &item)
2989       {
2990         return item.ptid == ptid;
2991       };
2992
2993     auto it = std::find_if (this->items.begin (),
2994                             this->items.end (),
2995                             match_ptid);
2996
2997     return it != this->items.end ();
2998   }
2999
3000   /* Remove the thread with ptid PTID.  */
3001
3002   void remove_thread (ptid_t ptid)
3003   {
3004     auto match_ptid = [&] (const thread_item &item)
3005       {
3006         return item.ptid == ptid;
3007       };
3008
3009     auto it = std::remove_if (this->items.begin (),
3010                               this->items.end (),
3011                               match_ptid);
3012
3013     if (it != this->items.end ())
3014       this->items.erase (it);
3015   }
3016
3017   /* The threads found on the remote target.  */
3018   std::vector<thread_item> items;
3019 };
3020
3021 static int
3022 remote_newthread_step (threadref *ref, void *data)
3023 {
3024   struct threads_listing_context *context
3025     = (struct threads_listing_context *) data;
3026   int pid = inferior_ptid.pid ();
3027   int lwp = threadref_to_int (ref);
3028   ptid_t ptid (pid, lwp);
3029
3030   context->items.emplace_back (ptid);
3031
3032   return 1;                     /* continue iterator */
3033 }
3034
3035 #define CRAZY_MAX_THREADS 1000
3036
3037 static ptid_t
3038 remote_current_thread (ptid_t oldpid)
3039 {
3040   struct remote_state *rs = get_remote_state ();
3041
3042   putpkt ("qC");
3043   getpkt (&rs->buf, &rs->buf_size, 0);
3044   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3045     {
3046       const char *obuf;
3047       ptid_t result;
3048
3049       result = read_ptid (&rs->buf[2], &obuf);
3050       if (*obuf != '\0' && remote_debug)
3051         fprintf_unfiltered (gdb_stdlog,
3052                             "warning: garbage in qC reply\n");
3053
3054       return result;
3055     }
3056   else
3057     return oldpid;
3058 }
3059
3060 /* List remote threads using the deprecated qL packet.  */
3061
3062 static int
3063 remote_get_threads_with_ql (struct target_ops *ops,
3064                             struct threads_listing_context *context)
3065 {
3066   if (remote_threadlist_iterator (remote_newthread_step, context,
3067                                   CRAZY_MAX_THREADS) >= 0)
3068     return 1;
3069
3070   return 0;
3071 }
3072
3073 #if defined(HAVE_LIBEXPAT)
3074
3075 static void
3076 start_thread (struct gdb_xml_parser *parser,
3077               const struct gdb_xml_element *element,
3078               void *user_data,
3079               std::vector<gdb_xml_value> &attributes)
3080 {
3081   struct threads_listing_context *data
3082     = (struct threads_listing_context *) user_data;
3083   struct gdb_xml_value *attr;
3084
3085   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3086   ptid_t ptid = read_ptid (id, NULL);
3087
3088   data->items.emplace_back (ptid);
3089   thread_item &item = data->items.back ();
3090
3091   attr = xml_find_attribute (attributes, "core");
3092   if (attr != NULL)
3093     item.core = *(ULONGEST *) attr->value.get ();
3094
3095   attr = xml_find_attribute (attributes, "name");
3096   if (attr != NULL)
3097     item.name = (const char *) attr->value.get ();
3098
3099   attr = xml_find_attribute (attributes, "handle");
3100   if (attr != NULL)
3101     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3102 }
3103
3104 static void
3105 end_thread (struct gdb_xml_parser *parser,
3106             const struct gdb_xml_element *element,
3107             void *user_data, const char *body_text)
3108 {
3109   struct threads_listing_context *data
3110     = (struct threads_listing_context *) user_data;
3111
3112   if (body_text != NULL && *body_text != '\0')
3113     data->items.back ().extra = body_text;
3114 }
3115
3116 const struct gdb_xml_attribute thread_attributes[] = {
3117   { "id", GDB_XML_AF_NONE, NULL, NULL },
3118   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3119   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3120   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3121   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3122 };
3123
3124 const struct gdb_xml_element thread_children[] = {
3125   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3126 };
3127
3128 const struct gdb_xml_element threads_children[] = {
3129   { "thread", thread_attributes, thread_children,
3130     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3131     start_thread, end_thread },
3132   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3133 };
3134
3135 const struct gdb_xml_element threads_elements[] = {
3136   { "threads", NULL, threads_children,
3137     GDB_XML_EF_NONE, NULL, NULL },
3138   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3139 };
3140
3141 #endif
3142
3143 /* List remote threads using qXfer:threads:read.  */
3144
3145 static int
3146 remote_get_threads_with_qxfer (struct target_ops *ops,
3147                                struct threads_listing_context *context)
3148 {
3149 #if defined(HAVE_LIBEXPAT)
3150   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3151     {
3152       gdb::optional<gdb::char_vector> xml
3153         = target_read_stralloc (ops, TARGET_OBJECT_THREADS, NULL);
3154
3155       if (xml && (*xml)[0] != '\0')
3156         {
3157           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3158                                threads_elements, xml->data (), context);
3159         }
3160
3161       return 1;
3162     }
3163 #endif
3164
3165   return 0;
3166 }
3167
3168 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3169
3170 static int
3171 remote_get_threads_with_qthreadinfo (struct target_ops *ops,
3172                                      struct threads_listing_context *context)
3173 {
3174   struct remote_state *rs = get_remote_state ();
3175
3176   if (rs->use_threadinfo_query)
3177     {
3178       const char *bufp;
3179
3180       putpkt ("qfThreadInfo");
3181       getpkt (&rs->buf, &rs->buf_size, 0);
3182       bufp = rs->buf;
3183       if (bufp[0] != '\0')              /* q packet recognized */
3184         {
3185           while (*bufp++ == 'm')        /* reply contains one or more TID */
3186             {
3187               do
3188                 {
3189                   ptid_t ptid = read_ptid (bufp, &bufp);
3190                   context->items.emplace_back (ptid);
3191                 }
3192               while (*bufp++ == ',');   /* comma-separated list */
3193               putpkt ("qsThreadInfo");
3194               getpkt (&rs->buf, &rs->buf_size, 0);
3195               bufp = rs->buf;
3196             }
3197           return 1;
3198         }
3199       else
3200         {
3201           /* Packet not recognized.  */
3202           rs->use_threadinfo_query = 0;
3203         }
3204     }
3205
3206   return 0;
3207 }
3208
3209 /* Implement the to_update_thread_list function for the remote
3210    targets.  */
3211
3212 static void
3213 remote_update_thread_list (struct target_ops *ops)
3214 {
3215   struct threads_listing_context context;
3216   int got_list = 0;
3217
3218   /* We have a few different mechanisms to fetch the thread list.  Try
3219      them all, starting with the most preferred one first, falling
3220      back to older methods.  */
3221   if (remote_get_threads_with_qxfer (ops, &context)
3222       || remote_get_threads_with_qthreadinfo (ops, &context)
3223       || remote_get_threads_with_ql (ops, &context))
3224     {
3225       struct thread_info *tp, *tmp;
3226
3227       got_list = 1;
3228
3229       if (context.items.empty ()
3230           && remote_thread_always_alive (ops, inferior_ptid))
3231         {
3232           /* Some targets don't really support threads, but still
3233              reply an (empty) thread list in response to the thread
3234              listing packets, instead of replying "packet not
3235              supported".  Exit early so we don't delete the main
3236              thread.  */
3237           return;
3238         }
3239
3240       /* CONTEXT now holds the current thread list on the remote
3241          target end.  Delete GDB-side threads no longer found on the
3242          target.  */
3243       ALL_THREADS_SAFE (tp, tmp)
3244         {
3245           if (!context.contains_thread (tp->ptid))
3246             {
3247               /* Not found.  */
3248               delete_thread (tp->ptid);
3249             }
3250         }
3251
3252       /* Remove any unreported fork child threads from CONTEXT so
3253          that we don't interfere with follow fork, which is where
3254          creation of such threads is handled.  */
3255       remove_new_fork_children (&context);
3256
3257       /* And now add threads we don't know about yet to our list.  */
3258       for (thread_item &item : context.items)
3259         {
3260           if (item.ptid != null_ptid)
3261             {
3262               /* In non-stop mode, we assume new found threads are
3263                  executing until proven otherwise with a stop reply.
3264                  In all-stop, we can only get here if all threads are
3265                  stopped.  */
3266               int executing = target_is_non_stop_p () ? 1 : 0;
3267
3268               remote_notice_new_inferior (item.ptid, executing);
3269
3270               remote_thread_info *info = get_remote_thread_info (item.ptid);
3271               info->core = item.core;
3272               info->extra = std::move (item.extra);
3273               info->name = std::move (item.name);
3274               info->thread_handle = std::move (item.thread_handle);
3275             }
3276         }
3277     }
3278
3279   if (!got_list)
3280     {
3281       /* If no thread listing method is supported, then query whether
3282          each known thread is alive, one by one, with the T packet.
3283          If the target doesn't support threads at all, then this is a
3284          no-op.  See remote_thread_alive.  */
3285       prune_threads ();
3286     }
3287 }
3288
3289 /*
3290  * Collect a descriptive string about the given thread.
3291  * The target may say anything it wants to about the thread
3292  * (typically info about its blocked / runnable state, name, etc.).
3293  * This string will appear in the info threads display.
3294  *
3295  * Optional: targets are not required to implement this function.
3296  */
3297
3298 static const char *
3299 remote_threads_extra_info (struct target_ops *self, struct thread_info *tp)
3300 {
3301   struct remote_state *rs = get_remote_state ();
3302   int result;
3303   int set;
3304   threadref id;
3305   struct gdb_ext_thread_info threadinfo;
3306   static char display_buf[100]; /* arbitrary...  */
3307   int n = 0;                    /* position in display_buf */
3308
3309   if (rs->remote_desc == 0)             /* paranoia */
3310     internal_error (__FILE__, __LINE__,
3311                     _("remote_threads_extra_info"));
3312
3313   if (ptid_equal (tp->ptid, magic_null_ptid)
3314       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3315     /* This is the main thread which was added by GDB.  The remote
3316        server doesn't know about it.  */
3317     return NULL;
3318
3319   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3320     {
3321       struct thread_info *info = find_thread_ptid (tp->ptid);
3322
3323       if (info != NULL && info->priv != NULL)
3324         {
3325           const std::string &extra = get_remote_thread_info (info)->extra;
3326           return !extra.empty () ? extra.c_str () : NULL;
3327         }
3328       else
3329         return NULL;
3330     }
3331
3332   if (rs->use_threadextra_query)
3333     {
3334       char *b = rs->buf;
3335       char *endb = rs->buf + get_remote_packet_size ();
3336
3337       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3338       b += strlen (b);
3339       write_ptid (b, endb, tp->ptid);
3340
3341       putpkt (rs->buf);
3342       getpkt (&rs->buf, &rs->buf_size, 0);
3343       if (rs->buf[0] != 0)
3344         {
3345           n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3346           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3347           display_buf [result] = '\0';
3348           return display_buf;
3349         }
3350     }
3351
3352   /* If the above query fails, fall back to the old method.  */
3353   rs->use_threadextra_query = 0;
3354   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3355     | TAG_MOREDISPLAY | TAG_DISPLAY;
3356   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3357   if (remote_get_threadinfo (&id, set, &threadinfo))
3358     if (threadinfo.active)
3359       {
3360         if (*threadinfo.shortname)
3361           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3362                           " Name: %s,", threadinfo.shortname);
3363         if (*threadinfo.display)
3364           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3365                           " State: %s,", threadinfo.display);
3366         if (*threadinfo.more_display)
3367           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3368                           " Priority: %s", threadinfo.more_display);
3369
3370         if (n > 0)
3371           {
3372             /* For purely cosmetic reasons, clear up trailing commas.  */
3373             if (',' == display_buf[n-1])
3374               display_buf[n-1] = ' ';
3375             return display_buf;
3376           }
3377       }
3378   return NULL;
3379 }
3380 \f
3381
3382 static bool
3383 remote_static_tracepoint_marker_at (struct target_ops *self, CORE_ADDR addr,
3384                                     struct static_tracepoint_marker *marker)
3385 {
3386   struct remote_state *rs = get_remote_state ();
3387   char *p = rs->buf;
3388
3389   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3390   p += strlen (p);
3391   p += hexnumstr (p, addr);
3392   putpkt (rs->buf);
3393   getpkt (&rs->buf, &rs->buf_size, 0);
3394   p = rs->buf;
3395
3396   if (*p == 'E')
3397     error (_("Remote failure reply: %s"), p);
3398
3399   if (*p++ == 'm')
3400     {
3401       parse_static_tracepoint_marker_definition (p, NULL, marker);
3402       return true;
3403     }
3404
3405   return false;
3406 }
3407
3408 static std::vector<static_tracepoint_marker>
3409 remote_static_tracepoint_markers_by_strid (struct target_ops *self,
3410                                            const char *strid)
3411 {
3412   struct remote_state *rs = get_remote_state ();
3413   std::vector<static_tracepoint_marker> markers;
3414   const char *p;
3415   static_tracepoint_marker marker;
3416
3417   /* Ask for a first packet of static tracepoint marker
3418      definition.  */
3419   putpkt ("qTfSTM");
3420   getpkt (&rs->buf, &rs->buf_size, 0);
3421   p = rs->buf;
3422   if (*p == 'E')
3423     error (_("Remote failure reply: %s"), p);
3424
3425   while (*p++ == 'm')
3426     {
3427       do
3428         {
3429           parse_static_tracepoint_marker_definition (p, &p, &marker);
3430
3431           if (strid == NULL || marker.str_id == strid)
3432             markers.push_back (std::move (marker));
3433         }
3434       while (*p++ == ',');      /* comma-separated list */
3435       /* Ask for another packet of static tracepoint definition.  */
3436       putpkt ("qTsSTM");
3437       getpkt (&rs->buf, &rs->buf_size, 0);
3438       p = rs->buf;
3439     }
3440
3441   return markers;
3442 }
3443
3444 \f
3445 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3446
3447 static ptid_t
3448 remote_get_ada_task_ptid (struct target_ops *self, long lwp, long thread)
3449 {
3450   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3451 }
3452 \f
3453
3454 /* Restart the remote side; this is an extended protocol operation.  */
3455
3456 static void
3457 extended_remote_restart (void)
3458 {
3459   struct remote_state *rs = get_remote_state ();
3460
3461   /* Send the restart command; for reasons I don't understand the
3462      remote side really expects a number after the "R".  */
3463   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3464   putpkt (rs->buf);
3465
3466   remote_fileio_reset ();
3467 }
3468 \f
3469 /* Clean up connection to a remote debugger.  */
3470
3471 static void
3472 remote_close (struct target_ops *self)
3473 {
3474   struct remote_state *rs = get_remote_state ();
3475
3476   if (rs->remote_desc == NULL)
3477     return; /* already closed */
3478
3479   /* Make sure we leave stdin registered in the event loop.  */
3480   remote_terminal_ours (self);
3481
3482   serial_close (rs->remote_desc);
3483   rs->remote_desc = NULL;
3484
3485   /* We don't have a connection to the remote stub anymore.  Get rid
3486      of all the inferiors and their threads we were controlling.
3487      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
3488      will be unable to find the thread corresponding to (pid, 0, 0).  */
3489   inferior_ptid = null_ptid;
3490   discard_all_inferiors ();
3491
3492   /* We are closing the remote target, so we should discard
3493      everything of this target.  */
3494   discard_pending_stop_replies_in_queue (rs);
3495
3496   if (remote_async_inferior_event_token)
3497     delete_async_event_handler (&remote_async_inferior_event_token);
3498
3499   remote_notif_state_xfree (rs->notif_state);
3500
3501   trace_reset_local_state ();
3502 }
3503
3504 /* Query the remote side for the text, data and bss offsets.  */
3505
3506 static void
3507 get_offsets (void)
3508 {
3509   struct remote_state *rs = get_remote_state ();
3510   char *buf;
3511   char *ptr;
3512   int lose, num_segments = 0, do_sections, do_segments;
3513   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
3514   struct section_offsets *offs;
3515   struct symfile_segment_data *data;
3516
3517   if (symfile_objfile == NULL)
3518     return;
3519
3520   putpkt ("qOffsets");
3521   getpkt (&rs->buf, &rs->buf_size, 0);
3522   buf = rs->buf;
3523
3524   if (buf[0] == '\000')
3525     return;                     /* Return silently.  Stub doesn't support
3526                                    this command.  */
3527   if (buf[0] == 'E')
3528     {
3529       warning (_("Remote failure reply: %s"), buf);
3530       return;
3531     }
3532
3533   /* Pick up each field in turn.  This used to be done with scanf, but
3534      scanf will make trouble if CORE_ADDR size doesn't match
3535      conversion directives correctly.  The following code will work
3536      with any size of CORE_ADDR.  */
3537   text_addr = data_addr = bss_addr = 0;
3538   ptr = buf;
3539   lose = 0;
3540
3541   if (startswith (ptr, "Text="))
3542     {
3543       ptr += 5;
3544       /* Don't use strtol, could lose on big values.  */
3545       while (*ptr && *ptr != ';')
3546         text_addr = (text_addr << 4) + fromhex (*ptr++);
3547
3548       if (startswith (ptr, ";Data="))
3549         {
3550           ptr += 6;
3551           while (*ptr && *ptr != ';')
3552             data_addr = (data_addr << 4) + fromhex (*ptr++);
3553         }
3554       else
3555         lose = 1;
3556
3557       if (!lose && startswith (ptr, ";Bss="))
3558         {
3559           ptr += 5;
3560           while (*ptr && *ptr != ';')
3561             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
3562
3563           if (bss_addr != data_addr)
3564             warning (_("Target reported unsupported offsets: %s"), buf);
3565         }
3566       else
3567         lose = 1;
3568     }
3569   else if (startswith (ptr, "TextSeg="))
3570     {
3571       ptr += 8;
3572       /* Don't use strtol, could lose on big values.  */
3573       while (*ptr && *ptr != ';')
3574         text_addr = (text_addr << 4) + fromhex (*ptr++);
3575       num_segments = 1;
3576
3577       if (startswith (ptr, ";DataSeg="))
3578         {
3579           ptr += 9;
3580           while (*ptr && *ptr != ';')
3581             data_addr = (data_addr << 4) + fromhex (*ptr++);
3582           num_segments++;
3583         }
3584     }
3585   else
3586     lose = 1;
3587
3588   if (lose)
3589     error (_("Malformed response to offset query, %s"), buf);
3590   else if (*ptr != '\0')
3591     warning (_("Target reported unsupported offsets: %s"), buf);
3592
3593   offs = ((struct section_offsets *)
3594           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
3595   memcpy (offs, symfile_objfile->section_offsets,
3596           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
3597
3598   data = get_symfile_segment_data (symfile_objfile->obfd);
3599   do_segments = (data != NULL);
3600   do_sections = num_segments == 0;
3601
3602   if (num_segments > 0)
3603     {
3604       segments[0] = text_addr;
3605       segments[1] = data_addr;
3606     }
3607   /* If we have two segments, we can still try to relocate everything
3608      by assuming that the .text and .data offsets apply to the whole
3609      text and data segments.  Convert the offsets given in the packet
3610      to base addresses for symfile_map_offsets_to_segments.  */
3611   else if (data && data->num_segments == 2)
3612     {
3613       segments[0] = data->segment_bases[0] + text_addr;
3614       segments[1] = data->segment_bases[1] + data_addr;
3615       num_segments = 2;
3616     }
3617   /* If the object file has only one segment, assume that it is text
3618      rather than data; main programs with no writable data are rare,
3619      but programs with no code are useless.  Of course the code might
3620      have ended up in the data segment... to detect that we would need
3621      the permissions here.  */
3622   else if (data && data->num_segments == 1)
3623     {
3624       segments[0] = data->segment_bases[0] + text_addr;
3625       num_segments = 1;
3626     }
3627   /* There's no way to relocate by segment.  */
3628   else
3629     do_segments = 0;
3630
3631   if (do_segments)
3632     {
3633       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
3634                                                  offs, num_segments, segments);
3635
3636       if (ret == 0 && !do_sections)
3637         error (_("Can not handle qOffsets TextSeg "
3638                  "response with this symbol file"));
3639
3640       if (ret > 0)
3641         do_sections = 0;
3642     }
3643
3644   if (data)
3645     free_symfile_segment_data (data);
3646
3647   if (do_sections)
3648     {
3649       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
3650
3651       /* This is a temporary kludge to force data and bss to use the
3652          same offsets because that's what nlmconv does now.  The real
3653          solution requires changes to the stub and remote.c that I
3654          don't have time to do right now.  */
3655
3656       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
3657       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
3658     }
3659
3660   objfile_relocate (symfile_objfile, offs);
3661 }
3662
3663 /* Send interrupt_sequence to remote target.  */
3664 static void
3665 send_interrupt_sequence (void)
3666 {
3667   struct remote_state *rs = get_remote_state ();
3668
3669   if (interrupt_sequence_mode == interrupt_sequence_control_c)
3670     remote_serial_write ("\x03", 1);
3671   else if (interrupt_sequence_mode == interrupt_sequence_break)
3672     serial_send_break (rs->remote_desc);
3673   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
3674     {
3675       serial_send_break (rs->remote_desc);
3676       remote_serial_write ("g", 1);
3677     }
3678   else
3679     internal_error (__FILE__, __LINE__,
3680                     _("Invalid value for interrupt_sequence_mode: %s."),
3681                     interrupt_sequence_mode);
3682 }
3683
3684
3685 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
3686    and extract the PTID.  Returns NULL_PTID if not found.  */
3687
3688 static ptid_t
3689 stop_reply_extract_thread (char *stop_reply)
3690 {
3691   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
3692     {
3693       const char *p;
3694
3695       /* Txx r:val ; r:val (...)  */
3696       p = &stop_reply[3];
3697
3698       /* Look for "register" named "thread".  */
3699       while (*p != '\0')
3700         {
3701           const char *p1;
3702
3703           p1 = strchr (p, ':');
3704           if (p1 == NULL)
3705             return null_ptid;
3706
3707           if (strncmp (p, "thread", p1 - p) == 0)
3708             return read_ptid (++p1, &p);
3709
3710           p1 = strchr (p, ';');
3711           if (p1 == NULL)
3712             return null_ptid;
3713           p1++;
3714
3715           p = p1;
3716         }
3717     }
3718
3719   return null_ptid;
3720 }
3721
3722 /* Determine the remote side's current thread.  If we have a stop
3723    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
3724    "thread" register we can extract the current thread from.  If not,
3725    ask the remote which is the current thread with qC.  The former
3726    method avoids a roundtrip.  */
3727
3728 static ptid_t
3729 get_current_thread (char *wait_status)
3730 {
3731   ptid_t ptid = null_ptid;
3732
3733   /* Note we don't use remote_parse_stop_reply as that makes use of
3734      the target architecture, which we haven't yet fully determined at
3735      this point.  */
3736   if (wait_status != NULL)
3737     ptid = stop_reply_extract_thread (wait_status);
3738   if (ptid_equal (ptid, null_ptid))
3739     ptid = remote_current_thread (inferior_ptid);
3740
3741   return ptid;
3742 }
3743
3744 /* Query the remote target for which is the current thread/process,
3745    add it to our tables, and update INFERIOR_PTID.  The caller is
3746    responsible for setting the state such that the remote end is ready
3747    to return the current thread.
3748
3749    This function is called after handling the '?' or 'vRun' packets,
3750    whose response is a stop reply from which we can also try
3751    extracting the thread.  If the target doesn't support the explicit
3752    qC query, we infer the current thread from that stop reply, passed
3753    in in WAIT_STATUS, which may be NULL.  */
3754
3755 static void
3756 add_current_inferior_and_thread (char *wait_status)
3757 {
3758   struct remote_state *rs = get_remote_state ();
3759   int fake_pid_p = 0;
3760
3761   inferior_ptid = null_ptid;
3762
3763   /* Now, if we have thread information, update inferior_ptid.  */
3764   ptid_t curr_ptid = get_current_thread (wait_status);
3765
3766   if (curr_ptid != null_ptid)
3767     {
3768       if (!remote_multi_process_p (rs))
3769         fake_pid_p = 1;
3770     }
3771   else
3772     {
3773       /* Without this, some commands which require an active target
3774          (such as kill) won't work.  This variable serves (at least)
3775          double duty as both the pid of the target process (if it has
3776          such), and as a flag indicating that a target is active.  */
3777       curr_ptid = magic_null_ptid;
3778       fake_pid_p = 1;
3779     }
3780
3781   remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
3782
3783   /* Add the main thread and switch to it.  Don't try reading
3784      registers yet, since we haven't fetched the target description
3785      yet.  */
3786   thread_info *tp = add_thread_silent (curr_ptid);
3787   switch_to_thread_no_regs (tp);
3788 }
3789
3790 /* Print info about a thread that was found already stopped on
3791    connection.  */
3792
3793 static void
3794 print_one_stopped_thread (struct thread_info *thread)
3795 {
3796   struct target_waitstatus *ws = &thread->suspend.waitstatus;
3797
3798   switch_to_thread (thread->ptid);
3799   stop_pc = get_frame_pc (get_current_frame ());
3800   set_current_sal_from_frame (get_current_frame ());
3801
3802   thread->suspend.waitstatus_pending_p = 0;
3803
3804   if (ws->kind == TARGET_WAITKIND_STOPPED)
3805     {
3806       enum gdb_signal sig = ws->value.sig;
3807
3808       if (signal_print_state (sig))
3809         gdb::observers::signal_received.notify (sig);
3810     }
3811   gdb::observers::normal_stop.notify (NULL, 1);
3812 }
3813
3814 /* Process all initial stop replies the remote side sent in response
3815    to the ? packet.  These indicate threads that were already stopped
3816    on initial connection.  We mark these threads as stopped and print
3817    their current frame before giving the user the prompt.  */
3818
3819 static void
3820 process_initial_stop_replies (int from_tty)
3821 {
3822   int pending_stop_replies = stop_reply_queue_length ();
3823   struct inferior *inf;
3824   struct thread_info *thread;
3825   struct thread_info *selected = NULL;
3826   struct thread_info *lowest_stopped = NULL;
3827   struct thread_info *first = NULL;
3828
3829   /* Consume the initial pending events.  */
3830   while (pending_stop_replies-- > 0)
3831     {
3832       ptid_t waiton_ptid = minus_one_ptid;
3833       ptid_t event_ptid;
3834       struct target_waitstatus ws;
3835       int ignore_event = 0;
3836       struct thread_info *thread;
3837
3838       memset (&ws, 0, sizeof (ws));
3839       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
3840       if (remote_debug)
3841         print_target_wait_results (waiton_ptid, event_ptid, &ws);
3842
3843       switch (ws.kind)
3844         {
3845         case TARGET_WAITKIND_IGNORE:
3846         case TARGET_WAITKIND_NO_RESUMED:
3847         case TARGET_WAITKIND_SIGNALLED:
3848         case TARGET_WAITKIND_EXITED:
3849           /* We shouldn't see these, but if we do, just ignore.  */
3850           if (remote_debug)
3851             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
3852           ignore_event = 1;
3853           break;
3854
3855         case TARGET_WAITKIND_EXECD:
3856           xfree (ws.value.execd_pathname);
3857           break;
3858         default:
3859           break;
3860         }
3861
3862       if (ignore_event)
3863         continue;
3864
3865       thread = find_thread_ptid (event_ptid);
3866
3867       if (ws.kind == TARGET_WAITKIND_STOPPED)
3868         {
3869           enum gdb_signal sig = ws.value.sig;
3870
3871           /* Stubs traditionally report SIGTRAP as initial signal,
3872              instead of signal 0.  Suppress it.  */
3873           if (sig == GDB_SIGNAL_TRAP)
3874             sig = GDB_SIGNAL_0;
3875           thread->suspend.stop_signal = sig;
3876           ws.value.sig = sig;
3877         }
3878
3879       thread->suspend.waitstatus = ws;
3880
3881       if (ws.kind != TARGET_WAITKIND_STOPPED
3882           || ws.value.sig != GDB_SIGNAL_0)
3883         thread->suspend.waitstatus_pending_p = 1;
3884
3885       set_executing (event_ptid, 0);
3886       set_running (event_ptid, 0);
3887       get_remote_thread_info (thread)->vcont_resumed = 0;
3888     }
3889
3890   /* "Notice" the new inferiors before anything related to
3891      registers/memory.  */
3892   ALL_INFERIORS (inf)
3893     {
3894       if (inf->pid == 0)
3895         continue;
3896
3897       inf->needs_setup = 1;
3898
3899       if (non_stop)
3900         {
3901           thread = any_live_thread_of_process (inf->pid);
3902           notice_new_inferior (thread->ptid,
3903                                thread->state == THREAD_RUNNING,
3904                                from_tty);
3905         }
3906     }
3907
3908   /* If all-stop on top of non-stop, pause all threads.  Note this
3909      records the threads' stop pc, so must be done after "noticing"
3910      the inferiors.  */
3911   if (!non_stop)
3912     {
3913       stop_all_threads ();
3914
3915       /* If all threads of an inferior were already stopped, we
3916          haven't setup the inferior yet.  */
3917       ALL_INFERIORS (inf)
3918         {
3919           if (inf->pid == 0)
3920             continue;
3921
3922           if (inf->needs_setup)
3923             {
3924               thread = any_live_thread_of_process (inf->pid);
3925               switch_to_thread_no_regs (thread);
3926               setup_inferior (0);
3927             }
3928         }
3929     }
3930
3931   /* Now go over all threads that are stopped, and print their current
3932      frame.  If all-stop, then if there's a signalled thread, pick
3933      that as current.  */
3934   ALL_NON_EXITED_THREADS (thread)
3935     {
3936       if (first == NULL)
3937         first = thread;
3938
3939       if (!non_stop)
3940         set_running (thread->ptid, 0);
3941       else if (thread->state != THREAD_STOPPED)
3942         continue;
3943
3944       if (selected == NULL
3945           && thread->suspend.waitstatus_pending_p)
3946         selected = thread;
3947
3948       if (lowest_stopped == NULL
3949           || thread->inf->num < lowest_stopped->inf->num
3950           || thread->per_inf_num < lowest_stopped->per_inf_num)
3951         lowest_stopped = thread;
3952
3953       if (non_stop)
3954         print_one_stopped_thread (thread);
3955     }
3956
3957   /* In all-stop, we only print the status of one thread, and leave
3958      others with their status pending.  */
3959   if (!non_stop)
3960     {
3961       thread = selected;
3962       if (thread == NULL)
3963         thread = lowest_stopped;
3964       if (thread == NULL)
3965         thread = first;
3966
3967       print_one_stopped_thread (thread);
3968     }
3969
3970   /* For "info program".  */
3971   thread = inferior_thread ();
3972   if (thread->state == THREAD_STOPPED)
3973     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
3974 }
3975
3976 /* Start the remote connection and sync state.  */
3977
3978 static void
3979 remote_start_remote (int from_tty, struct target_ops *target, int extended_p)
3980 {
3981   struct remote_state *rs = get_remote_state ();
3982   struct packet_config *noack_config;
3983   char *wait_status = NULL;
3984
3985   /* Signal other parts that we're going through the initial setup,
3986      and so things may not be stable yet.  E.g., we don't try to
3987      install tracepoints until we've relocated symbols.  Also, a
3988      Ctrl-C before we're connected and synced up can't interrupt the
3989      target.  Instead, it offers to drop the (potentially wedged)
3990      connection.  */
3991   rs->starting_up = 1;
3992
3993   QUIT;
3994
3995   if (interrupt_on_connect)
3996     send_interrupt_sequence ();
3997
3998   /* Ack any packet which the remote side has already sent.  */
3999   remote_serial_write ("+", 1);
4000
4001   /* The first packet we send to the target is the optional "supported
4002      packets" request.  If the target can answer this, it will tell us
4003      which later probes to skip.  */
4004   remote_query_supported ();
4005
4006   /* If the stub wants to get a QAllow, compose one and send it.  */
4007   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4008     remote_set_permissions (target);
4009
4010   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4011      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4012      as a reply to known packet.  For packet "vFile:setfs:" it is an
4013      invalid reply and GDB would return error in
4014      remote_hostio_set_filesystem, making remote files access impossible.
4015      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4016      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4017   {
4018     const char v_mustreplyempty[] = "vMustReplyEmpty";
4019
4020     putpkt (v_mustreplyempty);
4021     getpkt (&rs->buf, &rs->buf_size, 0);
4022     if (strcmp (rs->buf, "OK") == 0)
4023       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4024     else if (strcmp (rs->buf, "") != 0)
4025       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4026              rs->buf);
4027   }
4028
4029   /* Next, we possibly activate noack mode.
4030
4031      If the QStartNoAckMode packet configuration is set to AUTO,
4032      enable noack mode if the stub reported a wish for it with
4033      qSupported.
4034
4035      If set to TRUE, then enable noack mode even if the stub didn't
4036      report it in qSupported.  If the stub doesn't reply OK, the
4037      session ends with an error.
4038
4039      If FALSE, then don't activate noack mode, regardless of what the
4040      stub claimed should be the default with qSupported.  */
4041
4042   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4043   if (packet_config_support (noack_config) != PACKET_DISABLE)
4044     {
4045       putpkt ("QStartNoAckMode");
4046       getpkt (&rs->buf, &rs->buf_size, 0);
4047       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4048         rs->noack_mode = 1;
4049     }
4050
4051   if (extended_p)
4052     {
4053       /* Tell the remote that we are using the extended protocol.  */
4054       putpkt ("!");
4055       getpkt (&rs->buf, &rs->buf_size, 0);
4056     }
4057
4058   /* Let the target know which signals it is allowed to pass down to
4059      the program.  */
4060   update_signals_program_target ();
4061
4062   /* Next, if the target can specify a description, read it.  We do
4063      this before anything involving memory or registers.  */
4064   target_find_description ();
4065
4066   /* Next, now that we know something about the target, update the
4067      address spaces in the program spaces.  */
4068   update_address_spaces ();
4069
4070   /* On OSs where the list of libraries is global to all
4071      processes, we fetch them early.  */
4072   if (gdbarch_has_global_solist (target_gdbarch ()))
4073     solib_add (NULL, from_tty, auto_solib_add);
4074
4075   if (target_is_non_stop_p ())
4076     {
4077       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4078         error (_("Non-stop mode requested, but remote "
4079                  "does not support non-stop"));
4080
4081       putpkt ("QNonStop:1");
4082       getpkt (&rs->buf, &rs->buf_size, 0);
4083
4084       if (strcmp (rs->buf, "OK") != 0)
4085         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4086
4087       /* Find about threads and processes the stub is already
4088          controlling.  We default to adding them in the running state.
4089          The '?' query below will then tell us about which threads are
4090          stopped.  */
4091       remote_update_thread_list (target);
4092     }
4093   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4094     {
4095       /* Don't assume that the stub can operate in all-stop mode.
4096          Request it explicitly.  */
4097       putpkt ("QNonStop:0");
4098       getpkt (&rs->buf, &rs->buf_size, 0);
4099
4100       if (strcmp (rs->buf, "OK") != 0)
4101         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4102     }
4103
4104   /* Upload TSVs regardless of whether the target is running or not.  The
4105      remote stub, such as GDBserver, may have some predefined or builtin
4106      TSVs, even if the target is not running.  */
4107   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4108     {
4109       struct uploaded_tsv *uploaded_tsvs = NULL;
4110
4111       remote_upload_trace_state_variables (target, &uploaded_tsvs);
4112       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4113     }
4114
4115   /* Check whether the target is running now.  */
4116   putpkt ("?");
4117   getpkt (&rs->buf, &rs->buf_size, 0);
4118
4119   if (!target_is_non_stop_p ())
4120     {
4121       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4122         {
4123           if (!extended_p)
4124             error (_("The target is not running (try extended-remote?)"));
4125
4126           /* We're connected, but not running.  Drop out before we
4127              call start_remote.  */
4128           rs->starting_up = 0;
4129           return;
4130         }
4131       else
4132         {
4133           /* Save the reply for later.  */
4134           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4135           strcpy (wait_status, rs->buf);
4136         }
4137
4138       /* Fetch thread list.  */
4139       target_update_thread_list ();
4140
4141       /* Let the stub know that we want it to return the thread.  */
4142       set_continue_thread (minus_one_ptid);
4143
4144       if (thread_count () == 0)
4145         {
4146           /* Target has no concept of threads at all.  GDB treats
4147              non-threaded target as single-threaded; add a main
4148              thread.  */
4149           add_current_inferior_and_thread (wait_status);
4150         }
4151       else
4152         {
4153           /* We have thread information; select the thread the target
4154              says should be current.  If we're reconnecting to a
4155              multi-threaded program, this will ideally be the thread
4156              that last reported an event before GDB disconnected.  */
4157           inferior_ptid = get_current_thread (wait_status);
4158           if (ptid_equal (inferior_ptid, null_ptid))
4159             {
4160               /* Odd... The target was able to list threads, but not
4161                  tell us which thread was current (no "thread"
4162                  register in T stop reply?).  Just pick the first
4163                  thread in the thread list then.  */
4164               
4165               if (remote_debug)
4166                 fprintf_unfiltered (gdb_stdlog,
4167                                     "warning: couldn't determine remote "
4168                                     "current thread; picking first in list.\n");
4169
4170               inferior_ptid = thread_list->ptid;
4171             }
4172         }
4173
4174       /* init_wait_for_inferior should be called before get_offsets in order
4175          to manage `inserted' flag in bp loc in a correct state.
4176          breakpoint_init_inferior, called from init_wait_for_inferior, set
4177          `inserted' flag to 0, while before breakpoint_re_set, called from
4178          start_remote, set `inserted' flag to 1.  In the initialization of
4179          inferior, breakpoint_init_inferior should be called first, and then
4180          breakpoint_re_set can be called.  If this order is broken, state of
4181          `inserted' flag is wrong, and cause some problems on breakpoint
4182          manipulation.  */
4183       init_wait_for_inferior ();
4184
4185       get_offsets ();           /* Get text, data & bss offsets.  */
4186
4187       /* If we could not find a description using qXfer, and we know
4188          how to do it some other way, try again.  This is not
4189          supported for non-stop; it could be, but it is tricky if
4190          there are no stopped threads when we connect.  */
4191       if (remote_read_description_p (target)
4192           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4193         {
4194           target_clear_description ();
4195           target_find_description ();
4196         }
4197
4198       /* Use the previously fetched status.  */
4199       gdb_assert (wait_status != NULL);
4200       strcpy (rs->buf, wait_status);
4201       rs->cached_wait_status = 1;
4202
4203       start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4204     }
4205   else
4206     {
4207       /* Clear WFI global state.  Do this before finding about new
4208          threads and inferiors, and setting the current inferior.
4209          Otherwise we would clear the proceed status of the current
4210          inferior when we want its stop_soon state to be preserved
4211          (see notice_new_inferior).  */
4212       init_wait_for_inferior ();
4213
4214       /* In non-stop, we will either get an "OK", meaning that there
4215          are no stopped threads at this time; or, a regular stop
4216          reply.  In the latter case, there may be more than one thread
4217          stopped --- we pull them all out using the vStopped
4218          mechanism.  */
4219       if (strcmp (rs->buf, "OK") != 0)
4220         {
4221           struct notif_client *notif = &notif_client_stop;
4222
4223           /* remote_notif_get_pending_replies acks this one, and gets
4224              the rest out.  */
4225           rs->notif_state->pending_event[notif_client_stop.id]
4226             = remote_notif_parse (notif, rs->buf);
4227           remote_notif_get_pending_events (notif);
4228         }
4229
4230       if (thread_count () == 0)
4231         {
4232           if (!extended_p)
4233             error (_("The target is not running (try extended-remote?)"));
4234
4235           /* We're connected, but not running.  Drop out before we
4236              call start_remote.  */
4237           rs->starting_up = 0;
4238           return;
4239         }
4240
4241       /* In non-stop mode, any cached wait status will be stored in
4242          the stop reply queue.  */
4243       gdb_assert (wait_status == NULL);
4244
4245       /* Report all signals during attach/startup.  */
4246       remote_pass_signals (target, 0, NULL);
4247
4248       /* If there are already stopped threads, mark them stopped and
4249          report their stops before giving the prompt to the user.  */
4250       process_initial_stop_replies (from_tty);
4251
4252       if (target_can_async_p ())
4253         target_async (1);
4254     }
4255
4256   /* If we connected to a live target, do some additional setup.  */
4257   if (target_has_execution)
4258     {
4259       if (symfile_objfile)      /* No use without a symbol-file.  */
4260         remote_check_symbols ();
4261     }
4262
4263   /* Possibly the target has been engaged in a trace run started
4264      previously; find out where things are at.  */
4265   if (remote_get_trace_status (target, current_trace_status ()) != -1)
4266     {
4267       struct uploaded_tp *uploaded_tps = NULL;
4268
4269       if (current_trace_status ()->running)
4270         printf_filtered (_("Trace is already running on the target.\n"));
4271
4272       remote_upload_tracepoints (target, &uploaded_tps);
4273
4274       merge_uploaded_tracepoints (&uploaded_tps);
4275     }
4276
4277   /* Possibly the target has been engaged in a btrace record started
4278      previously; find out where things are at.  */
4279   remote_btrace_maybe_reopen ();
4280
4281   /* The thread and inferior lists are now synchronized with the
4282      target, our symbols have been relocated, and we're merged the
4283      target's tracepoints with ours.  We're done with basic start
4284      up.  */
4285   rs->starting_up = 0;
4286
4287   /* Maybe breakpoints are global and need to be inserted now.  */
4288   if (breakpoints_should_be_inserted_now ())
4289     insert_breakpoints ();
4290 }
4291
4292 /* Open a connection to a remote debugger.
4293    NAME is the filename used for communication.  */
4294
4295 static void
4296 remote_open (const char *name, int from_tty)
4297 {
4298   remote_open_1 (name, from_tty, &remote_ops, 0);
4299 }
4300
4301 /* Open a connection to a remote debugger using the extended
4302    remote gdb protocol.  NAME is the filename used for communication.  */
4303
4304 static void
4305 extended_remote_open (const char *name, int from_tty)
4306 {
4307   remote_open_1 (name, from_tty, &extended_remote_ops, 1 /*extended_p */);
4308 }
4309
4310 /* Reset all packets back to "unknown support".  Called when opening a
4311    new connection to a remote target.  */
4312
4313 static void
4314 reset_all_packet_configs_support (void)
4315 {
4316   int i;
4317
4318   for (i = 0; i < PACKET_MAX; i++)
4319     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4320 }
4321
4322 /* Initialize all packet configs.  */
4323
4324 static void
4325 init_all_packet_configs (void)
4326 {
4327   int i;
4328
4329   for (i = 0; i < PACKET_MAX; i++)
4330     {
4331       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4332       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4333     }
4334 }
4335
4336 /* Symbol look-up.  */
4337
4338 static void
4339 remote_check_symbols (void)
4340 {
4341   char *msg, *reply, *tmp;
4342   int end;
4343   long reply_size;
4344   struct cleanup *old_chain;
4345
4346   /* The remote side has no concept of inferiors that aren't running
4347      yet, it only knows about running processes.  If we're connected
4348      but our current inferior is not running, we should not invite the
4349      remote target to request symbol lookups related to its
4350      (unrelated) current process.  */
4351   if (!target_has_execution)
4352     return;
4353
4354   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4355     return;
4356
4357   /* Make sure the remote is pointing at the right process.  Note
4358      there's no way to select "no process".  */
4359   set_general_process ();
4360
4361   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4362      because we need both at the same time.  */
4363   msg = (char *) xmalloc (get_remote_packet_size ());
4364   old_chain = make_cleanup (xfree, msg);
4365   reply = (char *) xmalloc (get_remote_packet_size ());
4366   make_cleanup (free_current_contents, &reply);
4367   reply_size = get_remote_packet_size ();
4368
4369   /* Invite target to request symbol lookups.  */
4370
4371   putpkt ("qSymbol::");
4372   getpkt (&reply, &reply_size, 0);
4373   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4374
4375   while (startswith (reply, "qSymbol:"))
4376     {
4377       struct bound_minimal_symbol sym;
4378
4379       tmp = &reply[8];
4380       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4381       msg[end] = '\0';
4382       sym = lookup_minimal_symbol (msg, NULL, NULL);
4383       if (sym.minsym == NULL)
4384         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4385       else
4386         {
4387           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4388           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4389
4390           /* If this is a function address, return the start of code
4391              instead of any data function descriptor.  */
4392           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4393                                                          sym_addr,
4394                                                          &current_target);
4395
4396           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4397                      phex_nz (sym_addr, addr_size), &reply[8]);
4398         }
4399   
4400       putpkt (msg);
4401       getpkt (&reply, &reply_size, 0);
4402     }
4403
4404   do_cleanups (old_chain);
4405 }
4406
4407 static struct serial *
4408 remote_serial_open (const char *name)
4409 {
4410   static int udp_warning = 0;
4411
4412   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4413      of in ser-tcp.c, because it is the remote protocol assuming that the
4414      serial connection is reliable and not the serial connection promising
4415      to be.  */
4416   if (!udp_warning && startswith (name, "udp:"))
4417     {
4418       warning (_("The remote protocol may be unreliable over UDP.\n"
4419                  "Some events may be lost, rendering further debugging "
4420                  "impossible."));
4421       udp_warning = 1;
4422     }
4423
4424   return serial_open (name);
4425 }
4426
4427 /* Inform the target of our permission settings.  The permission flags
4428    work without this, but if the target knows the settings, it can do
4429    a couple things.  First, it can add its own check, to catch cases
4430    that somehow manage to get by the permissions checks in target
4431    methods.  Second, if the target is wired to disallow particular
4432    settings (for instance, a system in the field that is not set up to
4433    be able to stop at a breakpoint), it can object to any unavailable
4434    permissions.  */
4435
4436 void
4437 remote_set_permissions (struct target_ops *self)
4438 {
4439   struct remote_state *rs = get_remote_state ();
4440
4441   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4442              "WriteReg:%x;WriteMem:%x;"
4443              "InsertBreak:%x;InsertTrace:%x;"
4444              "InsertFastTrace:%x;Stop:%x",
4445              may_write_registers, may_write_memory,
4446              may_insert_breakpoints, may_insert_tracepoints,
4447              may_insert_fast_tracepoints, may_stop);
4448   putpkt (rs->buf);
4449   getpkt (&rs->buf, &rs->buf_size, 0);
4450
4451   /* If the target didn't like the packet, warn the user.  Do not try
4452      to undo the user's settings, that would just be maddening.  */
4453   if (strcmp (rs->buf, "OK") != 0)
4454     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4455 }
4456
4457 /* This type describes each known response to the qSupported
4458    packet.  */
4459 struct protocol_feature
4460 {
4461   /* The name of this protocol feature.  */
4462   const char *name;
4463
4464   /* The default for this protocol feature.  */
4465   enum packet_support default_support;
4466
4467   /* The function to call when this feature is reported, or after
4468      qSupported processing if the feature is not supported.
4469      The first argument points to this structure.  The second
4470      argument indicates whether the packet requested support be
4471      enabled, disabled, or probed (or the default, if this function
4472      is being called at the end of processing and this feature was
4473      not reported).  The third argument may be NULL; if not NULL, it
4474      is a NUL-terminated string taken from the packet following
4475      this feature's name and an equals sign.  */
4476   void (*func) (const struct protocol_feature *, enum packet_support,
4477                 const char *);
4478
4479   /* The corresponding packet for this feature.  Only used if
4480      FUNC is remote_supported_packet.  */
4481   int packet;
4482 };
4483
4484 static void
4485 remote_supported_packet (const struct protocol_feature *feature,
4486                          enum packet_support support,
4487                          const char *argument)
4488 {
4489   if (argument)
4490     {
4491       warning (_("Remote qSupported response supplied an unexpected value for"
4492                  " \"%s\"."), feature->name);
4493       return;
4494     }
4495
4496   remote_protocol_packets[feature->packet].support = support;
4497 }
4498
4499 static void
4500 remote_packet_size (const struct protocol_feature *feature,
4501                     enum packet_support support, const char *value)
4502 {
4503   struct remote_state *rs = get_remote_state ();
4504
4505   int packet_size;
4506   char *value_end;
4507
4508   if (support != PACKET_ENABLE)
4509     return;
4510
4511   if (value == NULL || *value == '\0')
4512     {
4513       warning (_("Remote target reported \"%s\" without a size."),
4514                feature->name);
4515       return;
4516     }
4517
4518   errno = 0;
4519   packet_size = strtol (value, &value_end, 16);
4520   if (errno != 0 || *value_end != '\0' || packet_size < 0)
4521     {
4522       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
4523                feature->name, value);
4524       return;
4525     }
4526
4527   /* Record the new maximum packet size.  */
4528   rs->explicit_packet_size = packet_size;
4529 }
4530
4531 static const struct protocol_feature remote_protocol_features[] = {
4532   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
4533   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
4534     PACKET_qXfer_auxv },
4535   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
4536     PACKET_qXfer_exec_file },
4537   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
4538     PACKET_qXfer_features },
4539   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
4540     PACKET_qXfer_libraries },
4541   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
4542     PACKET_qXfer_libraries_svr4 },
4543   { "augmented-libraries-svr4-read", PACKET_DISABLE,
4544     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
4545   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
4546     PACKET_qXfer_memory_map },
4547   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
4548     PACKET_qXfer_spu_read },
4549   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
4550     PACKET_qXfer_spu_write },
4551   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
4552     PACKET_qXfer_osdata },
4553   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
4554     PACKET_qXfer_threads },
4555   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
4556     PACKET_qXfer_traceframe_info },
4557   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
4558     PACKET_QPassSignals },
4559   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
4560     PACKET_QCatchSyscalls },
4561   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
4562     PACKET_QProgramSignals },
4563   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
4564     PACKET_QSetWorkingDir },
4565   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
4566     PACKET_QStartupWithShell },
4567   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
4568     PACKET_QEnvironmentHexEncoded },
4569   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
4570     PACKET_QEnvironmentReset },
4571   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
4572     PACKET_QEnvironmentUnset },
4573   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
4574     PACKET_QStartNoAckMode },
4575   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
4576     PACKET_multiprocess_feature },
4577   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
4578   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
4579     PACKET_qXfer_siginfo_read },
4580   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
4581     PACKET_qXfer_siginfo_write },
4582   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
4583     PACKET_ConditionalTracepoints },
4584   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
4585     PACKET_ConditionalBreakpoints },
4586   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
4587     PACKET_BreakpointCommands },
4588   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
4589     PACKET_FastTracepoints },
4590   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
4591     PACKET_StaticTracepoints },
4592   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
4593    PACKET_InstallInTrace},
4594   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
4595     PACKET_DisconnectedTracing_feature },
4596   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
4597     PACKET_bc },
4598   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
4599     PACKET_bs },
4600   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
4601     PACKET_TracepointSource },
4602   { "QAllow", PACKET_DISABLE, remote_supported_packet,
4603     PACKET_QAllow },
4604   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
4605     PACKET_EnableDisableTracepoints_feature },
4606   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
4607     PACKET_qXfer_fdpic },
4608   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
4609     PACKET_qXfer_uib },
4610   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
4611     PACKET_QDisableRandomization },
4612   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
4613   { "QTBuffer:size", PACKET_DISABLE,
4614     remote_supported_packet, PACKET_QTBuffer_size},
4615   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
4616   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
4617   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
4618   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
4619   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
4620     PACKET_qXfer_btrace },
4621   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
4622     PACKET_qXfer_btrace_conf },
4623   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
4624     PACKET_Qbtrace_conf_bts_size },
4625   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
4626   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
4627   { "fork-events", PACKET_DISABLE, remote_supported_packet,
4628     PACKET_fork_event_feature },
4629   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
4630     PACKET_vfork_event_feature },
4631   { "exec-events", PACKET_DISABLE, remote_supported_packet,
4632     PACKET_exec_event_feature },
4633   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
4634     PACKET_Qbtrace_conf_pt_size },
4635   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
4636   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
4637   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
4638 };
4639
4640 static char *remote_support_xml;
4641
4642 /* Register string appended to "xmlRegisters=" in qSupported query.  */
4643
4644 void
4645 register_remote_support_xml (const char *xml)
4646 {
4647 #if defined(HAVE_LIBEXPAT)
4648   if (remote_support_xml == NULL)
4649     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
4650   else
4651     {
4652       char *copy = xstrdup (remote_support_xml + 13);
4653       char *p = strtok (copy, ",");
4654
4655       do
4656         {
4657           if (strcmp (p, xml) == 0)
4658             {
4659               /* already there */
4660               xfree (copy);
4661               return;
4662             }
4663         }
4664       while ((p = strtok (NULL, ",")) != NULL);
4665       xfree (copy);
4666
4667       remote_support_xml = reconcat (remote_support_xml,
4668                                      remote_support_xml, ",", xml,
4669                                      (char *) NULL);
4670     }
4671 #endif
4672 }
4673
4674 static char *
4675 remote_query_supported_append (char *msg, const char *append)
4676 {
4677   if (msg)
4678     return reconcat (msg, msg, ";", append, (char *) NULL);
4679   else
4680     return xstrdup (append);
4681 }
4682
4683 static void
4684 remote_query_supported (void)
4685 {
4686   struct remote_state *rs = get_remote_state ();
4687   char *next;
4688   int i;
4689   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
4690
4691   /* The packet support flags are handled differently for this packet
4692      than for most others.  We treat an error, a disabled packet, and
4693      an empty response identically: any features which must be reported
4694      to be used will be automatically disabled.  An empty buffer
4695      accomplishes this, since that is also the representation for a list
4696      containing no features.  */
4697
4698   rs->buf[0] = 0;
4699   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
4700     {
4701       char *q = NULL;
4702       struct cleanup *old_chain = make_cleanup (free_current_contents, &q);
4703
4704       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
4705         q = remote_query_supported_append (q, "multiprocess+");
4706
4707       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
4708         q = remote_query_supported_append (q, "swbreak+");
4709       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
4710         q = remote_query_supported_append (q, "hwbreak+");
4711
4712       q = remote_query_supported_append (q, "qRelocInsn+");
4713
4714       if (packet_set_cmd_state (PACKET_fork_event_feature)
4715           != AUTO_BOOLEAN_FALSE)
4716         q = remote_query_supported_append (q, "fork-events+");
4717       if (packet_set_cmd_state (PACKET_vfork_event_feature)
4718           != AUTO_BOOLEAN_FALSE)
4719         q = remote_query_supported_append (q, "vfork-events+");
4720       if (packet_set_cmd_state (PACKET_exec_event_feature)
4721           != AUTO_BOOLEAN_FALSE)
4722         q = remote_query_supported_append (q, "exec-events+");
4723
4724       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
4725         q = remote_query_supported_append (q, "vContSupported+");
4726
4727       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
4728         q = remote_query_supported_append (q, "QThreadEvents+");
4729
4730       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
4731         q = remote_query_supported_append (q, "no-resumed+");
4732
4733       /* Keep this one last to work around a gdbserver <= 7.10 bug in
4734          the qSupported:xmlRegisters=i386 handling.  */
4735       if (remote_support_xml != NULL
4736           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
4737         q = remote_query_supported_append (q, remote_support_xml);
4738
4739       q = reconcat (q, "qSupported:", q, (char *) NULL);
4740       putpkt (q);
4741
4742       do_cleanups (old_chain);
4743
4744       getpkt (&rs->buf, &rs->buf_size, 0);
4745
4746       /* If an error occured, warn, but do not return - just reset the
4747          buffer to empty and go on to disable features.  */
4748       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
4749           == PACKET_ERROR)
4750         {
4751           warning (_("Remote failure reply: %s"), rs->buf);
4752           rs->buf[0] = 0;
4753         }
4754     }
4755
4756   memset (seen, 0, sizeof (seen));
4757
4758   next = rs->buf;
4759   while (*next)
4760     {
4761       enum packet_support is_supported;
4762       char *p, *end, *name_end, *value;
4763
4764       /* First separate out this item from the rest of the packet.  If
4765          there's another item after this, we overwrite the separator
4766          (terminated strings are much easier to work with).  */
4767       p = next;
4768       end = strchr (p, ';');
4769       if (end == NULL)
4770         {
4771           end = p + strlen (p);
4772           next = end;
4773         }
4774       else
4775         {
4776           *end = '\0';
4777           next = end + 1;
4778
4779           if (end == p)
4780             {
4781               warning (_("empty item in \"qSupported\" response"));
4782               continue;
4783             }
4784         }
4785
4786       name_end = strchr (p, '=');
4787       if (name_end)
4788         {
4789           /* This is a name=value entry.  */
4790           is_supported = PACKET_ENABLE;
4791           value = name_end + 1;
4792           *name_end = '\0';
4793         }
4794       else
4795         {
4796           value = NULL;
4797           switch (end[-1])
4798             {
4799             case '+':
4800               is_supported = PACKET_ENABLE;
4801               break;
4802
4803             case '-':
4804               is_supported = PACKET_DISABLE;
4805               break;
4806
4807             case '?':
4808               is_supported = PACKET_SUPPORT_UNKNOWN;
4809               break;
4810
4811             default:
4812               warning (_("unrecognized item \"%s\" "
4813                          "in \"qSupported\" response"), p);
4814               continue;
4815             }
4816           end[-1] = '\0';
4817         }
4818
4819       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4820         if (strcmp (remote_protocol_features[i].name, p) == 0)
4821           {
4822             const struct protocol_feature *feature;
4823
4824             seen[i] = 1;
4825             feature = &remote_protocol_features[i];
4826             feature->func (feature, is_supported, value);
4827             break;
4828           }
4829     }
4830
4831   /* If we increased the packet size, make sure to increase the global
4832      buffer size also.  We delay this until after parsing the entire
4833      qSupported packet, because this is the same buffer we were
4834      parsing.  */
4835   if (rs->buf_size < rs->explicit_packet_size)
4836     {
4837       rs->buf_size = rs->explicit_packet_size;
4838       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
4839     }
4840
4841   /* Handle the defaults for unmentioned features.  */
4842   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
4843     if (!seen[i])
4844       {
4845         const struct protocol_feature *feature;
4846
4847         feature = &remote_protocol_features[i];
4848         feature->func (feature, feature->default_support, NULL);
4849       }
4850 }
4851
4852 /* Serial QUIT handler for the remote serial descriptor.
4853
4854    Defers handling a Ctrl-C until we're done with the current
4855    command/response packet sequence, unless:
4856
4857    - We're setting up the connection.  Don't send a remote interrupt
4858      request, as we're not fully synced yet.  Quit immediately
4859      instead.
4860
4861    - The target has been resumed in the foreground
4862      (target_terminal::is_ours is false) with a synchronous resume
4863      packet, and we're blocked waiting for the stop reply, thus a
4864      Ctrl-C should be immediately sent to the target.
4865
4866    - We get a second Ctrl-C while still within the same serial read or
4867      write.  In that case the serial is seemingly wedged --- offer to
4868      quit/disconnect.
4869
4870    - We see a second Ctrl-C without target response, after having
4871      previously interrupted the target.  In that case the target/stub
4872      is probably wedged --- offer to quit/disconnect.
4873 */
4874
4875 static void
4876 remote_serial_quit_handler (void)
4877 {
4878   struct remote_state *rs = get_remote_state ();
4879
4880   if (check_quit_flag ())
4881     {
4882       /* If we're starting up, we're not fully synced yet.  Quit
4883          immediately.  */
4884       if (rs->starting_up)
4885         quit ();
4886       else if (rs->got_ctrlc_during_io)
4887         {
4888           if (query (_("The target is not responding to GDB commands.\n"
4889                        "Stop debugging it? ")))
4890             remote_unpush_and_throw ();
4891         }
4892       /* If ^C has already been sent once, offer to disconnect.  */
4893       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
4894         interrupt_query ();
4895       /* All-stop protocol, and blocked waiting for stop reply.  Send
4896          an interrupt request.  */
4897       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
4898         target_interrupt ();
4899       else
4900         rs->got_ctrlc_during_io = 1;
4901     }
4902 }
4903
4904 /* Remove any of the remote.c targets from target stack.  Upper targets depend
4905    on it so remove them first.  */
4906
4907 static void
4908 remote_unpush_target (void)
4909 {
4910   pop_all_targets_at_and_above (process_stratum);
4911 }
4912
4913 static void
4914 remote_unpush_and_throw (void)
4915 {
4916   remote_unpush_target ();
4917   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
4918 }
4919
4920 static void
4921 remote_open_1 (const char *name, int from_tty,
4922                struct target_ops *target, int extended_p)
4923 {
4924   struct remote_state *rs = get_remote_state ();
4925
4926   if (name == 0)
4927     error (_("To open a remote debug connection, you need to specify what\n"
4928            "serial device is attached to the remote system\n"
4929            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
4930
4931   /* See FIXME above.  */
4932   if (!target_async_permitted)
4933     wait_forever_enabled_p = 1;
4934
4935   /* If we're connected to a running target, target_preopen will kill it.
4936      Ask this question first, before target_preopen has a chance to kill
4937      anything.  */
4938   if (rs->remote_desc != NULL && !have_inferiors ())
4939     {
4940       if (from_tty
4941           && !query (_("Already connected to a remote target.  Disconnect? ")))
4942         error (_("Still connected."));
4943     }
4944
4945   /* Here the possibly existing remote target gets unpushed.  */
4946   target_preopen (from_tty);
4947
4948   /* Make sure we send the passed signals list the next time we resume.  */
4949   xfree (rs->last_pass_packet);
4950   rs->last_pass_packet = NULL;
4951
4952   /* Make sure we send the program signals list the next time we
4953      resume.  */
4954   xfree (rs->last_program_signals_packet);
4955   rs->last_program_signals_packet = NULL;
4956
4957   remote_fileio_reset ();
4958   reopen_exec_file ();
4959   reread_symbols ();
4960
4961   rs->remote_desc = remote_serial_open (name);
4962   if (!rs->remote_desc)
4963     perror_with_name (name);
4964
4965   if (baud_rate != -1)
4966     {
4967       if (serial_setbaudrate (rs->remote_desc, baud_rate))
4968         {
4969           /* The requested speed could not be set.  Error out to
4970              top level after closing remote_desc.  Take care to
4971              set remote_desc to NULL to avoid closing remote_desc
4972              more than once.  */
4973           serial_close (rs->remote_desc);
4974           rs->remote_desc = NULL;
4975           perror_with_name (name);
4976         }
4977     }
4978
4979   serial_setparity (rs->remote_desc, serial_parity);
4980   serial_raw (rs->remote_desc);
4981
4982   /* If there is something sitting in the buffer we might take it as a
4983      response to a command, which would be bad.  */
4984   serial_flush_input (rs->remote_desc);
4985
4986   if (from_tty)
4987     {
4988       puts_filtered ("Remote debugging using ");
4989       puts_filtered (name);
4990       puts_filtered ("\n");
4991     }
4992   push_target (target);         /* Switch to using remote target now.  */
4993
4994   /* Register extra event sources in the event loop.  */
4995   remote_async_inferior_event_token
4996     = create_async_event_handler (remote_async_inferior_event_handler,
4997                                   NULL);
4998   rs->notif_state = remote_notif_state_allocate ();
4999
5000   /* Reset the target state; these things will be queried either by
5001      remote_query_supported or as they are needed.  */
5002   reset_all_packet_configs_support ();
5003   rs->cached_wait_status = 0;
5004   rs->explicit_packet_size = 0;
5005   rs->noack_mode = 0;
5006   rs->extended = extended_p;
5007   rs->waiting_for_stop_reply = 0;
5008   rs->ctrlc_pending_p = 0;
5009   rs->got_ctrlc_during_io = 0;
5010
5011   rs->general_thread = not_sent_ptid;
5012   rs->continue_thread = not_sent_ptid;
5013   rs->remote_traceframe_number = -1;
5014
5015   rs->last_resume_exec_dir = EXEC_FORWARD;
5016
5017   /* Probe for ability to use "ThreadInfo" query, as required.  */
5018   rs->use_threadinfo_query = 1;
5019   rs->use_threadextra_query = 1;
5020
5021   readahead_cache_invalidate ();
5022
5023   if (target_async_permitted)
5024     {
5025       /* FIXME: cagney/1999-09-23: During the initial connection it is
5026          assumed that the target is already ready and able to respond to
5027          requests.  Unfortunately remote_start_remote() eventually calls
5028          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5029          around this.  Eventually a mechanism that allows
5030          wait_for_inferior() to expect/get timeouts will be
5031          implemented.  */
5032       wait_forever_enabled_p = 0;
5033     }
5034
5035   /* First delete any symbols previously loaded from shared libraries.  */
5036   no_shared_libraries (NULL, 0);
5037
5038   /* Start afresh.  */
5039   init_thread_list ();
5040
5041   /* Start the remote connection.  If error() or QUIT, discard this
5042      target (we'd otherwise be in an inconsistent state) and then
5043      propogate the error on up the exception chain.  This ensures that
5044      the caller doesn't stumble along blindly assuming that the
5045      function succeeded.  The CLI doesn't have this problem but other
5046      UI's, such as MI do.
5047
5048      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5049      this function should return an error indication letting the
5050      caller restore the previous state.  Unfortunately the command
5051      ``target remote'' is directly wired to this function making that
5052      impossible.  On a positive note, the CLI side of this problem has
5053      been fixed - the function set_cmd_context() makes it possible for
5054      all the ``target ....'' commands to share a common callback
5055      function.  See cli-dump.c.  */
5056   {
5057
5058     TRY
5059       {
5060         remote_start_remote (from_tty, target, extended_p);
5061       }
5062     CATCH (ex, RETURN_MASK_ALL)
5063       {
5064         /* Pop the partially set up target - unless something else did
5065            already before throwing the exception.  */
5066         if (rs->remote_desc != NULL)
5067           remote_unpush_target ();
5068         if (target_async_permitted)
5069           wait_forever_enabled_p = 1;
5070         throw_exception (ex);
5071       }
5072     END_CATCH
5073   }
5074
5075   remote_btrace_reset ();
5076
5077   if (target_async_permitted)
5078     wait_forever_enabled_p = 1;
5079 }
5080
5081 /* Detach the specified process.  */
5082
5083 static void
5084 remote_detach_pid (int pid)
5085 {
5086   struct remote_state *rs = get_remote_state ();
5087
5088   if (remote_multi_process_p (rs))
5089     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5090   else
5091     strcpy (rs->buf, "D");
5092
5093   putpkt (rs->buf);
5094   getpkt (&rs->buf, &rs->buf_size, 0);
5095
5096   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5097     ;
5098   else if (rs->buf[0] == '\0')
5099     error (_("Remote doesn't know how to detach"));
5100   else
5101     error (_("Can't detach process."));
5102 }
5103
5104 /* This detaches a program to which we previously attached, using
5105    inferior_ptid to identify the process.  After this is done, GDB
5106    can be used to debug some other program.  We better not have left
5107    any breakpoints in the target program or it'll die when it hits
5108    one.  */
5109
5110 static void
5111 remote_detach_1 (int from_tty, inferior *inf)
5112 {
5113   int pid = ptid_get_pid (inferior_ptid);
5114   struct remote_state *rs = get_remote_state ();
5115   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5116   int is_fork_parent;
5117
5118   if (!target_has_execution)
5119     error (_("No process to detach from."));
5120
5121   target_announce_detach (from_tty);
5122
5123   /* Tell the remote target to detach.  */
5124   remote_detach_pid (pid);
5125
5126   /* Exit only if this is the only active inferior.  */
5127   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5128     puts_filtered (_("Ending remote debugging.\n"));
5129
5130   /* Check to see if we are detaching a fork parent.  Note that if we
5131      are detaching a fork child, tp == NULL.  */
5132   is_fork_parent = (tp != NULL
5133                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5134
5135   /* If doing detach-on-fork, we don't mourn, because that will delete
5136      breakpoints that should be available for the followed inferior.  */
5137   if (!is_fork_parent)
5138     {
5139       /* Save the pid as a string before mourning, since that will
5140          unpush the remote target, and we need the string after.  */
5141       std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5142
5143       target_mourn_inferior (inferior_ptid);
5144       if (print_inferior_events)
5145         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5146                            inf->num, infpid.c_str ());
5147     }
5148   else
5149     {
5150       inferior_ptid = null_ptid;
5151       detach_inferior (pid);
5152     }
5153 }
5154
5155 static void
5156 remote_detach (struct target_ops *ops, inferior *inf, int from_tty)
5157 {
5158   remote_detach_1 (from_tty, inf);
5159 }
5160
5161 static void
5162 extended_remote_detach (struct target_ops *ops, inferior *inf, int from_tty)
5163 {
5164   remote_detach_1 (from_tty, inf);
5165 }
5166
5167 /* Target follow-fork function for remote targets.  On entry, and
5168    at return, the current inferior is the fork parent.
5169
5170    Note that although this is currently only used for extended-remote,
5171    it is named remote_follow_fork in anticipation of using it for the
5172    remote target as well.  */
5173
5174 static int
5175 remote_follow_fork (struct target_ops *ops, int follow_child,
5176                     int detach_fork)
5177 {
5178   struct remote_state *rs = get_remote_state ();
5179   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5180
5181   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5182       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5183     {
5184       /* When following the parent and detaching the child, we detach
5185          the child here.  For the case of following the child and
5186          detaching the parent, the detach is done in the target-
5187          independent follow fork code in infrun.c.  We can't use
5188          target_detach when detaching an unfollowed child because
5189          the client side doesn't know anything about the child.  */
5190       if (detach_fork && !follow_child)
5191         {
5192           /* Detach the fork child.  */
5193           ptid_t child_ptid;
5194           pid_t child_pid;
5195
5196           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5197           child_pid = ptid_get_pid (child_ptid);
5198
5199           remote_detach_pid (child_pid);
5200         }
5201     }
5202   return 0;
5203 }
5204
5205 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5206    in the program space of the new inferior.  On entry and at return the
5207    current inferior is the exec'ing inferior.  INF is the new exec'd
5208    inferior, which may be the same as the exec'ing inferior unless
5209    follow-exec-mode is "new".  */
5210
5211 static void
5212 remote_follow_exec (struct target_ops *ops,
5213                     struct inferior *inf, char *execd_pathname)
5214 {
5215   /* We know that this is a target file name, so if it has the "target:"
5216      prefix we strip it off before saving it in the program space.  */
5217   if (is_target_filename (execd_pathname))
5218     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5219
5220   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5221 }
5222
5223 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5224
5225 static void
5226 remote_disconnect (struct target_ops *target, const char *args, int from_tty)
5227 {
5228   if (args)
5229     error (_("Argument given to \"disconnect\" when remotely debugging."));
5230
5231   /* Make sure we unpush even the extended remote targets.  Calling
5232      target_mourn_inferior won't unpush, and remote_mourn won't
5233      unpush if there is more than one inferior left.  */
5234   unpush_target (target);
5235   generic_mourn_inferior ();
5236
5237   if (from_tty)
5238     puts_filtered ("Ending remote debugging.\n");
5239 }
5240
5241 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5242    be chatty about it.  */
5243
5244 static void
5245 extended_remote_attach (struct target_ops *target, const char *args,
5246                         int from_tty)
5247 {
5248   struct remote_state *rs = get_remote_state ();
5249   int pid;
5250   char *wait_status = NULL;
5251
5252   pid = parse_pid_to_attach (args);
5253
5254   /* Remote PID can be freely equal to getpid, do not check it here the same
5255      way as in other targets.  */
5256
5257   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5258     error (_("This target does not support attaching to a process"));
5259
5260   if (from_tty)
5261     {
5262       char *exec_file = get_exec_file (0);
5263
5264       if (exec_file)
5265         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5266                            target_pid_to_str (pid_to_ptid (pid)));
5267       else
5268         printf_unfiltered (_("Attaching to %s\n"),
5269                            target_pid_to_str (pid_to_ptid (pid)));
5270
5271       gdb_flush (gdb_stdout);
5272     }
5273
5274   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5275   putpkt (rs->buf);
5276   getpkt (&rs->buf, &rs->buf_size, 0);
5277
5278   switch (packet_ok (rs->buf,
5279                      &remote_protocol_packets[PACKET_vAttach]))
5280     {
5281     case PACKET_OK:
5282       if (!target_is_non_stop_p ())
5283         {
5284           /* Save the reply for later.  */
5285           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5286           strcpy (wait_status, rs->buf);
5287         }
5288       else if (strcmp (rs->buf, "OK") != 0)
5289         error (_("Attaching to %s failed with: %s"),
5290                target_pid_to_str (pid_to_ptid (pid)),
5291                rs->buf);
5292       break;
5293     case PACKET_UNKNOWN:
5294       error (_("This target does not support attaching to a process"));
5295     default:
5296       error (_("Attaching to %s failed"),
5297              target_pid_to_str (pid_to_ptid (pid)));
5298     }
5299
5300   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5301
5302   inferior_ptid = pid_to_ptid (pid);
5303
5304   if (target_is_non_stop_p ())
5305     {
5306       struct thread_info *thread;
5307
5308       /* Get list of threads.  */
5309       remote_update_thread_list (target);
5310
5311       thread = first_thread_of_process (pid);
5312       if (thread)
5313         inferior_ptid = thread->ptid;
5314       else
5315         inferior_ptid = pid_to_ptid (pid);
5316
5317       /* Invalidate our notion of the remote current thread.  */
5318       record_currthread (rs, minus_one_ptid);
5319     }
5320   else
5321     {
5322       /* Now, if we have thread information, update inferior_ptid.  */
5323       inferior_ptid = remote_current_thread (inferior_ptid);
5324
5325       /* Add the main thread to the thread list.  */
5326       thread_info *thr = add_thread_silent (inferior_ptid);
5327       /* Don't consider the thread stopped until we've processed the
5328          saved stop reply.  */
5329       set_executing (thr->ptid, true);
5330     }
5331
5332   /* Next, if the target can specify a description, read it.  We do
5333      this before anything involving memory or registers.  */
5334   target_find_description ();
5335
5336   if (!target_is_non_stop_p ())
5337     {
5338       /* Use the previously fetched status.  */
5339       gdb_assert (wait_status != NULL);
5340
5341       if (target_can_async_p ())
5342         {
5343           struct notif_event *reply
5344             =  remote_notif_parse (&notif_client_stop, wait_status);
5345
5346           push_stop_reply ((struct stop_reply *) reply);
5347
5348           target_async (1);
5349         }
5350       else
5351         {
5352           gdb_assert (wait_status != NULL);
5353           strcpy (rs->buf, wait_status);
5354           rs->cached_wait_status = 1;
5355         }
5356     }
5357   else
5358     gdb_assert (wait_status == NULL);
5359 }
5360
5361 /* Implementation of the to_post_attach method.  */
5362
5363 static void
5364 extended_remote_post_attach (struct target_ops *ops, int pid)
5365 {
5366   /* Get text, data & bss offsets.  */
5367   get_offsets ();
5368
5369   /* In certain cases GDB might not have had the chance to start
5370      symbol lookup up until now.  This could happen if the debugged
5371      binary is not using shared libraries, the vsyscall page is not
5372      present (on Linux) and the binary itself hadn't changed since the
5373      debugging process was started.  */
5374   if (symfile_objfile != NULL)
5375     remote_check_symbols();
5376 }
5377
5378 \f
5379 /* Check for the availability of vCont.  This function should also check
5380    the response.  */
5381
5382 static void
5383 remote_vcont_probe (struct remote_state *rs)
5384 {
5385   char *buf;
5386
5387   strcpy (rs->buf, "vCont?");
5388   putpkt (rs->buf);
5389   getpkt (&rs->buf, &rs->buf_size, 0);
5390   buf = rs->buf;
5391
5392   /* Make sure that the features we assume are supported.  */
5393   if (startswith (buf, "vCont"))
5394     {
5395       char *p = &buf[5];
5396       int support_c, support_C;
5397
5398       rs->supports_vCont.s = 0;
5399       rs->supports_vCont.S = 0;
5400       support_c = 0;
5401       support_C = 0;
5402       rs->supports_vCont.t = 0;
5403       rs->supports_vCont.r = 0;
5404       while (p && *p == ';')
5405         {
5406           p++;
5407           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5408             rs->supports_vCont.s = 1;
5409           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5410             rs->supports_vCont.S = 1;
5411           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5412             support_c = 1;
5413           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5414             support_C = 1;
5415           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5416             rs->supports_vCont.t = 1;
5417           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5418             rs->supports_vCont.r = 1;
5419
5420           p = strchr (p, ';');
5421         }
5422
5423       /* If c, and C are not all supported, we can't use vCont.  Clearing
5424          BUF will make packet_ok disable the packet.  */
5425       if (!support_c || !support_C)
5426         buf[0] = 0;
5427     }
5428
5429   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5430 }
5431
5432 /* Helper function for building "vCont" resumptions.  Write a
5433    resumption to P.  ENDP points to one-passed-the-end of the buffer
5434    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5435    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5436    resumed thread should be single-stepped and/or signalled.  If PTID
5437    equals minus_one_ptid, then all threads are resumed; if PTID
5438    represents a process, then all threads of the process are resumed;
5439    the thread to be stepped and/or signalled is given in the global
5440    INFERIOR_PTID.  */
5441
5442 static char *
5443 append_resumption (char *p, char *endp,
5444                    ptid_t ptid, int step, enum gdb_signal siggnal)
5445 {
5446   struct remote_state *rs = get_remote_state ();
5447
5448   if (step && siggnal != GDB_SIGNAL_0)
5449     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5450   else if (step
5451            /* GDB is willing to range step.  */
5452            && use_range_stepping
5453            /* Target supports range stepping.  */
5454            && rs->supports_vCont.r
5455            /* We don't currently support range stepping multiple
5456               threads with a wildcard (though the protocol allows it,
5457               so stubs shouldn't make an active effort to forbid
5458               it).  */
5459            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
5460     {
5461       struct thread_info *tp;
5462
5463       if (ptid_equal (ptid, minus_one_ptid))
5464         {
5465           /* If we don't know about the target thread's tid, then
5466              we're resuming magic_null_ptid (see caller).  */
5467           tp = find_thread_ptid (magic_null_ptid);
5468         }
5469       else
5470         tp = find_thread_ptid (ptid);
5471       gdb_assert (tp != NULL);
5472
5473       if (tp->control.may_range_step)
5474         {
5475           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
5476
5477           p += xsnprintf (p, endp - p, ";r%s,%s",
5478                           phex_nz (tp->control.step_range_start,
5479                                    addr_size),
5480                           phex_nz (tp->control.step_range_end,
5481                                    addr_size));
5482         }
5483       else
5484         p += xsnprintf (p, endp - p, ";s");
5485     }
5486   else if (step)
5487     p += xsnprintf (p, endp - p, ";s");
5488   else if (siggnal != GDB_SIGNAL_0)
5489     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
5490   else
5491     p += xsnprintf (p, endp - p, ";c");
5492
5493   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
5494     {
5495       ptid_t nptid;
5496
5497       /* All (-1) threads of process.  */
5498       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
5499
5500       p += xsnprintf (p, endp - p, ":");
5501       p = write_ptid (p, endp, nptid);
5502     }
5503   else if (!ptid_equal (ptid, minus_one_ptid))
5504     {
5505       p += xsnprintf (p, endp - p, ":");
5506       p = write_ptid (p, endp, ptid);
5507     }
5508
5509   return p;
5510 }
5511
5512 /* Clear the thread's private info on resume.  */
5513
5514 static void
5515 resume_clear_thread_private_info (struct thread_info *thread)
5516 {
5517   if (thread->priv != NULL)
5518     {
5519       remote_thread_info *priv = get_remote_thread_info (thread);
5520
5521       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
5522       priv->watch_data_address = 0;
5523     }
5524 }
5525
5526 /* Append a vCont continue-with-signal action for threads that have a
5527    non-zero stop signal.  */
5528
5529 static char *
5530 append_pending_thread_resumptions (char *p, char *endp, ptid_t ptid)
5531 {
5532   struct thread_info *thread;
5533
5534   ALL_NON_EXITED_THREADS (thread)
5535     if (ptid_match (thread->ptid, ptid)
5536         && !ptid_equal (inferior_ptid, thread->ptid)
5537         && thread->suspend.stop_signal != GDB_SIGNAL_0)
5538       {
5539         p = append_resumption (p, endp, thread->ptid,
5540                                0, thread->suspend.stop_signal);
5541         thread->suspend.stop_signal = GDB_SIGNAL_0;
5542         resume_clear_thread_private_info (thread);
5543       }
5544
5545   return p;
5546 }
5547
5548 /* Set the target running, using the packets that use Hc
5549    (c/s/C/S).  */
5550
5551 static void
5552 remote_resume_with_hc (struct target_ops *ops,
5553                        ptid_t ptid, int step, enum gdb_signal siggnal)
5554 {
5555   struct remote_state *rs = get_remote_state ();
5556   struct thread_info *thread;
5557   char *buf;
5558
5559   rs->last_sent_signal = siggnal;
5560   rs->last_sent_step = step;
5561
5562   /* The c/s/C/S resume packets use Hc, so set the continue
5563      thread.  */
5564   if (ptid_equal (ptid, minus_one_ptid))
5565     set_continue_thread (any_thread_ptid);
5566   else
5567     set_continue_thread (ptid);
5568
5569   ALL_NON_EXITED_THREADS (thread)
5570     resume_clear_thread_private_info (thread);
5571
5572   buf = rs->buf;
5573   if (execution_direction == EXEC_REVERSE)
5574     {
5575       /* We don't pass signals to the target in reverse exec mode.  */
5576       if (info_verbose && siggnal != GDB_SIGNAL_0)
5577         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
5578                  siggnal);
5579
5580       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
5581         error (_("Remote reverse-step not supported."));
5582       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
5583         error (_("Remote reverse-continue not supported."));
5584
5585       strcpy (buf, step ? "bs" : "bc");
5586     }
5587   else if (siggnal != GDB_SIGNAL_0)
5588     {
5589       buf[0] = step ? 'S' : 'C';
5590       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
5591       buf[2] = tohex (((int) siggnal) & 0xf);
5592       buf[3] = '\0';
5593     }
5594   else
5595     strcpy (buf, step ? "s" : "c");
5596
5597   putpkt (buf);
5598 }
5599
5600 /* Resume the remote inferior by using a "vCont" packet.  The thread
5601    to be resumed is PTID; STEP and SIGGNAL indicate whether the
5602    resumed thread should be single-stepped and/or signalled.  If PTID
5603    equals minus_one_ptid, then all threads are resumed; the thread to
5604    be stepped and/or signalled is given in the global INFERIOR_PTID.
5605    This function returns non-zero iff it resumes the inferior.
5606
5607    This function issues a strict subset of all possible vCont commands
5608    at the moment.  */
5609
5610 static int
5611 remote_resume_with_vcont (ptid_t ptid, int step, enum gdb_signal siggnal)
5612 {
5613   struct remote_state *rs = get_remote_state ();
5614   char *p;
5615   char *endp;
5616
5617   /* No reverse execution actions defined for vCont.  */
5618   if (execution_direction == EXEC_REVERSE)
5619     return 0;
5620
5621   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
5622     remote_vcont_probe (rs);
5623
5624   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
5625     return 0;
5626
5627   p = rs->buf;
5628   endp = rs->buf + get_remote_packet_size ();
5629
5630   /* If we could generate a wider range of packets, we'd have to worry
5631      about overflowing BUF.  Should there be a generic
5632      "multi-part-packet" packet?  */
5633
5634   p += xsnprintf (p, endp - p, "vCont");
5635
5636   if (ptid_equal (ptid, magic_null_ptid))
5637     {
5638       /* MAGIC_NULL_PTID means that we don't have any active threads,
5639          so we don't have any TID numbers the inferior will
5640          understand.  Make sure to only send forms that do not specify
5641          a TID.  */
5642       append_resumption (p, endp, minus_one_ptid, step, siggnal);
5643     }
5644   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
5645     {
5646       /* Resume all threads (of all processes, or of a single
5647          process), with preference for INFERIOR_PTID.  This assumes
5648          inferior_ptid belongs to the set of all threads we are about
5649          to resume.  */
5650       if (step || siggnal != GDB_SIGNAL_0)
5651         {
5652           /* Step inferior_ptid, with or without signal.  */
5653           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
5654         }
5655
5656       /* Also pass down any pending signaled resumption for other
5657          threads not the current.  */
5658       p = append_pending_thread_resumptions (p, endp, ptid);
5659
5660       /* And continue others without a signal.  */
5661       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
5662     }
5663   else
5664     {
5665       /* Scheduler locking; resume only PTID.  */
5666       append_resumption (p, endp, ptid, step, siggnal);
5667     }
5668
5669   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
5670   putpkt (rs->buf);
5671
5672   if (target_is_non_stop_p ())
5673     {
5674       /* In non-stop, the stub replies to vCont with "OK".  The stop
5675          reply will be reported asynchronously by means of a `%Stop'
5676          notification.  */
5677       getpkt (&rs->buf, &rs->buf_size, 0);
5678       if (strcmp (rs->buf, "OK") != 0)
5679         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5680     }
5681
5682   return 1;
5683 }
5684
5685 /* Tell the remote machine to resume.  */
5686
5687 static void
5688 remote_resume (struct target_ops *ops,
5689                ptid_t ptid, int step, enum gdb_signal siggnal)
5690 {
5691   struct remote_state *rs = get_remote_state ();
5692
5693   /* When connected in non-stop mode, the core resumes threads
5694      individually.  Resuming remote threads directly in target_resume
5695      would thus result in sending one packet per thread.  Instead, to
5696      minimize roundtrip latency, here we just store the resume
5697      request; the actual remote resumption will be done in
5698      target_commit_resume / remote_commit_resume, where we'll be able
5699      to do vCont action coalescing.  */
5700   if (target_is_non_stop_p () && execution_direction != EXEC_REVERSE)
5701     {
5702       remote_thread_info *remote_thr;
5703
5704       if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
5705         remote_thr = get_remote_thread_info (inferior_ptid);
5706       else
5707         remote_thr = get_remote_thread_info (ptid);
5708
5709       remote_thr->last_resume_step = step;
5710       remote_thr->last_resume_sig = siggnal;
5711       return;
5712     }
5713
5714   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
5715      (explained in remote-notif.c:handle_notification) so
5716      remote_notif_process is not called.  We need find a place where
5717      it is safe to start a 'vNotif' sequence.  It is good to do it
5718      before resuming inferior, because inferior was stopped and no RSP
5719      traffic at that moment.  */
5720   if (!target_is_non_stop_p ())
5721     remote_notif_process (rs->notif_state, &notif_client_stop);
5722
5723   rs->last_resume_exec_dir = execution_direction;
5724
5725   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
5726   if (!remote_resume_with_vcont (ptid, step, siggnal))
5727     remote_resume_with_hc (ops, ptid, step, siggnal);
5728
5729   /* We are about to start executing the inferior, let's register it
5730      with the event loop.  NOTE: this is the one place where all the
5731      execution commands end up.  We could alternatively do this in each
5732      of the execution commands in infcmd.c.  */
5733   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
5734      into infcmd.c in order to allow inferior function calls to work
5735      NOT asynchronously.  */
5736   if (target_can_async_p ())
5737     target_async (1);
5738
5739   /* We've just told the target to resume.  The remote server will
5740      wait for the inferior to stop, and then send a stop reply.  In
5741      the mean time, we can't start another command/query ourselves
5742      because the stub wouldn't be ready to process it.  This applies
5743      only to the base all-stop protocol, however.  In non-stop (which
5744      only supports vCont), the stub replies with an "OK", and is
5745      immediate able to process further serial input.  */
5746   if (!target_is_non_stop_p ())
5747     rs->waiting_for_stop_reply = 1;
5748 }
5749
5750 static void check_pending_events_prevent_wildcard_vcont
5751   (int *may_global_wildcard_vcont);
5752 static int is_pending_fork_parent_thread (struct thread_info *thread);
5753
5754 /* Private per-inferior info for target remote processes.  */
5755
5756 struct remote_inferior : public private_inferior
5757 {
5758   /* Whether we can send a wildcard vCont for this process.  */
5759   bool may_wildcard_vcont = true;
5760 };
5761
5762 /* Get the remote private inferior data associated to INF.  */
5763
5764 static remote_inferior *
5765 get_remote_inferior (inferior *inf)
5766 {
5767   if (inf->priv == NULL)
5768     inf->priv.reset (new remote_inferior);
5769
5770   return static_cast<remote_inferior *> (inf->priv.get ());
5771 }
5772
5773 /* Structure used to track the construction of a vCont packet in the
5774    outgoing packet buffer.  This is used to send multiple vCont
5775    packets if we have more actions than would fit a single packet.  */
5776
5777 struct vcont_builder
5778 {
5779   /* Pointer to the first action.  P points here if no action has been
5780      appended yet.  */
5781   char *first_action;
5782
5783   /* Where the next action will be appended.  */
5784   char *p;
5785
5786   /* The end of the buffer.  Must never write past this.  */
5787   char *endp;
5788 };
5789
5790 /* Prepare the outgoing buffer for a new vCont packet.  */
5791
5792 static void
5793 vcont_builder_restart (struct vcont_builder *builder)
5794 {
5795   struct remote_state *rs = get_remote_state ();
5796
5797   builder->p = rs->buf;
5798   builder->endp = rs->buf + get_remote_packet_size ();
5799   builder->p += xsnprintf (builder->p, builder->endp - builder->p, "vCont");
5800   builder->first_action = builder->p;
5801 }
5802
5803 /* If the vCont packet being built has any action, send it to the
5804    remote end.  */
5805
5806 static void
5807 vcont_builder_flush (struct vcont_builder *builder)
5808 {
5809   struct remote_state *rs;
5810
5811   if (builder->p == builder->first_action)
5812     return;
5813
5814   rs = get_remote_state ();
5815   putpkt (rs->buf);
5816   getpkt (&rs->buf, &rs->buf_size, 0);
5817   if (strcmp (rs->buf, "OK") != 0)
5818     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
5819 }
5820
5821 /* The largest action is range-stepping, with its two addresses.  This
5822    is more than sufficient.  If a new, bigger action is created, it'll
5823    quickly trigger a failed assertion in append_resumption (and we'll
5824    just bump this).  */
5825 #define MAX_ACTION_SIZE 200
5826
5827 /* Append a new vCont action in the outgoing packet being built.  If
5828    the action doesn't fit the packet along with previous actions, push
5829    what we've got so far to the remote end and start over a new vCont
5830    packet (with the new action).  */
5831
5832 static void
5833 vcont_builder_push_action (struct vcont_builder *builder,
5834                            ptid_t ptid, int step, enum gdb_signal siggnal)
5835 {
5836   char buf[MAX_ACTION_SIZE + 1];
5837   char *endp;
5838   size_t rsize;
5839
5840   endp = append_resumption (buf, buf + sizeof (buf),
5841                             ptid, step, siggnal);
5842
5843   /* Check whether this new action would fit in the vCont packet along
5844      with previous actions.  If not, send what we've got so far and
5845      start a new vCont packet.  */
5846   rsize = endp - buf;
5847   if (rsize > builder->endp - builder->p)
5848     {
5849       vcont_builder_flush (builder);
5850       vcont_builder_restart (builder);
5851
5852       /* Should now fit.  */
5853       gdb_assert (rsize <= builder->endp - builder->p);
5854     }
5855
5856   memcpy (builder->p, buf, rsize);
5857   builder->p += rsize;
5858   *builder->p = '\0';
5859 }
5860
5861 /* to_commit_resume implementation.  */
5862
5863 static void
5864 remote_commit_resume (struct target_ops *ops)
5865 {
5866   struct inferior *inf;
5867   struct thread_info *tp;
5868   int any_process_wildcard;
5869   int may_global_wildcard_vcont;
5870   struct vcont_builder vcont_builder;
5871
5872   /* If connected in all-stop mode, we'd send the remote resume
5873      request directly from remote_resume.  Likewise if
5874      reverse-debugging, as there are no defined vCont actions for
5875      reverse execution.  */
5876   if (!target_is_non_stop_p () || execution_direction == EXEC_REVERSE)
5877     return;
5878
5879   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
5880      instead of resuming all threads of each process individually.
5881      However, if any thread of a process must remain halted, we can't
5882      send wildcard resumes and must send one action per thread.
5883
5884      Care must be taken to not resume threads/processes the server
5885      side already told us are stopped, but the core doesn't know about
5886      yet, because the events are still in the vStopped notification
5887      queue.  For example:
5888
5889        #1 => vCont s:p1.1;c
5890        #2 <= OK
5891        #3 <= %Stopped T05 p1.1
5892        #4 => vStopped
5893        #5 <= T05 p1.2
5894        #6 => vStopped
5895        #7 <= OK
5896        #8 (infrun handles the stop for p1.1 and continues stepping)
5897        #9 => vCont s:p1.1;c
5898
5899      The last vCont above would resume thread p1.2 by mistake, because
5900      the server has no idea that the event for p1.2 had not been
5901      handled yet.
5902
5903      The server side must similarly ignore resume actions for the
5904      thread that has a pending %Stopped notification (and any other
5905      threads with events pending), until GDB acks the notification
5906      with vStopped.  Otherwise, e.g., the following case is
5907      mishandled:
5908
5909        #1 => g  (or any other packet)
5910        #2 <= [registers]
5911        #3 <= %Stopped T05 p1.2
5912        #4 => vCont s:p1.1;c
5913        #5 <= OK
5914
5915      Above, the server must not resume thread p1.2.  GDB can't know
5916      that p1.2 stopped until it acks the %Stopped notification, and
5917      since from GDB's perspective all threads should be running, it
5918      sends a "c" action.
5919
5920      Finally, special care must also be given to handling fork/vfork
5921      events.  A (v)fork event actually tells us that two processes
5922      stopped -- the parent and the child.  Until we follow the fork,
5923      we must not resume the child.  Therefore, if we have a pending
5924      fork follow, we must not send a global wildcard resume action
5925      (vCont;c).  We can still send process-wide wildcards though.  */
5926
5927   /* Start by assuming a global wildcard (vCont;c) is possible.  */
5928   may_global_wildcard_vcont = 1;
5929
5930   /* And assume every process is individually wildcard-able too.  */
5931   ALL_NON_EXITED_INFERIORS (inf)
5932     {
5933       remote_inferior *priv = get_remote_inferior (inf);
5934
5935       priv->may_wildcard_vcont = true;
5936     }
5937
5938   /* Check for any pending events (not reported or processed yet) and
5939      disable process and global wildcard resumes appropriately.  */
5940   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
5941
5942   ALL_NON_EXITED_THREADS (tp)
5943     {
5944       /* If a thread of a process is not meant to be resumed, then we
5945          can't wildcard that process.  */
5946       if (!tp->executing)
5947         {
5948           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
5949
5950           /* And if we can't wildcard a process, we can't wildcard
5951              everything either.  */
5952           may_global_wildcard_vcont = 0;
5953           continue;
5954         }
5955
5956       /* If a thread is the parent of an unfollowed fork, then we
5957          can't do a global wildcard, as that would resume the fork
5958          child.  */
5959       if (is_pending_fork_parent_thread (tp))
5960         may_global_wildcard_vcont = 0;
5961     }
5962
5963   /* Now let's build the vCont packet(s).  Actions must be appended
5964      from narrower to wider scopes (thread -> process -> global).  If
5965      we end up with too many actions for a single packet vcont_builder
5966      flushes the current vCont packet to the remote side and starts a
5967      new one.  */
5968   vcont_builder_restart (&vcont_builder);
5969
5970   /* Threads first.  */
5971   ALL_NON_EXITED_THREADS (tp)
5972     {
5973       remote_thread_info *remote_thr = get_remote_thread_info (tp);
5974
5975       if (!tp->executing || remote_thr->vcont_resumed)
5976         continue;
5977
5978       gdb_assert (!thread_is_in_step_over_chain (tp));
5979
5980       if (!remote_thr->last_resume_step
5981           && remote_thr->last_resume_sig == GDB_SIGNAL_0
5982           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
5983         {
5984           /* We'll send a wildcard resume instead.  */
5985           remote_thr->vcont_resumed = 1;
5986           continue;
5987         }
5988
5989       vcont_builder_push_action (&vcont_builder, tp->ptid,
5990                                  remote_thr->last_resume_step,
5991                                  remote_thr->last_resume_sig);
5992       remote_thr->vcont_resumed = 1;
5993     }
5994
5995   /* Now check whether we can send any process-wide wildcard.  This is
5996      to avoid sending a global wildcard in the case nothing is
5997      supposed to be resumed.  */
5998   any_process_wildcard = 0;
5999
6000   ALL_NON_EXITED_INFERIORS (inf)
6001     {
6002       if (get_remote_inferior (inf)->may_wildcard_vcont)
6003         {
6004           any_process_wildcard = 1;
6005           break;
6006         }
6007     }
6008
6009   if (any_process_wildcard)
6010     {
6011       /* If all processes are wildcard-able, then send a single "c"
6012          action, otherwise, send an "all (-1) threads of process"
6013          continue action for each running process, if any.  */
6014       if (may_global_wildcard_vcont)
6015         {
6016           vcont_builder_push_action (&vcont_builder, minus_one_ptid,
6017                                      0, GDB_SIGNAL_0);
6018         }
6019       else
6020         {
6021           ALL_NON_EXITED_INFERIORS (inf)
6022             {
6023               if (get_remote_inferior (inf)->may_wildcard_vcont)
6024                 {
6025                   vcont_builder_push_action (&vcont_builder,
6026                                              pid_to_ptid (inf->pid),
6027                                              0, GDB_SIGNAL_0);
6028                 }
6029             }
6030         }
6031     }
6032
6033   vcont_builder_flush (&vcont_builder);
6034 }
6035
6036 \f
6037
6038 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6039    thread, all threads of a remote process, or all threads of all
6040    processes.  */
6041
6042 static void
6043 remote_stop_ns (ptid_t ptid)
6044 {
6045   struct remote_state *rs = get_remote_state ();
6046   char *p = rs->buf;
6047   char *endp = rs->buf + get_remote_packet_size ();
6048
6049   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6050     remote_vcont_probe (rs);
6051
6052   if (!rs->supports_vCont.t)
6053     error (_("Remote server does not support stopping threads"));
6054
6055   if (ptid_equal (ptid, minus_one_ptid)
6056       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6057     p += xsnprintf (p, endp - p, "vCont;t");
6058   else
6059     {
6060       ptid_t nptid;
6061
6062       p += xsnprintf (p, endp - p, "vCont;t:");
6063
6064       if (ptid_is_pid (ptid))
6065           /* All (-1) threads of process.  */
6066         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6067       else
6068         {
6069           /* Small optimization: if we already have a stop reply for
6070              this thread, no use in telling the stub we want this
6071              stopped.  */
6072           if (peek_stop_reply (ptid))
6073             return;
6074
6075           nptid = ptid;
6076         }
6077
6078       write_ptid (p, endp, nptid);
6079     }
6080
6081   /* In non-stop, we get an immediate OK reply.  The stop reply will
6082      come in asynchronously by notification.  */
6083   putpkt (rs->buf);
6084   getpkt (&rs->buf, &rs->buf_size, 0);
6085   if (strcmp (rs->buf, "OK") != 0)
6086     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6087 }
6088
6089 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6090    interrupt the remote target.  It is undefined which thread of which
6091    process reports the interrupt.  */
6092
6093 static void
6094 remote_interrupt_as (void)
6095 {
6096   struct remote_state *rs = get_remote_state ();
6097
6098   rs->ctrlc_pending_p = 1;
6099
6100   /* If the inferior is stopped already, but the core didn't know
6101      about it yet, just ignore the request.  The cached wait status
6102      will be collected in remote_wait.  */
6103   if (rs->cached_wait_status)
6104     return;
6105
6106   /* Send interrupt_sequence to remote target.  */
6107   send_interrupt_sequence ();
6108 }
6109
6110 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6111    the remote target.  It is undefined which thread of which process
6112    reports the interrupt.  Throws an error if the packet is not
6113    supported by the server.  */
6114
6115 static void
6116 remote_interrupt_ns (void)
6117 {
6118   struct remote_state *rs = get_remote_state ();
6119   char *p = rs->buf;
6120   char *endp = rs->buf + get_remote_packet_size ();
6121
6122   xsnprintf (p, endp - p, "vCtrlC");
6123
6124   /* In non-stop, we get an immediate OK reply.  The stop reply will
6125      come in asynchronously by notification.  */
6126   putpkt (rs->buf);
6127   getpkt (&rs->buf, &rs->buf_size, 0);
6128
6129   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6130     {
6131     case PACKET_OK:
6132       break;
6133     case PACKET_UNKNOWN:
6134       error (_("No support for interrupting the remote target."));
6135     case PACKET_ERROR:
6136       error (_("Interrupting target failed: %s"), rs->buf);
6137     }
6138 }
6139
6140 /* Implement the to_stop function for the remote targets.  */
6141
6142 static void
6143 remote_stop (struct target_ops *self, ptid_t ptid)
6144 {
6145   if (remote_debug)
6146     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6147
6148   if (target_is_non_stop_p ())
6149     remote_stop_ns (ptid);
6150   else
6151     {
6152       /* We don't currently have a way to transparently pause the
6153          remote target in all-stop mode.  Interrupt it instead.  */
6154       remote_interrupt_as ();
6155     }
6156 }
6157
6158 /* Implement the to_interrupt function for the remote targets.  */
6159
6160 static void
6161 remote_interrupt (struct target_ops *self)
6162 {
6163   if (remote_debug)
6164     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6165
6166   if (target_is_non_stop_p ())
6167     remote_interrupt_ns ();
6168   else
6169     remote_interrupt_as ();
6170 }
6171
6172 /* Implement the to_pass_ctrlc function for the remote targets.  */
6173
6174 static void
6175 remote_pass_ctrlc (struct target_ops *self)
6176 {
6177   struct remote_state *rs = get_remote_state ();
6178
6179   if (remote_debug)
6180     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6181
6182   /* If we're starting up, we're not fully synced yet.  Quit
6183      immediately.  */
6184   if (rs->starting_up)
6185     quit ();
6186   /* If ^C has already been sent once, offer to disconnect.  */
6187   else if (rs->ctrlc_pending_p)
6188     interrupt_query ();
6189   else
6190     target_interrupt ();
6191 }
6192
6193 /* Ask the user what to do when an interrupt is received.  */
6194
6195 static void
6196 interrupt_query (void)
6197 {
6198   struct remote_state *rs = get_remote_state ();
6199
6200   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6201     {
6202       if (query (_("The target is not responding to interrupt requests.\n"
6203                    "Stop debugging it? ")))
6204         {
6205           remote_unpush_target ();
6206           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6207         }
6208     }
6209   else
6210     {
6211       if (query (_("Interrupted while waiting for the program.\n"
6212                    "Give up waiting? ")))
6213         quit ();
6214     }
6215 }
6216
6217 /* Enable/disable target terminal ownership.  Most targets can use
6218    terminal groups to control terminal ownership.  Remote targets are
6219    different in that explicit transfer of ownership to/from GDB/target
6220    is required.  */
6221
6222 static void
6223 remote_terminal_inferior (struct target_ops *self)
6224 {
6225   /* NOTE: At this point we could also register our selves as the
6226      recipient of all input.  Any characters typed could then be
6227      passed on down to the target.  */
6228 }
6229
6230 static void
6231 remote_terminal_ours (struct target_ops *self)
6232 {
6233 }
6234
6235 static void
6236 remote_console_output (char *msg)
6237 {
6238   char *p;
6239
6240   for (p = msg; p[0] && p[1]; p += 2)
6241     {
6242       char tb[2];
6243       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6244
6245       tb[0] = c;
6246       tb[1] = 0;
6247       fputs_unfiltered (tb, gdb_stdtarg);
6248     }
6249   gdb_flush (gdb_stdtarg);
6250 }
6251
6252 DEF_VEC_O(cached_reg_t);
6253
6254 typedef struct stop_reply
6255 {
6256   struct notif_event base;
6257
6258   /* The identifier of the thread about this event  */
6259   ptid_t ptid;
6260
6261   /* The remote state this event is associated with.  When the remote
6262      connection, represented by a remote_state object, is closed,
6263      all the associated stop_reply events should be released.  */
6264   struct remote_state *rs;
6265
6266   struct target_waitstatus ws;
6267
6268   /* The architecture associated with the expedited registers.  */
6269   gdbarch *arch;
6270
6271   /* Expedited registers.  This makes remote debugging a bit more
6272      efficient for those targets that provide critical registers as
6273      part of their normal status mechanism (as another roundtrip to
6274      fetch them is avoided).  */
6275   VEC(cached_reg_t) *regcache;
6276
6277   enum target_stop_reason stop_reason;
6278
6279   CORE_ADDR watch_data_address;
6280
6281   int core;
6282 } *stop_reply_p;
6283
6284 DECLARE_QUEUE_P (stop_reply_p);
6285 DEFINE_QUEUE_P (stop_reply_p);
6286 /* The list of already fetched and acknowledged stop events.  This
6287    queue is used for notification Stop, and other notifications
6288    don't need queue for their events, because the notification events
6289    of Stop can't be consumed immediately, so that events should be
6290    queued first, and be consumed by remote_wait_{ns,as} one per
6291    time.  Other notifications can consume their events immediately,
6292    so queue is not needed for them.  */
6293 static QUEUE (stop_reply_p) *stop_reply_queue;
6294
6295 static void
6296 stop_reply_xfree (struct stop_reply *r)
6297 {
6298   notif_event_xfree ((struct notif_event *) r);
6299 }
6300
6301 /* Return the length of the stop reply queue.  */
6302
6303 static int
6304 stop_reply_queue_length (void)
6305 {
6306   return QUEUE_length (stop_reply_p, stop_reply_queue);
6307 }
6308
6309 static void
6310 remote_notif_stop_parse (struct notif_client *self, char *buf,
6311                          struct notif_event *event)
6312 {
6313   remote_parse_stop_reply (buf, (struct stop_reply *) event);
6314 }
6315
6316 static void
6317 remote_notif_stop_ack (struct notif_client *self, char *buf,
6318                        struct notif_event *event)
6319 {
6320   struct stop_reply *stop_reply = (struct stop_reply *) event;
6321
6322   /* acknowledge */
6323   putpkt (self->ack_command);
6324
6325   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6326       /* We got an unknown stop reply.  */
6327       error (_("Unknown stop reply"));
6328
6329   push_stop_reply (stop_reply);
6330 }
6331
6332 static int
6333 remote_notif_stop_can_get_pending_events (struct notif_client *self)
6334 {
6335   /* We can't get pending events in remote_notif_process for
6336      notification stop, and we have to do this in remote_wait_ns
6337      instead.  If we fetch all queued events from stub, remote stub
6338      may exit and we have no chance to process them back in
6339      remote_wait_ns.  */
6340   mark_async_event_handler (remote_async_inferior_event_token);
6341   return 0;
6342 }
6343
6344 static void
6345 stop_reply_dtr (struct notif_event *event)
6346 {
6347   struct stop_reply *r = (struct stop_reply *) event;
6348   cached_reg_t *reg;
6349   int ix;
6350
6351   for (ix = 0;
6352        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6353        ix++)
6354     xfree (reg->data);
6355
6356   VEC_free (cached_reg_t, r->regcache);
6357 }
6358
6359 static struct notif_event *
6360 remote_notif_stop_alloc_reply (void)
6361 {
6362   /* We cast to a pointer to the "base class".  */
6363   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6364
6365   r->dtr = stop_reply_dtr;
6366
6367   return r;
6368 }
6369
6370 /* A client of notification Stop.  */
6371
6372 struct notif_client notif_client_stop =
6373 {
6374   "Stop",
6375   "vStopped",
6376   remote_notif_stop_parse,
6377   remote_notif_stop_ack,
6378   remote_notif_stop_can_get_pending_events,
6379   remote_notif_stop_alloc_reply,
6380   REMOTE_NOTIF_STOP,
6381 };
6382
6383 /* A parameter to pass data in and out.  */
6384
6385 struct queue_iter_param
6386 {
6387   void *input;
6388   struct stop_reply *output;
6389 };
6390
6391 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6392    the pid of the process that owns the threads we want to check, or
6393    -1 if we want to check all threads.  */
6394
6395 static int
6396 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6397                         ptid_t thread_ptid)
6398 {
6399   if (ws->kind == TARGET_WAITKIND_FORKED
6400       || ws->kind == TARGET_WAITKIND_VFORKED)
6401     {
6402       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6403         return 1;
6404     }
6405
6406   return 0;
6407 }
6408
6409 /* Return the thread's pending status used to determine whether the
6410    thread is a fork parent stopped at a fork event.  */
6411
6412 static struct target_waitstatus *
6413 thread_pending_fork_status (struct thread_info *thread)
6414 {
6415   if (thread->suspend.waitstatus_pending_p)
6416     return &thread->suspend.waitstatus;
6417   else
6418     return &thread->pending_follow;
6419 }
6420
6421 /* Determine if THREAD is a pending fork parent thread.  */
6422
6423 static int
6424 is_pending_fork_parent_thread (struct thread_info *thread)
6425 {
6426   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6427   int pid = -1;
6428
6429   return is_pending_fork_parent (ws, pid, thread->ptid);
6430 }
6431
6432 /* Check whether EVENT is a fork event, and if it is, remove the
6433    fork child from the context list passed in DATA.  */
6434
6435 static int
6436 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6437                               QUEUE_ITER (stop_reply_p) *iter,
6438                               stop_reply_p event,
6439                               void *data)
6440 {
6441   struct queue_iter_param *param = (struct queue_iter_param *) data;
6442   struct threads_listing_context *context
6443     = (struct threads_listing_context *) param->input;
6444
6445   if (event->ws.kind == TARGET_WAITKIND_FORKED
6446       || event->ws.kind == TARGET_WAITKIND_VFORKED
6447       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6448     context->remove_thread (event->ws.value.related_pid);
6449
6450   return 1;
6451 }
6452
6453 /* If CONTEXT contains any fork child threads that have not been
6454    reported yet, remove them from the CONTEXT list.  If such a
6455    thread exists it is because we are stopped at a fork catchpoint
6456    and have not yet called follow_fork, which will set up the
6457    host-side data structures for the new process.  */
6458
6459 static void
6460 remove_new_fork_children (struct threads_listing_context *context)
6461 {
6462   struct thread_info * thread;
6463   int pid = -1;
6464   struct notif_client *notif = &notif_client_stop;
6465   struct queue_iter_param param;
6466
6467   /* For any threads stopped at a fork event, remove the corresponding
6468      fork child threads from the CONTEXT list.  */
6469   ALL_NON_EXITED_THREADS (thread)
6470     {
6471       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6472
6473       if (is_pending_fork_parent (ws, pid, thread->ptid))
6474         context->remove_thread (ws->value.related_pid);
6475     }
6476
6477   /* Check for any pending fork events (not reported or processed yet)
6478      in process PID and remove those fork child threads from the
6479      CONTEXT list as well.  */
6480   remote_notif_get_pending_events (notif);
6481   param.input = context;
6482   param.output = NULL;
6483   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6484                  remove_child_of_pending_fork, &param);
6485 }
6486
6487 /* Check whether EVENT would prevent a global or process wildcard
6488    vCont action.  */
6489
6490 static int
6491 check_pending_event_prevents_wildcard_vcont_callback
6492   (QUEUE (stop_reply_p) *q,
6493    QUEUE_ITER (stop_reply_p) *iter,
6494    stop_reply_p event,
6495    void *data)
6496 {
6497   struct inferior *inf;
6498   int *may_global_wildcard_vcont = (int *) data;
6499
6500   if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
6501       || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
6502     return 1;
6503
6504   if (event->ws.kind == TARGET_WAITKIND_FORKED
6505       || event->ws.kind == TARGET_WAITKIND_VFORKED)
6506     *may_global_wildcard_vcont = 0;
6507
6508   inf = find_inferior_ptid (event->ptid);
6509
6510   /* This may be the first time we heard about this process.
6511      Regardless, we must not do a global wildcard resume, otherwise
6512      we'd resume this process too.  */
6513   *may_global_wildcard_vcont = 0;
6514   if (inf != NULL)
6515     get_remote_inferior (inf)->may_wildcard_vcont = false;
6516
6517   return 1;
6518 }
6519
6520 /* Check whether any event pending in the vStopped queue would prevent
6521    a global or process wildcard vCont action.  Clear
6522    *may_global_wildcard if we can't do a global wildcard (vCont;c),
6523    and clear the event inferior's may_wildcard_vcont flag if we can't
6524    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
6525
6526 static void
6527 check_pending_events_prevent_wildcard_vcont (int *may_global_wildcard)
6528 {
6529   struct notif_client *notif = &notif_client_stop;
6530
6531   remote_notif_get_pending_events (notif);
6532   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6533                  check_pending_event_prevents_wildcard_vcont_callback,
6534                  may_global_wildcard);
6535 }
6536
6537 /* Remove stop replies in the queue if its pid is equal to the given
6538    inferior's pid.  */
6539
6540 static int
6541 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
6542                                 QUEUE_ITER (stop_reply_p) *iter,
6543                                 stop_reply_p event,
6544                                 void *data)
6545 {
6546   struct queue_iter_param *param = (struct queue_iter_param *) data;
6547   struct inferior *inf = (struct inferior *) param->input;
6548
6549   if (ptid_get_pid (event->ptid) == inf->pid)
6550     {
6551       stop_reply_xfree (event);
6552       QUEUE_remove_elem (stop_reply_p, q, iter);
6553     }
6554
6555   return 1;
6556 }
6557
6558 /* Discard all pending stop replies of inferior INF.  */
6559
6560 static void
6561 discard_pending_stop_replies (struct inferior *inf)
6562 {
6563   struct queue_iter_param param;
6564   struct stop_reply *reply;
6565   struct remote_state *rs = get_remote_state ();
6566   struct remote_notif_state *rns = rs->notif_state;
6567
6568   /* This function can be notified when an inferior exists.  When the
6569      target is not remote, the notification state is NULL.  */
6570   if (rs->remote_desc == NULL)
6571     return;
6572
6573   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
6574
6575   /* Discard the in-flight notification.  */
6576   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
6577     {
6578       stop_reply_xfree (reply);
6579       rns->pending_event[notif_client_stop.id] = NULL;
6580     }
6581
6582   param.input = inf;
6583   param.output = NULL;
6584   /* Discard the stop replies we have already pulled with
6585      vStopped.  */
6586   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6587                  remove_stop_reply_for_inferior, &param);
6588 }
6589
6590 /* If its remote state is equal to the given remote state,
6591    remove EVENT from the stop reply queue.  */
6592
6593 static int
6594 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
6595                                    QUEUE_ITER (stop_reply_p) *iter,
6596                                    stop_reply_p event,
6597                                    void *data)
6598 {
6599   struct queue_iter_param *param = (struct queue_iter_param *) data;
6600   struct remote_state *rs = (struct remote_state *) param->input;
6601
6602   if (event->rs == rs)
6603     {
6604       stop_reply_xfree (event);
6605       QUEUE_remove_elem (stop_reply_p, q, iter);
6606     }
6607
6608   return 1;
6609 }
6610
6611 /* Discard the stop replies for RS in stop_reply_queue.  */
6612
6613 static void
6614 discard_pending_stop_replies_in_queue (struct remote_state *rs)
6615 {
6616   struct queue_iter_param param;
6617
6618   param.input = rs;
6619   param.output = NULL;
6620   /* Discard the stop replies we have already pulled with
6621      vStopped.  */
6622   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6623                  remove_stop_reply_of_remote_state, &param);
6624 }
6625
6626 /* A parameter to pass data in and out.  */
6627
6628 static int
6629 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
6630                                    QUEUE_ITER (stop_reply_p) *iter,
6631                                    stop_reply_p event,
6632                                    void *data)
6633 {
6634   struct queue_iter_param *param = (struct queue_iter_param *) data;
6635   ptid_t *ptid = (ptid_t *) param->input;
6636
6637   if (ptid_match (event->ptid, *ptid))
6638     {
6639       param->output = event;
6640       QUEUE_remove_elem (stop_reply_p, q, iter);
6641       return 0;
6642     }
6643
6644   return 1;
6645 }
6646
6647 /* Remove the first reply in 'stop_reply_queue' which matches
6648    PTID.  */
6649
6650 static struct stop_reply *
6651 remote_notif_remove_queued_reply (ptid_t ptid)
6652 {
6653   struct queue_iter_param param;
6654
6655   param.input = &ptid;
6656   param.output = NULL;
6657
6658   QUEUE_iterate (stop_reply_p, stop_reply_queue,
6659                  remote_notif_remove_once_on_match, &param);
6660   if (notif_debug)
6661     fprintf_unfiltered (gdb_stdlog,
6662                         "notif: discard queued event: 'Stop' in %s\n",
6663                         target_pid_to_str (ptid));
6664
6665   return param.output;
6666 }
6667
6668 /* Look for a queued stop reply belonging to PTID.  If one is found,
6669    remove it from the queue, and return it.  Returns NULL if none is
6670    found.  If there are still queued events left to process, tell the
6671    event loop to get back to target_wait soon.  */
6672
6673 static struct stop_reply *
6674 queued_stop_reply (ptid_t ptid)
6675 {
6676   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
6677
6678   if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
6679     /* There's still at least an event left.  */
6680     mark_async_event_handler (remote_async_inferior_event_token);
6681
6682   return r;
6683 }
6684
6685 /* Push a fully parsed stop reply in the stop reply queue.  Since we
6686    know that we now have at least one queued event left to pass to the
6687    core side, tell the event loop to get back to target_wait soon.  */
6688
6689 static void
6690 push_stop_reply (struct stop_reply *new_event)
6691 {
6692   QUEUE_enque (stop_reply_p, stop_reply_queue, new_event);
6693
6694   if (notif_debug)
6695     fprintf_unfiltered (gdb_stdlog,
6696                         "notif: push 'Stop' %s to queue %d\n",
6697                         target_pid_to_str (new_event->ptid),
6698                         QUEUE_length (stop_reply_p,
6699                                       stop_reply_queue));
6700
6701   mark_async_event_handler (remote_async_inferior_event_token);
6702 }
6703
6704 static int
6705 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
6706                               QUEUE_ITER (stop_reply_p) *iter,
6707                               struct stop_reply *event,
6708                               void *data)
6709 {
6710   ptid_t *ptid = (ptid_t *) data;
6711
6712   return !(ptid_equal (*ptid, event->ptid)
6713            && event->ws.kind == TARGET_WAITKIND_STOPPED);
6714 }
6715
6716 /* Returns true if we have a stop reply for PTID.  */
6717
6718 static int
6719 peek_stop_reply (ptid_t ptid)
6720 {
6721   return !QUEUE_iterate (stop_reply_p, stop_reply_queue,
6722                          stop_reply_match_ptid_and_ws, &ptid);
6723 }
6724
6725 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
6726    starting with P and ending with PEND matches PREFIX.  */
6727
6728 static int
6729 strprefix (const char *p, const char *pend, const char *prefix)
6730 {
6731   for ( ; p < pend; p++, prefix++)
6732     if (*p != *prefix)
6733       return 0;
6734   return *prefix == '\0';
6735 }
6736
6737 /* Parse the stop reply in BUF.  Either the function succeeds, and the
6738    result is stored in EVENT, or throws an error.  */
6739
6740 static void
6741 remote_parse_stop_reply (char *buf, struct stop_reply *event)
6742 {
6743   remote_arch_state *rsa = NULL;
6744   ULONGEST addr;
6745   const char *p;
6746   int skipregs = 0;
6747
6748   event->ptid = null_ptid;
6749   event->rs = get_remote_state ();
6750   event->ws.kind = TARGET_WAITKIND_IGNORE;
6751   event->ws.value.integer = 0;
6752   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6753   event->regcache = NULL;
6754   event->core = -1;
6755
6756   switch (buf[0])
6757     {
6758     case 'T':           /* Status with PC, SP, FP, ...  */
6759       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
6760       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
6761             ss = signal number
6762             n... = register number
6763             r... = register contents
6764       */
6765
6766       p = &buf[3];      /* after Txx */
6767       while (*p)
6768         {
6769           const char *p1;
6770           int fieldsize;
6771
6772           p1 = strchr (p, ':');
6773           if (p1 == NULL)
6774             error (_("Malformed packet(a) (missing colon): %s\n\
6775 Packet: '%s'\n"),
6776                    p, buf);
6777           if (p == p1)
6778             error (_("Malformed packet(a) (missing register number): %s\n\
6779 Packet: '%s'\n"),
6780                    p, buf);
6781
6782           /* Some "registers" are actually extended stop information.
6783              Note if you're adding a new entry here: GDB 7.9 and
6784              earlier assume that all register "numbers" that start
6785              with an hex digit are real register numbers.  Make sure
6786              the server only sends such a packet if it knows the
6787              client understands it.  */
6788
6789           if (strprefix (p, p1, "thread"))
6790             event->ptid = read_ptid (++p1, &p);
6791           else if (strprefix (p, p1, "syscall_entry"))
6792             {
6793               ULONGEST sysno;
6794
6795               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
6796               p = unpack_varlen_hex (++p1, &sysno);
6797               event->ws.value.syscall_number = (int) sysno;
6798             }
6799           else if (strprefix (p, p1, "syscall_return"))
6800             {
6801               ULONGEST sysno;
6802
6803               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
6804               p = unpack_varlen_hex (++p1, &sysno);
6805               event->ws.value.syscall_number = (int) sysno;
6806             }
6807           else if (strprefix (p, p1, "watch")
6808                    || strprefix (p, p1, "rwatch")
6809                    || strprefix (p, p1, "awatch"))
6810             {
6811               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
6812               p = unpack_varlen_hex (++p1, &addr);
6813               event->watch_data_address = (CORE_ADDR) addr;
6814             }
6815           else if (strprefix (p, p1, "swbreak"))
6816             {
6817               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
6818
6819               /* Make sure the stub doesn't forget to indicate support
6820                  with qSupported.  */
6821               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
6822                 error (_("Unexpected swbreak stop reason"));
6823
6824               /* The value part is documented as "must be empty",
6825                  though we ignore it, in case we ever decide to make
6826                  use of it in a backward compatible way.  */
6827               p = strchrnul (p1 + 1, ';');
6828             }
6829           else if (strprefix (p, p1, "hwbreak"))
6830             {
6831               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
6832
6833               /* Make sure the stub doesn't forget to indicate support
6834                  with qSupported.  */
6835               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
6836                 error (_("Unexpected hwbreak stop reason"));
6837
6838               /* See above.  */
6839               p = strchrnul (p1 + 1, ';');
6840             }
6841           else if (strprefix (p, p1, "library"))
6842             {
6843               event->ws.kind = TARGET_WAITKIND_LOADED;
6844               p = strchrnul (p1 + 1, ';');
6845             }
6846           else if (strprefix (p, p1, "replaylog"))
6847             {
6848               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
6849               /* p1 will indicate "begin" or "end", but it makes
6850                  no difference for now, so ignore it.  */
6851               p = strchrnul (p1 + 1, ';');
6852             }
6853           else if (strprefix (p, p1, "core"))
6854             {
6855               ULONGEST c;
6856
6857               p = unpack_varlen_hex (++p1, &c);
6858               event->core = c;
6859             }
6860           else if (strprefix (p, p1, "fork"))
6861             {
6862               event->ws.value.related_pid = read_ptid (++p1, &p);
6863               event->ws.kind = TARGET_WAITKIND_FORKED;
6864             }
6865           else if (strprefix (p, p1, "vfork"))
6866             {
6867               event->ws.value.related_pid = read_ptid (++p1, &p);
6868               event->ws.kind = TARGET_WAITKIND_VFORKED;
6869             }
6870           else if (strprefix (p, p1, "vforkdone"))
6871             {
6872               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
6873               p = strchrnul (p1 + 1, ';');
6874             }
6875           else if (strprefix (p, p1, "exec"))
6876             {
6877               ULONGEST ignored;
6878               char pathname[PATH_MAX];
6879               int pathlen;
6880
6881               /* Determine the length of the execd pathname.  */
6882               p = unpack_varlen_hex (++p1, &ignored);
6883               pathlen = (p - p1) / 2;
6884
6885               /* Save the pathname for event reporting and for
6886                  the next run command.  */
6887               hex2bin (p1, (gdb_byte *) pathname, pathlen);
6888               pathname[pathlen] = '\0';
6889
6890               /* This is freed during event handling.  */
6891               event->ws.value.execd_pathname = xstrdup (pathname);
6892               event->ws.kind = TARGET_WAITKIND_EXECD;
6893
6894               /* Skip the registers included in this packet, since
6895                  they may be for an architecture different from the
6896                  one used by the original program.  */
6897               skipregs = 1;
6898             }
6899           else if (strprefix (p, p1, "create"))
6900             {
6901               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
6902               p = strchrnul (p1 + 1, ';');
6903             }
6904           else
6905             {
6906               ULONGEST pnum;
6907               const char *p_temp;
6908
6909               if (skipregs)
6910                 {
6911                   p = strchrnul (p1 + 1, ';');
6912                   p++;
6913                   continue;
6914                 }
6915
6916               /* Maybe a real ``P'' register number.  */
6917               p_temp = unpack_varlen_hex (p, &pnum);
6918               /* If the first invalid character is the colon, we got a
6919                  register number.  Otherwise, it's an unknown stop
6920                  reason.  */
6921               if (p_temp == p1)
6922                 {
6923                   /* If we haven't parsed the event's thread yet, find
6924                      it now, in order to find the architecture of the
6925                      reported expedited registers.  */
6926                   if (event->ptid == null_ptid)
6927                     {
6928                       const char *thr = strstr (p1 + 1, ";thread:");
6929                       if (thr != NULL)
6930                         event->ptid = read_ptid (thr + strlen (";thread:"),
6931                                                  NULL);
6932                       else
6933                         {
6934                           /* Either the current thread hasn't changed,
6935                              or the inferior is not multi-threaded.
6936                              The event must be for the thread we last
6937                              set as (or learned as being) current.  */
6938                           event->ptid = event->rs->general_thread;
6939                         }
6940                     }
6941
6942                   if (rsa == NULL)
6943                     {
6944                       inferior *inf = (event->ptid == null_ptid
6945                                        ? NULL
6946                                        : find_inferior_ptid (event->ptid));
6947                       /* If this is the first time we learn anything
6948                          about this process, skip the registers
6949                          included in this packet, since we don't yet
6950                          know which architecture to use to parse them.
6951                          We'll determine the architecture later when
6952                          we process the stop reply and retrieve the
6953                          target description, via
6954                          remote_notice_new_inferior ->
6955                          post_create_inferior.  */
6956                       if (inf == NULL)
6957                         {
6958                           p = strchrnul (p1 + 1, ';');
6959                           p++;
6960                           continue;
6961                         }
6962
6963                       event->arch = inf->gdbarch;
6964                       rsa = get_remote_arch_state (event->arch);
6965                     }
6966
6967                   packet_reg *reg
6968                     = packet_reg_from_pnum (event->arch, rsa, pnum);
6969                   cached_reg_t cached_reg;
6970
6971                   if (reg == NULL)
6972                     error (_("Remote sent bad register number %s: %s\n\
6973 Packet: '%s'\n"),
6974                            hex_string (pnum), p, buf);
6975
6976                   cached_reg.num = reg->regnum;
6977                   cached_reg.data = (gdb_byte *)
6978                     xmalloc (register_size (event->arch, reg->regnum));
6979
6980                   p = p1 + 1;
6981                   fieldsize = hex2bin (p, cached_reg.data,
6982                                        register_size (event->arch, reg->regnum));
6983                   p += 2 * fieldsize;
6984                   if (fieldsize < register_size (event->arch, reg->regnum))
6985                     warning (_("Remote reply is too short: %s"), buf);
6986
6987                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
6988                 }
6989               else
6990                 {
6991                   /* Not a number.  Silently skip unknown optional
6992                      info.  */
6993                   p = strchrnul (p1 + 1, ';');
6994                 }
6995             }
6996
6997           if (*p != ';')
6998             error (_("Remote register badly formatted: %s\nhere: %s"),
6999                    buf, p);
7000           ++p;
7001         }
7002
7003       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7004         break;
7005
7006       /* fall through */
7007     case 'S':           /* Old style status, just signal only.  */
7008       {
7009         int sig;
7010
7011         event->ws.kind = TARGET_WAITKIND_STOPPED;
7012         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7013         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7014           event->ws.value.sig = (enum gdb_signal) sig;
7015         else
7016           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7017       }
7018       break;
7019     case 'w':           /* Thread exited.  */
7020       {
7021         const char *p;
7022         ULONGEST value;
7023
7024         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7025         p = unpack_varlen_hex (&buf[1], &value);
7026         event->ws.value.integer = value;
7027         if (*p != ';')
7028           error (_("stop reply packet badly formatted: %s"), buf);
7029         event->ptid = read_ptid (++p, NULL);
7030         break;
7031       }
7032     case 'W':           /* Target exited.  */
7033     case 'X':
7034       {
7035         const char *p;
7036         int pid;
7037         ULONGEST value;
7038
7039         /* GDB used to accept only 2 hex chars here.  Stubs should
7040            only send more if they detect GDB supports multi-process
7041            support.  */
7042         p = unpack_varlen_hex (&buf[1], &value);
7043
7044         if (buf[0] == 'W')
7045           {
7046             /* The remote process exited.  */
7047             event->ws.kind = TARGET_WAITKIND_EXITED;
7048             event->ws.value.integer = value;
7049           }
7050         else
7051           {
7052             /* The remote process exited with a signal.  */
7053             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7054             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7055               event->ws.value.sig = (enum gdb_signal) value;
7056             else
7057               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7058           }
7059
7060         /* If no process is specified, assume inferior_ptid.  */
7061         pid = ptid_get_pid (inferior_ptid);
7062         if (*p == '\0')
7063           ;
7064         else if (*p == ';')
7065           {
7066             p++;
7067
7068             if (*p == '\0')
7069               ;
7070             else if (startswith (p, "process:"))
7071               {
7072                 ULONGEST upid;
7073
7074                 p += sizeof ("process:") - 1;
7075                 unpack_varlen_hex (p, &upid);
7076                 pid = upid;
7077               }
7078             else
7079               error (_("unknown stop reply packet: %s"), buf);
7080           }
7081         else
7082           error (_("unknown stop reply packet: %s"), buf);
7083         event->ptid = pid_to_ptid (pid);
7084       }
7085       break;
7086     case 'N':
7087       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7088       event->ptid = minus_one_ptid;
7089       break;
7090     }
7091
7092   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7093     error (_("No process or thread specified in stop reply: %s"), buf);
7094 }
7095
7096 /* When the stub wants to tell GDB about a new notification reply, it
7097    sends a notification (%Stop, for example).  Those can come it at
7098    any time, hence, we have to make sure that any pending
7099    putpkt/getpkt sequence we're making is finished, before querying
7100    the stub for more events with the corresponding ack command
7101    (vStopped, for example).  E.g., if we started a vStopped sequence
7102    immediately upon receiving the notification, something like this
7103    could happen:
7104
7105     1.1) --> Hg 1
7106     1.2) <-- OK
7107     1.3) --> g
7108     1.4) <-- %Stop
7109     1.5) --> vStopped
7110     1.6) <-- (registers reply to step #1.3)
7111
7112    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7113    query.
7114
7115    To solve this, whenever we parse a %Stop notification successfully,
7116    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7117    doing whatever we were doing:
7118
7119     2.1) --> Hg 1
7120     2.2) <-- OK
7121     2.3) --> g
7122     2.4) <-- %Stop
7123       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7124     2.5) <-- (registers reply to step #2.3)
7125
7126    Eventualy after step #2.5, we return to the event loop, which
7127    notices there's an event on the
7128    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7129    associated callback --- the function below.  At this point, we're
7130    always safe to start a vStopped sequence. :
7131
7132     2.6) --> vStopped
7133     2.7) <-- T05 thread:2
7134     2.8) --> vStopped
7135     2.9) --> OK
7136 */
7137
7138 void
7139 remote_notif_get_pending_events (struct notif_client *nc)
7140 {
7141   struct remote_state *rs = get_remote_state ();
7142
7143   if (rs->notif_state->pending_event[nc->id] != NULL)
7144     {
7145       if (notif_debug)
7146         fprintf_unfiltered (gdb_stdlog,
7147                             "notif: process: '%s' ack pending event\n",
7148                             nc->name);
7149
7150       /* acknowledge */
7151       nc->ack (nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7152       rs->notif_state->pending_event[nc->id] = NULL;
7153
7154       while (1)
7155         {
7156           getpkt (&rs->buf, &rs->buf_size, 0);
7157           if (strcmp (rs->buf, "OK") == 0)
7158             break;
7159           else
7160             remote_notif_ack (nc, rs->buf);
7161         }
7162     }
7163   else
7164     {
7165       if (notif_debug)
7166         fprintf_unfiltered (gdb_stdlog,
7167                             "notif: process: '%s' no pending reply\n",
7168                             nc->name);
7169     }
7170 }
7171
7172 /* Called when it is decided that STOP_REPLY holds the info of the
7173    event that is to be returned to the core.  This function always
7174    destroys STOP_REPLY.  */
7175
7176 static ptid_t
7177 process_stop_reply (struct stop_reply *stop_reply,
7178                     struct target_waitstatus *status)
7179 {
7180   ptid_t ptid;
7181
7182   *status = stop_reply->ws;
7183   ptid = stop_reply->ptid;
7184
7185   /* If no thread/process was reported by the stub, assume the current
7186      inferior.  */
7187   if (ptid_equal (ptid, null_ptid))
7188     ptid = inferior_ptid;
7189
7190   if (status->kind != TARGET_WAITKIND_EXITED
7191       && status->kind != TARGET_WAITKIND_SIGNALLED
7192       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7193     {
7194       /* Expedited registers.  */
7195       if (stop_reply->regcache)
7196         {
7197           struct regcache *regcache
7198             = get_thread_arch_regcache (ptid, stop_reply->arch);
7199           cached_reg_t *reg;
7200           int ix;
7201
7202           for (ix = 0;
7203                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7204                ix++)
7205           {
7206             regcache_raw_supply (regcache, reg->num, reg->data);
7207             xfree (reg->data);
7208           }
7209
7210           VEC_free (cached_reg_t, stop_reply->regcache);
7211         }
7212
7213       remote_notice_new_inferior (ptid, 0);
7214       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7215       remote_thr->core = stop_reply->core;
7216       remote_thr->stop_reason = stop_reply->stop_reason;
7217       remote_thr->watch_data_address = stop_reply->watch_data_address;
7218       remote_thr->vcont_resumed = 0;
7219     }
7220
7221   stop_reply_xfree (stop_reply);
7222   return ptid;
7223 }
7224
7225 /* The non-stop mode version of target_wait.  */
7226
7227 static ptid_t
7228 remote_wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7229 {
7230   struct remote_state *rs = get_remote_state ();
7231   struct stop_reply *stop_reply;
7232   int ret;
7233   int is_notif = 0;
7234
7235   /* If in non-stop mode, get out of getpkt even if a
7236      notification is received.  */
7237
7238   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7239                               0 /* forever */, &is_notif);
7240   while (1)
7241     {
7242       if (ret != -1 && !is_notif)
7243         switch (rs->buf[0])
7244           {
7245           case 'E':             /* Error of some sort.  */
7246             /* We're out of sync with the target now.  Did it continue
7247                or not?  We can't tell which thread it was in non-stop,
7248                so just ignore this.  */
7249             warning (_("Remote failure reply: %s"), rs->buf);
7250             break;
7251           case 'O':             /* Console output.  */
7252             remote_console_output (rs->buf + 1);
7253             break;
7254           default:
7255             warning (_("Invalid remote reply: %s"), rs->buf);
7256             break;
7257           }
7258
7259       /* Acknowledge a pending stop reply that may have arrived in the
7260          mean time.  */
7261       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7262         remote_notif_get_pending_events (&notif_client_stop);
7263
7264       /* If indeed we noticed a stop reply, we're done.  */
7265       stop_reply = queued_stop_reply (ptid);
7266       if (stop_reply != NULL)
7267         return process_stop_reply (stop_reply, status);
7268
7269       /* Still no event.  If we're just polling for an event, then
7270          return to the event loop.  */
7271       if (options & TARGET_WNOHANG)
7272         {
7273           status->kind = TARGET_WAITKIND_IGNORE;
7274           return minus_one_ptid;
7275         }
7276
7277       /* Otherwise do a blocking wait.  */
7278       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7279                                   1 /* forever */, &is_notif);
7280     }
7281 }
7282
7283 /* Wait until the remote machine stops, then return, storing status in
7284    STATUS just as `wait' would.  */
7285
7286 static ptid_t
7287 remote_wait_as (ptid_t ptid, struct target_waitstatus *status, int options)
7288 {
7289   struct remote_state *rs = get_remote_state ();
7290   ptid_t event_ptid = null_ptid;
7291   char *buf;
7292   struct stop_reply *stop_reply;
7293
7294  again:
7295
7296   status->kind = TARGET_WAITKIND_IGNORE;
7297   status->value.integer = 0;
7298
7299   stop_reply = queued_stop_reply (ptid);
7300   if (stop_reply != NULL)
7301     return process_stop_reply (stop_reply, status);
7302
7303   if (rs->cached_wait_status)
7304     /* Use the cached wait status, but only once.  */
7305     rs->cached_wait_status = 0;
7306   else
7307     {
7308       int ret;
7309       int is_notif;
7310       int forever = ((options & TARGET_WNOHANG) == 0
7311                      && wait_forever_enabled_p);
7312
7313       if (!rs->waiting_for_stop_reply)
7314         {
7315           status->kind = TARGET_WAITKIND_NO_RESUMED;
7316           return minus_one_ptid;
7317         }
7318
7319       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7320          _never_ wait for ever -> test on target_is_async_p().
7321          However, before we do that we need to ensure that the caller
7322          knows how to take the target into/out of async mode.  */
7323       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7324                                   forever, &is_notif);
7325
7326       /* GDB gets a notification.  Return to core as this event is
7327          not interesting.  */
7328       if (ret != -1 && is_notif)
7329         return minus_one_ptid;
7330
7331       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7332         return minus_one_ptid;
7333     }
7334
7335   buf = rs->buf;
7336
7337   /* Assume that the target has acknowledged Ctrl-C unless we receive
7338      an 'F' or 'O' packet.  */
7339   if (buf[0] != 'F' && buf[0] != 'O')
7340     rs->ctrlc_pending_p = 0;
7341
7342   switch (buf[0])
7343     {
7344     case 'E':           /* Error of some sort.  */
7345       /* We're out of sync with the target now.  Did it continue or
7346          not?  Not is more likely, so report a stop.  */
7347       rs->waiting_for_stop_reply = 0;
7348
7349       warning (_("Remote failure reply: %s"), buf);
7350       status->kind = TARGET_WAITKIND_STOPPED;
7351       status->value.sig = GDB_SIGNAL_0;
7352       break;
7353     case 'F':           /* File-I/O request.  */
7354       /* GDB may access the inferior memory while handling the File-I/O
7355          request, but we don't want GDB accessing memory while waiting
7356          for a stop reply.  See the comments in putpkt_binary.  Set
7357          waiting_for_stop_reply to 0 temporarily.  */
7358       rs->waiting_for_stop_reply = 0;
7359       remote_fileio_request (buf, rs->ctrlc_pending_p);
7360       rs->ctrlc_pending_p = 0;
7361       /* GDB handled the File-I/O request, and the target is running
7362          again.  Keep waiting for events.  */
7363       rs->waiting_for_stop_reply = 1;
7364       break;
7365     case 'N': case 'T': case 'S': case 'X': case 'W':
7366       {
7367         struct stop_reply *stop_reply;
7368
7369         /* There is a stop reply to handle.  */
7370         rs->waiting_for_stop_reply = 0;
7371
7372         stop_reply
7373           = (struct stop_reply *) remote_notif_parse (&notif_client_stop,
7374                                                       rs->buf);
7375
7376         event_ptid = process_stop_reply (stop_reply, status);
7377         break;
7378       }
7379     case 'O':           /* Console output.  */
7380       remote_console_output (buf + 1);
7381       break;
7382     case '\0':
7383       if (rs->last_sent_signal != GDB_SIGNAL_0)
7384         {
7385           /* Zero length reply means that we tried 'S' or 'C' and the
7386              remote system doesn't support it.  */
7387           target_terminal::ours_for_output ();
7388           printf_filtered
7389             ("Can't send signals to this remote system.  %s not sent.\n",
7390              gdb_signal_to_name (rs->last_sent_signal));
7391           rs->last_sent_signal = GDB_SIGNAL_0;
7392           target_terminal::inferior ();
7393
7394           strcpy (buf, rs->last_sent_step ? "s" : "c");
7395           putpkt (buf);
7396           break;
7397         }
7398       /* else fallthrough */
7399     default:
7400       warning (_("Invalid remote reply: %s"), buf);
7401       break;
7402     }
7403
7404   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7405     return minus_one_ptid;
7406   else if (status->kind == TARGET_WAITKIND_IGNORE)
7407     {
7408       /* Nothing interesting happened.  If we're doing a non-blocking
7409          poll, we're done.  Otherwise, go back to waiting.  */
7410       if (options & TARGET_WNOHANG)
7411         return minus_one_ptid;
7412       else
7413         goto again;
7414     }
7415   else if (status->kind != TARGET_WAITKIND_EXITED
7416            && status->kind != TARGET_WAITKIND_SIGNALLED)
7417     {
7418       if (!ptid_equal (event_ptid, null_ptid))
7419         record_currthread (rs, event_ptid);
7420       else
7421         event_ptid = inferior_ptid;
7422     }
7423   else
7424     /* A process exit.  Invalidate our notion of current thread.  */
7425     record_currthread (rs, minus_one_ptid);
7426
7427   return event_ptid;
7428 }
7429
7430 /* Wait until the remote machine stops, then return, storing status in
7431    STATUS just as `wait' would.  */
7432
7433 static ptid_t
7434 remote_wait (struct target_ops *ops,
7435              ptid_t ptid, struct target_waitstatus *status, int options)
7436 {
7437   ptid_t event_ptid;
7438
7439   if (target_is_non_stop_p ())
7440     event_ptid = remote_wait_ns (ptid, status, options);
7441   else
7442     event_ptid = remote_wait_as (ptid, status, options);
7443
7444   if (target_is_async_p ())
7445     {
7446       /* If there are are events left in the queue tell the event loop
7447          to return here.  */
7448       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
7449         mark_async_event_handler (remote_async_inferior_event_token);
7450     }
7451
7452   return event_ptid;
7453 }
7454
7455 /* Fetch a single register using a 'p' packet.  */
7456
7457 static int
7458 fetch_register_using_p (struct regcache *regcache, struct packet_reg *reg)
7459 {
7460   struct gdbarch *gdbarch = regcache->arch ();
7461   struct remote_state *rs = get_remote_state ();
7462   char *buf, *p;
7463   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7464   int i;
7465
7466   if (packet_support (PACKET_p) == PACKET_DISABLE)
7467     return 0;
7468
7469   if (reg->pnum == -1)
7470     return 0;
7471
7472   p = rs->buf;
7473   *p++ = 'p';
7474   p += hexnumstr (p, reg->pnum);
7475   *p++ = '\0';
7476   putpkt (rs->buf);
7477   getpkt (&rs->buf, &rs->buf_size, 0);
7478
7479   buf = rs->buf;
7480
7481   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7482     {
7483     case PACKET_OK:
7484       break;
7485     case PACKET_UNKNOWN:
7486       return 0;
7487     case PACKET_ERROR:
7488       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7489              gdbarch_register_name (regcache->arch (), 
7490                                     reg->regnum), 
7491              buf);
7492     }
7493
7494   /* If this register is unfetchable, tell the regcache.  */
7495   if (buf[0] == 'x')
7496     {
7497       regcache_raw_supply (regcache, reg->regnum, NULL);
7498       return 1;
7499     }
7500
7501   /* Otherwise, parse and supply the value.  */
7502   p = buf;
7503   i = 0;
7504   while (p[0] != 0)
7505     {
7506       if (p[1] == 0)
7507         error (_("fetch_register_using_p: early buf termination"));
7508
7509       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7510       p += 2;
7511     }
7512   regcache_raw_supply (regcache, reg->regnum, regp);
7513   return 1;
7514 }
7515
7516 /* Fetch the registers included in the target's 'g' packet.  */
7517
7518 static int
7519 send_g_packet (void)
7520 {
7521   struct remote_state *rs = get_remote_state ();
7522   int buf_len;
7523
7524   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7525   putpkt (rs->buf);
7526   getpkt (&rs->buf, &rs->buf_size, 0);
7527   if (packet_check_result (rs->buf) == PACKET_ERROR)
7528     error (_("Could not read registers; remote failure reply '%s'"),
7529            rs->buf);
7530
7531   /* We can get out of synch in various cases.  If the first character
7532      in the buffer is not a hex character, assume that has happened
7533      and try to fetch another packet to read.  */
7534   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7535          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7536          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7537          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7538     {
7539       if (remote_debug)
7540         fprintf_unfiltered (gdb_stdlog,
7541                             "Bad register packet; fetching a new packet\n");
7542       getpkt (&rs->buf, &rs->buf_size, 0);
7543     }
7544
7545   buf_len = strlen (rs->buf);
7546
7547   /* Sanity check the received packet.  */
7548   if (buf_len % 2 != 0)
7549     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
7550
7551   return buf_len / 2;
7552 }
7553
7554 static void
7555 process_g_packet (struct regcache *regcache)
7556 {
7557   struct gdbarch *gdbarch = regcache->arch ();
7558   struct remote_state *rs = get_remote_state ();
7559   remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7560   int i, buf_len;
7561   char *p;
7562   char *regs;
7563
7564   buf_len = strlen (rs->buf);
7565
7566   /* Further sanity checks, with knowledge of the architecture.  */
7567   if (buf_len > 2 * rsa->sizeof_g_packet)
7568     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
7569              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
7570
7571   /* Save the size of the packet sent to us by the target.  It is used
7572      as a heuristic when determining the max size of packets that the
7573      target can safely receive.  */
7574   if (rsa->actual_register_packet_size == 0)
7575     rsa->actual_register_packet_size = buf_len;
7576
7577   /* If this is smaller than we guessed the 'g' packet would be,
7578      update our records.  A 'g' reply that doesn't include a register's
7579      value implies either that the register is not available, or that
7580      the 'p' packet must be used.  */
7581   if (buf_len < 2 * rsa->sizeof_g_packet)
7582     {
7583       long sizeof_g_packet = buf_len / 2;
7584
7585       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7586         {
7587           long offset = rsa->regs[i].offset;
7588           long reg_size = register_size (gdbarch, i);
7589
7590           if (rsa->regs[i].pnum == -1)
7591             continue;
7592
7593           if (offset >= sizeof_g_packet)
7594             rsa->regs[i].in_g_packet = 0;
7595           else if (offset + reg_size > sizeof_g_packet)
7596             error (_("Truncated register %d in remote 'g' packet"), i);
7597           else
7598             rsa->regs[i].in_g_packet = 1;
7599         }
7600
7601       /* Looks valid enough, we can assume this is the correct length
7602          for a 'g' packet.  It's important not to adjust
7603          rsa->sizeof_g_packet if we have truncated registers otherwise
7604          this "if" won't be run the next time the method is called
7605          with a packet of the same size and one of the internal errors
7606          below will trigger instead.  */
7607       rsa->sizeof_g_packet = sizeof_g_packet;
7608     }
7609
7610   regs = (char *) alloca (rsa->sizeof_g_packet);
7611
7612   /* Unimplemented registers read as all bits zero.  */
7613   memset (regs, 0, rsa->sizeof_g_packet);
7614
7615   /* Reply describes registers byte by byte, each byte encoded as two
7616      hex characters.  Suck them all up, then supply them to the
7617      register cacheing/storage mechanism.  */
7618
7619   p = rs->buf;
7620   for (i = 0; i < rsa->sizeof_g_packet; i++)
7621     {
7622       if (p[0] == 0 || p[1] == 0)
7623         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
7624         internal_error (__FILE__, __LINE__,
7625                         _("unexpected end of 'g' packet reply"));
7626
7627       if (p[0] == 'x' && p[1] == 'x')
7628         regs[i] = 0;            /* 'x' */
7629       else
7630         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
7631       p += 2;
7632     }
7633
7634   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7635     {
7636       struct packet_reg *r = &rsa->regs[i];
7637       long reg_size = register_size (gdbarch, i);
7638
7639       if (r->in_g_packet)
7640         {
7641           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
7642             /* This shouldn't happen - we adjusted in_g_packet above.  */
7643             internal_error (__FILE__, __LINE__,
7644                             _("unexpected end of 'g' packet reply"));
7645           else if (rs->buf[r->offset * 2] == 'x')
7646             {
7647               gdb_assert (r->offset * 2 < strlen (rs->buf));
7648               /* The register isn't available, mark it as such (at
7649                  the same time setting the value to zero).  */
7650               regcache_raw_supply (regcache, r->regnum, NULL);
7651             }
7652           else
7653             regcache_raw_supply (regcache, r->regnum,
7654                                  regs + r->offset);
7655         }
7656     }
7657 }
7658
7659 static void
7660 fetch_registers_using_g (struct regcache *regcache)
7661 {
7662   send_g_packet ();
7663   process_g_packet (regcache);
7664 }
7665
7666 /* Make the remote selected traceframe match GDB's selected
7667    traceframe.  */
7668
7669 static void
7670 set_remote_traceframe (void)
7671 {
7672   int newnum;
7673   struct remote_state *rs = get_remote_state ();
7674
7675   if (rs->remote_traceframe_number == get_traceframe_number ())
7676     return;
7677
7678   /* Avoid recursion, remote_trace_find calls us again.  */
7679   rs->remote_traceframe_number = get_traceframe_number ();
7680
7681   newnum = target_trace_find (tfind_number,
7682                               get_traceframe_number (), 0, 0, NULL);
7683
7684   /* Should not happen.  If it does, all bets are off.  */
7685   if (newnum != get_traceframe_number ())
7686     warning (_("could not set remote traceframe"));
7687 }
7688
7689 static void
7690 remote_fetch_registers (struct target_ops *ops,
7691                         struct regcache *regcache, int regnum)
7692 {
7693   struct gdbarch *gdbarch = regcache->arch ();
7694   remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7695   int i;
7696
7697   set_remote_traceframe ();
7698   set_general_thread (regcache_get_ptid (regcache));
7699
7700   if (regnum >= 0)
7701     {
7702       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7703
7704       gdb_assert (reg != NULL);
7705
7706       /* If this register might be in the 'g' packet, try that first -
7707          we are likely to read more than one register.  If this is the
7708          first 'g' packet, we might be overly optimistic about its
7709          contents, so fall back to 'p'.  */
7710       if (reg->in_g_packet)
7711         {
7712           fetch_registers_using_g (regcache);
7713           if (reg->in_g_packet)
7714             return;
7715         }
7716
7717       if (fetch_register_using_p (regcache, reg))
7718         return;
7719
7720       /* This register is not available.  */
7721       regcache_raw_supply (regcache, reg->regnum, NULL);
7722
7723       return;
7724     }
7725
7726   fetch_registers_using_g (regcache);
7727
7728   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7729     if (!rsa->regs[i].in_g_packet)
7730       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
7731         {
7732           /* This register is not available.  */
7733           regcache_raw_supply (regcache, i, NULL);
7734         }
7735 }
7736
7737 /* Prepare to store registers.  Since we may send them all (using a
7738    'G' request), we have to read out the ones we don't want to change
7739    first.  */
7740
7741 static void
7742 remote_prepare_to_store (struct target_ops *self, struct regcache *regcache)
7743 {
7744   remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
7745   int i;
7746
7747   /* Make sure the entire registers array is valid.  */
7748   switch (packet_support (PACKET_P))
7749     {
7750     case PACKET_DISABLE:
7751     case PACKET_SUPPORT_UNKNOWN:
7752       /* Make sure all the necessary registers are cached.  */
7753       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
7754         if (rsa->regs[i].in_g_packet)
7755           regcache_raw_update (regcache, rsa->regs[i].regnum);
7756       break;
7757     case PACKET_ENABLE:
7758       break;
7759     }
7760 }
7761
7762 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
7763    packet was not recognized.  */
7764
7765 static int
7766 store_register_using_P (const struct regcache *regcache, 
7767                         struct packet_reg *reg)
7768 {
7769   struct gdbarch *gdbarch = regcache->arch ();
7770   struct remote_state *rs = get_remote_state ();
7771   /* Try storing a single register.  */
7772   char *buf = rs->buf;
7773   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7774   char *p;
7775
7776   if (packet_support (PACKET_P) == PACKET_DISABLE)
7777     return 0;
7778
7779   if (reg->pnum == -1)
7780     return 0;
7781
7782   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
7783   p = buf + strlen (buf);
7784   regcache_raw_collect (regcache, reg->regnum, regp);
7785   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
7786   putpkt (rs->buf);
7787   getpkt (&rs->buf, &rs->buf_size, 0);
7788
7789   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
7790     {
7791     case PACKET_OK:
7792       return 1;
7793     case PACKET_ERROR:
7794       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
7795              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
7796     case PACKET_UNKNOWN:
7797       return 0;
7798     default:
7799       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
7800     }
7801 }
7802
7803 /* Store register REGNUM, or all registers if REGNUM == -1, from the
7804    contents of the register cache buffer.  FIXME: ignores errors.  */
7805
7806 static void
7807 store_registers_using_G (const struct regcache *regcache)
7808 {
7809   struct remote_state *rs = get_remote_state ();
7810   remote_arch_state *rsa = get_remote_arch_state (regcache->arch ());
7811   gdb_byte *regs;
7812   char *p;
7813
7814   /* Extract all the registers in the regcache copying them into a
7815      local buffer.  */
7816   {
7817     int i;
7818
7819     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
7820     memset (regs, 0, rsa->sizeof_g_packet);
7821     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
7822       {
7823         struct packet_reg *r = &rsa->regs[i];
7824
7825         if (r->in_g_packet)
7826           regcache_raw_collect (regcache, r->regnum, regs + r->offset);
7827       }
7828   }
7829
7830   /* Command describes registers byte by byte,
7831      each byte encoded as two hex characters.  */
7832   p = rs->buf;
7833   *p++ = 'G';
7834   bin2hex (regs, p, rsa->sizeof_g_packet);
7835   putpkt (rs->buf);
7836   getpkt (&rs->buf, &rs->buf_size, 0);
7837   if (packet_check_result (rs->buf) == PACKET_ERROR)
7838     error (_("Could not write registers; remote failure reply '%s'"), 
7839            rs->buf);
7840 }
7841
7842 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
7843    of the register cache buffer.  FIXME: ignores errors.  */
7844
7845 static void
7846 remote_store_registers (struct target_ops *ops,
7847                         struct regcache *regcache, int regnum)
7848 {
7849   struct gdbarch *gdbarch = regcache->arch ();
7850   remote_arch_state *rsa = get_remote_arch_state (gdbarch);
7851   int i;
7852
7853   set_remote_traceframe ();
7854   set_general_thread (regcache_get_ptid (regcache));
7855
7856   if (regnum >= 0)
7857     {
7858       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
7859
7860       gdb_assert (reg != NULL);
7861
7862       /* Always prefer to store registers using the 'P' packet if
7863          possible; we often change only a small number of registers.
7864          Sometimes we change a larger number; we'd need help from a
7865          higher layer to know to use 'G'.  */
7866       if (store_register_using_P (regcache, reg))
7867         return;
7868
7869       /* For now, don't complain if we have no way to write the
7870          register.  GDB loses track of unavailable registers too
7871          easily.  Some day, this may be an error.  We don't have
7872          any way to read the register, either...  */
7873       if (!reg->in_g_packet)
7874         return;
7875
7876       store_registers_using_G (regcache);
7877       return;
7878     }
7879
7880   store_registers_using_G (regcache);
7881
7882   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
7883     if (!rsa->regs[i].in_g_packet)
7884       if (!store_register_using_P (regcache, &rsa->regs[i]))
7885         /* See above for why we do not issue an error here.  */
7886         continue;
7887 }
7888 \f
7889
7890 /* Return the number of hex digits in num.  */
7891
7892 static int
7893 hexnumlen (ULONGEST num)
7894 {
7895   int i;
7896
7897   for (i = 0; num != 0; i++)
7898     num >>= 4;
7899
7900   return std::max (i, 1);
7901 }
7902
7903 /* Set BUF to the minimum number of hex digits representing NUM.  */
7904
7905 static int
7906 hexnumstr (char *buf, ULONGEST num)
7907 {
7908   int len = hexnumlen (num);
7909
7910   return hexnumnstr (buf, num, len);
7911 }
7912
7913
7914 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
7915
7916 static int
7917 hexnumnstr (char *buf, ULONGEST num, int width)
7918 {
7919   int i;
7920
7921   buf[width] = '\0';
7922
7923   for (i = width - 1; i >= 0; i--)
7924     {
7925       buf[i] = "0123456789abcdef"[(num & 0xf)];
7926       num >>= 4;
7927     }
7928
7929   return width;
7930 }
7931
7932 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
7933
7934 static CORE_ADDR
7935 remote_address_masked (CORE_ADDR addr)
7936 {
7937   unsigned int address_size = remote_address_size;
7938
7939   /* If "remoteaddresssize" was not set, default to target address size.  */
7940   if (!address_size)
7941     address_size = gdbarch_addr_bit (target_gdbarch ());
7942
7943   if (address_size > 0
7944       && address_size < (sizeof (ULONGEST) * 8))
7945     {
7946       /* Only create a mask when that mask can safely be constructed
7947          in a ULONGEST variable.  */
7948       ULONGEST mask = 1;
7949
7950       mask = (mask << address_size) - 1;
7951       addr &= mask;
7952     }
7953   return addr;
7954 }
7955
7956 /* Determine whether the remote target supports binary downloading.
7957    This is accomplished by sending a no-op memory write of zero length
7958    to the target at the specified address. It does not suffice to send
7959    the whole packet, since many stubs strip the eighth bit and
7960    subsequently compute a wrong checksum, which causes real havoc with
7961    remote_write_bytes.
7962
7963    NOTE: This can still lose if the serial line is not eight-bit
7964    clean.  In cases like this, the user should clear "remote
7965    X-packet".  */
7966
7967 static void
7968 check_binary_download (CORE_ADDR addr)
7969 {
7970   struct remote_state *rs = get_remote_state ();
7971
7972   switch (packet_support (PACKET_X))
7973     {
7974     case PACKET_DISABLE:
7975       break;
7976     case PACKET_ENABLE:
7977       break;
7978     case PACKET_SUPPORT_UNKNOWN:
7979       {
7980         char *p;
7981
7982         p = rs->buf;
7983         *p++ = 'X';
7984         p += hexnumstr (p, (ULONGEST) addr);
7985         *p++ = ',';
7986         p += hexnumstr (p, (ULONGEST) 0);
7987         *p++ = ':';
7988         *p = '\0';
7989
7990         putpkt_binary (rs->buf, (int) (p - rs->buf));
7991         getpkt (&rs->buf, &rs->buf_size, 0);
7992
7993         if (rs->buf[0] == '\0')
7994           {
7995             if (remote_debug)
7996               fprintf_unfiltered (gdb_stdlog,
7997                                   "binary downloading NOT "
7998                                   "supported by target\n");
7999             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8000           }
8001         else
8002           {
8003             if (remote_debug)
8004               fprintf_unfiltered (gdb_stdlog,
8005                                   "binary downloading supported by target\n");
8006             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8007           }
8008         break;
8009       }
8010     }
8011 }
8012
8013 /* Helper function to resize the payload in order to try to get a good
8014    alignment.  We try to write an amount of data such that the next write will
8015    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8016
8017 static int
8018 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8019 {
8020   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8021 }
8022
8023 /* Write memory data directly to the remote machine.
8024    This does not inform the data cache; the data cache uses this.
8025    HEADER is the starting part of the packet.
8026    MEMADDR is the address in the remote memory space.
8027    MYADDR is the address of the buffer in our space.
8028    LEN_UNITS is the number of addressable units to write.
8029    UNIT_SIZE is the length in bytes of an addressable unit.
8030    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8031    should send data as binary ('X'), or hex-encoded ('M').
8032
8033    The function creates packet of the form
8034        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8035
8036    where encoding of <DATA> is terminated by PACKET_FORMAT.
8037
8038    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8039    are omitted.
8040
8041    Return the transferred status, error or OK (an
8042    'enum target_xfer_status' value).  Save the number of addressable units
8043    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8044
8045    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8046    exchange between gdb and the stub could look like (?? in place of the
8047    checksum):
8048
8049    -> $m1000,4#??
8050    <- aaaabbbbccccdddd
8051
8052    -> $M1000,3:eeeeffffeeee#??
8053    <- OK
8054
8055    -> $m1000,4#??
8056    <- eeeeffffeeeedddd  */
8057
8058 static enum target_xfer_status
8059 remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8060                         const gdb_byte *myaddr, ULONGEST len_units,
8061                         int unit_size, ULONGEST *xfered_len_units,
8062                         char packet_format, int use_length)
8063 {
8064   struct remote_state *rs = get_remote_state ();
8065   char *p;
8066   char *plen = NULL;
8067   int plenlen = 0;
8068   int todo_units;
8069   int units_written;
8070   int payload_capacity_bytes;
8071   int payload_length_bytes;
8072
8073   if (packet_format != 'X' && packet_format != 'M')
8074     internal_error (__FILE__, __LINE__,
8075                     _("remote_write_bytes_aux: bad packet format"));
8076
8077   if (len_units == 0)
8078     return TARGET_XFER_EOF;
8079
8080   payload_capacity_bytes = get_memory_write_packet_size ();
8081
8082   /* The packet buffer will be large enough for the payload;
8083      get_memory_packet_size ensures this.  */
8084   rs->buf[0] = '\0';
8085
8086   /* Compute the size of the actual payload by subtracting out the
8087      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8088
8089   payload_capacity_bytes -= strlen ("$,:#NN");
8090   if (!use_length)
8091     /* The comma won't be used.  */
8092     payload_capacity_bytes += 1;
8093   payload_capacity_bytes -= strlen (header);
8094   payload_capacity_bytes -= hexnumlen (memaddr);
8095
8096   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8097
8098   strcat (rs->buf, header);
8099   p = rs->buf + strlen (header);
8100
8101   /* Compute a best guess of the number of bytes actually transfered.  */
8102   if (packet_format == 'X')
8103     {
8104       /* Best guess at number of bytes that will fit.  */
8105       todo_units = std::min (len_units,
8106                              (ULONGEST) payload_capacity_bytes / unit_size);
8107       if (use_length)
8108         payload_capacity_bytes -= hexnumlen (todo_units);
8109       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8110     }
8111   else
8112     {
8113       /* Number of bytes that will fit.  */
8114       todo_units
8115         = std::min (len_units,
8116                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8117       if (use_length)
8118         payload_capacity_bytes -= hexnumlen (todo_units);
8119       todo_units = std::min (todo_units,
8120                              (payload_capacity_bytes / unit_size) / 2);
8121     }
8122
8123   if (todo_units <= 0)
8124     internal_error (__FILE__, __LINE__,
8125                     _("minimum packet size too small to write data"));
8126
8127   /* If we already need another packet, then try to align the end
8128      of this packet to a useful boundary.  */
8129   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8130     todo_units = align_for_efficient_write (todo_units, memaddr);
8131
8132   /* Append "<memaddr>".  */
8133   memaddr = remote_address_masked (memaddr);
8134   p += hexnumstr (p, (ULONGEST) memaddr);
8135
8136   if (use_length)
8137     {
8138       /* Append ",".  */
8139       *p++ = ',';
8140
8141       /* Append the length and retain its location and size.  It may need to be
8142          adjusted once the packet body has been created.  */
8143       plen = p;
8144       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8145       p += plenlen;
8146     }
8147
8148   /* Append ":".  */
8149   *p++ = ':';
8150   *p = '\0';
8151
8152   /* Append the packet body.  */
8153   if (packet_format == 'X')
8154     {
8155       /* Binary mode.  Send target system values byte by byte, in
8156          increasing byte addresses.  Only escape certain critical
8157          characters.  */
8158       payload_length_bytes =
8159           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8160                                 &units_written, payload_capacity_bytes);
8161
8162       /* If not all TODO units fit, then we'll need another packet.  Make
8163          a second try to keep the end of the packet aligned.  Don't do
8164          this if the packet is tiny.  */
8165       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8166         {
8167           int new_todo_units;
8168
8169           new_todo_units = align_for_efficient_write (units_written, memaddr);
8170
8171           if (new_todo_units != units_written)
8172             payload_length_bytes =
8173                 remote_escape_output (myaddr, new_todo_units, unit_size,
8174                                       (gdb_byte *) p, &units_written,
8175                                       payload_capacity_bytes);
8176         }
8177
8178       p += payload_length_bytes;
8179       if (use_length && units_written < todo_units)
8180         {
8181           /* Escape chars have filled up the buffer prematurely,
8182              and we have actually sent fewer units than planned.
8183              Fix-up the length field of the packet.  Use the same
8184              number of characters as before.  */
8185           plen += hexnumnstr (plen, (ULONGEST) units_written,
8186                               plenlen);
8187           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8188         }
8189     }
8190   else
8191     {
8192       /* Normal mode: Send target system values byte by byte, in
8193          increasing byte addresses.  Each byte is encoded as a two hex
8194          value.  */
8195       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8196       units_written = todo_units;
8197     }
8198
8199   putpkt_binary (rs->buf, (int) (p - rs->buf));
8200   getpkt (&rs->buf, &rs->buf_size, 0);
8201
8202   if (rs->buf[0] == 'E')
8203     return TARGET_XFER_E_IO;
8204
8205   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8206      send fewer units than we'd planned.  */
8207   *xfered_len_units = (ULONGEST) units_written;
8208   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8209 }
8210
8211 /* Write memory data directly to the remote machine.
8212    This does not inform the data cache; the data cache uses this.
8213    MEMADDR is the address in the remote memory space.
8214    MYADDR is the address of the buffer in our space.
8215    LEN is the number of bytes.
8216
8217    Return the transferred status, error or OK (an
8218    'enum target_xfer_status' value).  Save the number of bytes
8219    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8220
8221 static enum target_xfer_status
8222 remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr, ULONGEST len,
8223                     int unit_size, ULONGEST *xfered_len)
8224 {
8225   const char *packet_format = NULL;
8226
8227   /* Check whether the target supports binary download.  */
8228   check_binary_download (memaddr);
8229
8230   switch (packet_support (PACKET_X))
8231     {
8232     case PACKET_ENABLE:
8233       packet_format = "X";
8234       break;
8235     case PACKET_DISABLE:
8236       packet_format = "M";
8237       break;
8238     case PACKET_SUPPORT_UNKNOWN:
8239       internal_error (__FILE__, __LINE__,
8240                       _("remote_write_bytes: bad internal state"));
8241     default:
8242       internal_error (__FILE__, __LINE__, _("bad switch"));
8243     }
8244
8245   return remote_write_bytes_aux (packet_format,
8246                                  memaddr, myaddr, len, unit_size, xfered_len,
8247                                  packet_format[0], 1);
8248 }
8249
8250 /* Read memory data directly from the remote machine.
8251    This does not use the data cache; the data cache uses this.
8252    MEMADDR is the address in the remote memory space.
8253    MYADDR is the address of the buffer in our space.
8254    LEN_UNITS is the number of addressable memory units to read..
8255    UNIT_SIZE is the length in bytes of an addressable unit.
8256
8257    Return the transferred status, error or OK (an
8258    'enum target_xfer_status' value).  Save the number of bytes
8259    transferred in *XFERED_LEN_UNITS.
8260
8261    See the comment of remote_write_bytes_aux for an example of
8262    memory read/write exchange between gdb and the stub.  */
8263
8264 static enum target_xfer_status
8265 remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr, ULONGEST len_units,
8266                      int unit_size, ULONGEST *xfered_len_units)
8267 {
8268   struct remote_state *rs = get_remote_state ();
8269   int buf_size_bytes;           /* Max size of packet output buffer.  */
8270   char *p;
8271   int todo_units;
8272   int decoded_bytes;
8273
8274   buf_size_bytes = get_memory_read_packet_size ();
8275   /* The packet buffer will be large enough for the payload;
8276      get_memory_packet_size ensures this.  */
8277
8278   /* Number of units that will fit.  */
8279   todo_units = std::min (len_units,
8280                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8281
8282   /* Construct "m"<memaddr>","<len>".  */
8283   memaddr = remote_address_masked (memaddr);
8284   p = rs->buf;
8285   *p++ = 'm';
8286   p += hexnumstr (p, (ULONGEST) memaddr);
8287   *p++ = ',';
8288   p += hexnumstr (p, (ULONGEST) todo_units);
8289   *p = '\0';
8290   putpkt (rs->buf);
8291   getpkt (&rs->buf, &rs->buf_size, 0);
8292   if (rs->buf[0] == 'E'
8293       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8294       && rs->buf[3] == '\0')
8295     return TARGET_XFER_E_IO;
8296   /* Reply describes memory byte by byte, each byte encoded as two hex
8297      characters.  */
8298   p = rs->buf;
8299   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8300   /* Return what we have.  Let higher layers handle partial reads.  */
8301   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8302   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8303 }
8304
8305 /* Using the set of read-only target sections of remote, read live
8306    read-only memory.
8307
8308    For interface/parameters/return description see target.h,
8309    to_xfer_partial.  */
8310
8311 static enum target_xfer_status
8312 remote_xfer_live_readonly_partial (struct target_ops *ops, gdb_byte *readbuf,
8313                                    ULONGEST memaddr, ULONGEST len,
8314                                    int unit_size, ULONGEST *xfered_len)
8315 {
8316   struct target_section *secp;
8317   struct target_section_table *table;
8318
8319   secp = target_section_by_addr (ops, memaddr);
8320   if (secp != NULL
8321       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8322                                  secp->the_bfd_section)
8323           & SEC_READONLY))
8324     {
8325       struct target_section *p;
8326       ULONGEST memend = memaddr + len;
8327
8328       table = target_get_section_table (ops);
8329
8330       for (p = table->sections; p < table->sections_end; p++)
8331         {
8332           if (memaddr >= p->addr)
8333             {
8334               if (memend <= p->endaddr)
8335                 {
8336                   /* Entire transfer is within this section.  */
8337                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8338                                               xfered_len);
8339                 }
8340               else if (memaddr >= p->endaddr)
8341                 {
8342                   /* This section ends before the transfer starts.  */
8343                   continue;
8344                 }
8345               else
8346                 {
8347                   /* This section overlaps the transfer.  Just do half.  */
8348                   len = p->endaddr - memaddr;
8349                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8350                                               xfered_len);
8351                 }
8352             }
8353         }
8354     }
8355
8356   return TARGET_XFER_EOF;
8357 }
8358
8359 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8360    first if the requested memory is unavailable in traceframe.
8361    Otherwise, fall back to remote_read_bytes_1.  */
8362
8363 static enum target_xfer_status
8364 remote_read_bytes (struct target_ops *ops, CORE_ADDR memaddr,
8365                    gdb_byte *myaddr, ULONGEST len, int unit_size,
8366                    ULONGEST *xfered_len)
8367 {
8368   if (len == 0)
8369     return TARGET_XFER_EOF;
8370
8371   if (get_traceframe_number () != -1)
8372     {
8373       std::vector<mem_range> available;
8374
8375       /* If we fail to get the set of available memory, then the
8376          target does not support querying traceframe info, and so we
8377          attempt reading from the traceframe anyway (assuming the
8378          target implements the old QTro packet then).  */
8379       if (traceframe_available_memory (&available, memaddr, len))
8380         {
8381           if (available.empty () || available[0].start != memaddr)
8382             {
8383               enum target_xfer_status res;
8384
8385               /* Don't read into the traceframe's available
8386                  memory.  */
8387               if (!available.empty ())
8388                 {
8389                   LONGEST oldlen = len;
8390
8391                   len = available[0].start - memaddr;
8392                   gdb_assert (len <= oldlen);
8393                 }
8394
8395               /* This goes through the topmost target again.  */
8396               res = remote_xfer_live_readonly_partial (ops, myaddr, memaddr,
8397                                                        len, unit_size, xfered_len);
8398               if (res == TARGET_XFER_OK)
8399                 return TARGET_XFER_OK;
8400               else
8401                 {
8402                   /* No use trying further, we know some memory starting
8403                      at MEMADDR isn't available.  */
8404                   *xfered_len = len;
8405                   return (*xfered_len != 0) ?
8406                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8407                 }
8408             }
8409
8410           /* Don't try to read more than how much is available, in
8411              case the target implements the deprecated QTro packet to
8412              cater for older GDBs (the target's knowledge of read-only
8413              sections may be outdated by now).  */
8414           len = available[0].length;
8415         }
8416     }
8417
8418   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8419 }
8420
8421 \f
8422
8423 /* Sends a packet with content determined by the printf format string
8424    FORMAT and the remaining arguments, then gets the reply.  Returns
8425    whether the packet was a success, a failure, or unknown.  */
8426
8427 static enum packet_result remote_send_printf (const char *format, ...)
8428   ATTRIBUTE_PRINTF (1, 2);
8429
8430 static enum packet_result
8431 remote_send_printf (const char *format, ...)
8432 {
8433   struct remote_state *rs = get_remote_state ();
8434   int max_size = get_remote_packet_size ();
8435   va_list ap;
8436
8437   va_start (ap, format);
8438
8439   rs->buf[0] = '\0';
8440   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8441     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8442
8443   if (putpkt (rs->buf) < 0)
8444     error (_("Communication problem with target."));
8445
8446   rs->buf[0] = '\0';
8447   getpkt (&rs->buf, &rs->buf_size, 0);
8448
8449   return packet_check_result (rs->buf);
8450 }
8451
8452 /* Flash writing can take quite some time.  We'll set
8453    effectively infinite timeout for flash operations.
8454    In future, we'll need to decide on a better approach.  */
8455 static const int remote_flash_timeout = 1000;
8456
8457 static void
8458 remote_flash_erase (struct target_ops *ops,
8459                     ULONGEST address, LONGEST length)
8460 {
8461   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8462   enum packet_result ret;
8463   scoped_restore restore_timeout
8464     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8465
8466   ret = remote_send_printf ("vFlashErase:%s,%s",
8467                             phex (address, addr_size),
8468                             phex (length, 4));
8469   switch (ret)
8470     {
8471     case PACKET_UNKNOWN:
8472       error (_("Remote target does not support flash erase"));
8473     case PACKET_ERROR:
8474       error (_("Error erasing flash with vFlashErase packet"));
8475     default:
8476       break;
8477     }
8478 }
8479
8480 static enum target_xfer_status
8481 remote_flash_write (struct target_ops *ops, ULONGEST address,
8482                     ULONGEST length, ULONGEST *xfered_len,
8483                     const gdb_byte *data)
8484 {
8485   scoped_restore restore_timeout
8486     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8487   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8488                                  xfered_len,'X', 0);
8489 }
8490
8491 static void
8492 remote_flash_done (struct target_ops *ops)
8493 {
8494   int ret;
8495
8496   scoped_restore restore_timeout
8497     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8498
8499   ret = remote_send_printf ("vFlashDone");
8500
8501   switch (ret)
8502     {
8503     case PACKET_UNKNOWN:
8504       error (_("Remote target does not support vFlashDone"));
8505     case PACKET_ERROR:
8506       error (_("Error finishing flash operation"));
8507     default:
8508       break;
8509     }
8510 }
8511
8512 static void
8513 remote_files_info (struct target_ops *ignore)
8514 {
8515   puts_filtered ("Debugging a target over a serial line.\n");
8516 }
8517 \f
8518 /* Stuff for dealing with the packets which are part of this protocol.
8519    See comment at top of file for details.  */
8520
8521 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8522    error to higher layers.  Called when a serial error is detected.
8523    The exception message is STRING, followed by a colon and a blank,
8524    the system error message for errno at function entry and final dot
8525    for output compatibility with throw_perror_with_name.  */
8526
8527 static void
8528 unpush_and_perror (const char *string)
8529 {
8530   int saved_errno = errno;
8531
8532   remote_unpush_target ();
8533   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8534                safe_strerror (saved_errno));
8535 }
8536
8537 /* Read a single character from the remote end.  The current quit
8538    handler is overridden to avoid quitting in the middle of packet
8539    sequence, as that would break communication with the remote server.
8540    See remote_serial_quit_handler for more detail.  */
8541
8542 static int
8543 readchar (int timeout)
8544 {
8545   int ch;
8546   struct remote_state *rs = get_remote_state ();
8547
8548   {
8549     scoped_restore restore_quit
8550       = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8551
8552     rs->got_ctrlc_during_io = 0;
8553
8554     ch = serial_readchar (rs->remote_desc, timeout);
8555
8556     if (rs->got_ctrlc_during_io)
8557       set_quit_flag ();
8558   }
8559
8560   if (ch >= 0)
8561     return ch;
8562
8563   switch ((enum serial_rc) ch)
8564     {
8565     case SERIAL_EOF:
8566       remote_unpush_target ();
8567       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
8568       /* no return */
8569     case SERIAL_ERROR:
8570       unpush_and_perror (_("Remote communication error.  "
8571                            "Target disconnected."));
8572       /* no return */
8573     case SERIAL_TIMEOUT:
8574       break;
8575     }
8576   return ch;
8577 }
8578
8579 /* Wrapper for serial_write that closes the target and throws if
8580    writing fails.  The current quit handler is overridden to avoid
8581    quitting in the middle of packet sequence, as that would break
8582    communication with the remote server.  See
8583    remote_serial_quit_handler for more detail.  */
8584
8585 static void
8586 remote_serial_write (const char *str, int len)
8587 {
8588   struct remote_state *rs = get_remote_state ();
8589
8590   scoped_restore restore_quit
8591     = make_scoped_restore (&quit_handler, remote_serial_quit_handler);
8592
8593   rs->got_ctrlc_during_io = 0;
8594
8595   if (serial_write (rs->remote_desc, str, len))
8596     {
8597       unpush_and_perror (_("Remote communication error.  "
8598                            "Target disconnected."));
8599     }
8600
8601   if (rs->got_ctrlc_during_io)
8602     set_quit_flag ();
8603 }
8604
8605 /* Return a string representing an escaped version of BUF, of len N.
8606    E.g. \n is converted to \\n, \t to \\t, etc.  */
8607
8608 static std::string
8609 escape_buffer (const char *buf, int n)
8610 {
8611   string_file stb;
8612
8613   stb.putstrn (buf, n, '\\');
8614   return std::move (stb.string ());
8615 }
8616
8617 /* Display a null-terminated packet on stdout, for debugging, using C
8618    string notation.  */
8619
8620 static void
8621 print_packet (const char *buf)
8622 {
8623   puts_filtered ("\"");
8624   fputstr_filtered (buf, '"', gdb_stdout);
8625   puts_filtered ("\"");
8626 }
8627
8628 int
8629 putpkt (const char *buf)
8630 {
8631   return putpkt_binary (buf, strlen (buf));
8632 }
8633
8634 /* Send a packet to the remote machine, with error checking.  The data
8635    of the packet is in BUF.  The string in BUF can be at most
8636    get_remote_packet_size () - 5 to account for the $, # and checksum,
8637    and for a possible /0 if we are debugging (remote_debug) and want
8638    to print the sent packet as a string.  */
8639
8640 static int
8641 putpkt_binary (const char *buf, int cnt)
8642 {
8643   struct remote_state *rs = get_remote_state ();
8644   int i;
8645   unsigned char csum = 0;
8646   gdb::def_vector<char> data (cnt + 6);
8647   char *buf2 = data.data ();
8648
8649   int ch;
8650   int tcount = 0;
8651   char *p;
8652
8653   /* Catch cases like trying to read memory or listing threads while
8654      we're waiting for a stop reply.  The remote server wouldn't be
8655      ready to handle this request, so we'd hang and timeout.  We don't
8656      have to worry about this in synchronous mode, because in that
8657      case it's not possible to issue a command while the target is
8658      running.  This is not a problem in non-stop mode, because in that
8659      case, the stub is always ready to process serial input.  */
8660   if (!target_is_non_stop_p ()
8661       && target_is_async_p ()
8662       && rs->waiting_for_stop_reply)
8663     {
8664       error (_("Cannot execute this command while the target is running.\n"
8665                "Use the \"interrupt\" command to stop the target\n"
8666                "and then try again."));
8667     }
8668
8669   /* We're sending out a new packet.  Make sure we don't look at a
8670      stale cached response.  */
8671   rs->cached_wait_status = 0;
8672
8673   /* Copy the packet into buffer BUF2, encapsulating it
8674      and giving it a checksum.  */
8675
8676   p = buf2;
8677   *p++ = '$';
8678
8679   for (i = 0; i < cnt; i++)
8680     {
8681       csum += buf[i];
8682       *p++ = buf[i];
8683     }
8684   *p++ = '#';
8685   *p++ = tohex ((csum >> 4) & 0xf);
8686   *p++ = tohex (csum & 0xf);
8687
8688   /* Send it over and over until we get a positive ack.  */
8689
8690   while (1)
8691     {
8692       int started_error_output = 0;
8693
8694       if (remote_debug)
8695         {
8696           *p = '\0';
8697
8698           int len = (int) (p - buf2);
8699
8700           std::string str
8701             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
8702
8703           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
8704
8705           if (len > REMOTE_DEBUG_MAX_CHAR)
8706             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
8707                                 len - REMOTE_DEBUG_MAX_CHAR);
8708
8709           fprintf_unfiltered (gdb_stdlog, "...");
8710
8711           gdb_flush (gdb_stdlog);
8712         }
8713       remote_serial_write (buf2, p - buf2);
8714
8715       /* If this is a no acks version of the remote protocol, send the
8716          packet and move on.  */
8717       if (rs->noack_mode)
8718         break;
8719
8720       /* Read until either a timeout occurs (-2) or '+' is read.
8721          Handle any notification that arrives in the mean time.  */
8722       while (1)
8723         {
8724           ch = readchar (remote_timeout);
8725
8726           if (remote_debug)
8727             {
8728               switch (ch)
8729                 {
8730                 case '+':
8731                 case '-':
8732                 case SERIAL_TIMEOUT:
8733                 case '$':
8734                 case '%':
8735                   if (started_error_output)
8736                     {
8737                       putchar_unfiltered ('\n');
8738                       started_error_output = 0;
8739                     }
8740                 }
8741             }
8742
8743           switch (ch)
8744             {
8745             case '+':
8746               if (remote_debug)
8747                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
8748               return 1;
8749             case '-':
8750               if (remote_debug)
8751                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
8752               /* FALLTHROUGH */
8753             case SERIAL_TIMEOUT:
8754               tcount++;
8755               if (tcount > 3)
8756                 return 0;
8757               break;            /* Retransmit buffer.  */
8758             case '$':
8759               {
8760                 if (remote_debug)
8761                   fprintf_unfiltered (gdb_stdlog,
8762                                       "Packet instead of Ack, ignoring it\n");
8763                 /* It's probably an old response sent because an ACK
8764                    was lost.  Gobble up the packet and ack it so it
8765                    doesn't get retransmitted when we resend this
8766                    packet.  */
8767                 skip_frame ();
8768                 remote_serial_write ("+", 1);
8769                 continue;       /* Now, go look for +.  */
8770               }
8771
8772             case '%':
8773               {
8774                 int val;
8775
8776                 /* If we got a notification, handle it, and go back to looking
8777                    for an ack.  */
8778                 /* We've found the start of a notification.  Now
8779                    collect the data.  */
8780                 val = read_frame (&rs->buf, &rs->buf_size);
8781                 if (val >= 0)
8782                   {
8783                     if (remote_debug)
8784                       {
8785                         std::string str = escape_buffer (rs->buf, val);
8786
8787                         fprintf_unfiltered (gdb_stdlog,
8788                                             "  Notification received: %s\n",
8789                                             str.c_str ());
8790                       }
8791                     handle_notification (rs->notif_state, rs->buf);
8792                     /* We're in sync now, rewait for the ack.  */
8793                     tcount = 0;
8794                   }
8795                 else
8796                   {
8797                     if (remote_debug)
8798                       {
8799                         if (!started_error_output)
8800                           {
8801                             started_error_output = 1;
8802                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8803                           }
8804                         fputc_unfiltered (ch & 0177, gdb_stdlog);
8805                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
8806                       }
8807                   }
8808                 continue;
8809               }
8810               /* fall-through */
8811             default:
8812               if (remote_debug)
8813                 {
8814                   if (!started_error_output)
8815                     {
8816                       started_error_output = 1;
8817                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
8818                     }
8819                   fputc_unfiltered (ch & 0177, gdb_stdlog);
8820                 }
8821               continue;
8822             }
8823           break;                /* Here to retransmit.  */
8824         }
8825
8826 #if 0
8827       /* This is wrong.  If doing a long backtrace, the user should be
8828          able to get out next time we call QUIT, without anything as
8829          violent as interrupt_query.  If we want to provide a way out of
8830          here without getting to the next QUIT, it should be based on
8831          hitting ^C twice as in remote_wait.  */
8832       if (quit_flag)
8833         {
8834           quit_flag = 0;
8835           interrupt_query ();
8836         }
8837 #endif
8838     }
8839
8840   return 0;
8841 }
8842
8843 /* Come here after finding the start of a frame when we expected an
8844    ack.  Do our best to discard the rest of this packet.  */
8845
8846 static void
8847 skip_frame (void)
8848 {
8849   int c;
8850
8851   while (1)
8852     {
8853       c = readchar (remote_timeout);
8854       switch (c)
8855         {
8856         case SERIAL_TIMEOUT:
8857           /* Nothing we can do.  */
8858           return;
8859         case '#':
8860           /* Discard the two bytes of checksum and stop.  */
8861           c = readchar (remote_timeout);
8862           if (c >= 0)
8863             c = readchar (remote_timeout);
8864
8865           return;
8866         case '*':               /* Run length encoding.  */
8867           /* Discard the repeat count.  */
8868           c = readchar (remote_timeout);
8869           if (c < 0)
8870             return;
8871           break;
8872         default:
8873           /* A regular character.  */
8874           break;
8875         }
8876     }
8877 }
8878
8879 /* Come here after finding the start of the frame.  Collect the rest
8880    into *BUF, verifying the checksum, length, and handling run-length
8881    compression.  NUL terminate the buffer.  If there is not enough room,
8882    expand *BUF using xrealloc.
8883
8884    Returns -1 on error, number of characters in buffer (ignoring the
8885    trailing NULL) on success. (could be extended to return one of the
8886    SERIAL status indications).  */
8887
8888 static long
8889 read_frame (char **buf_p,
8890             long *sizeof_buf)
8891 {
8892   unsigned char csum;
8893   long bc;
8894   int c;
8895   char *buf = *buf_p;
8896   struct remote_state *rs = get_remote_state ();
8897
8898   csum = 0;
8899   bc = 0;
8900
8901   while (1)
8902     {
8903       c = readchar (remote_timeout);
8904       switch (c)
8905         {
8906         case SERIAL_TIMEOUT:
8907           if (remote_debug)
8908             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
8909           return -1;
8910         case '$':
8911           if (remote_debug)
8912             fputs_filtered ("Saw new packet start in middle of old one\n",
8913                             gdb_stdlog);
8914           return -1;            /* Start a new packet, count retries.  */
8915         case '#':
8916           {
8917             unsigned char pktcsum;
8918             int check_0 = 0;
8919             int check_1 = 0;
8920
8921             buf[bc] = '\0';
8922
8923             check_0 = readchar (remote_timeout);
8924             if (check_0 >= 0)
8925               check_1 = readchar (remote_timeout);
8926
8927             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
8928               {
8929                 if (remote_debug)
8930                   fputs_filtered ("Timeout in checksum, retrying\n",
8931                                   gdb_stdlog);
8932                 return -1;
8933               }
8934             else if (check_0 < 0 || check_1 < 0)
8935               {
8936                 if (remote_debug)
8937                   fputs_filtered ("Communication error in checksum\n",
8938                                   gdb_stdlog);
8939                 return -1;
8940               }
8941
8942             /* Don't recompute the checksum; with no ack packets we
8943                don't have any way to indicate a packet retransmission
8944                is necessary.  */
8945             if (rs->noack_mode)
8946               return bc;
8947
8948             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
8949             if (csum == pktcsum)
8950               return bc;
8951
8952             if (remote_debug)
8953               {
8954                 std::string str = escape_buffer (buf, bc);
8955
8956                 fprintf_unfiltered (gdb_stdlog,
8957                                     "Bad checksum, sentsum=0x%x, "
8958                                     "csum=0x%x, buf=%s\n",
8959                                     pktcsum, csum, str.c_str ());
8960               }
8961             /* Number of characters in buffer ignoring trailing
8962                NULL.  */
8963             return -1;
8964           }
8965         case '*':               /* Run length encoding.  */
8966           {
8967             int repeat;
8968
8969             csum += c;
8970             c = readchar (remote_timeout);
8971             csum += c;
8972             repeat = c - ' ' + 3;       /* Compute repeat count.  */
8973
8974             /* The character before ``*'' is repeated.  */
8975
8976             if (repeat > 0 && repeat <= 255 && bc > 0)
8977               {
8978                 if (bc + repeat - 1 >= *sizeof_buf - 1)
8979                   {
8980                     /* Make some more room in the buffer.  */
8981                     *sizeof_buf += repeat;
8982                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
8983                     buf = *buf_p;
8984                   }
8985
8986                 memset (&buf[bc], buf[bc - 1], repeat);
8987                 bc += repeat;
8988                 continue;
8989               }
8990
8991             buf[bc] = '\0';
8992             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
8993             return -1;
8994           }
8995         default:
8996           if (bc >= *sizeof_buf - 1)
8997             {
8998               /* Make some more room in the buffer.  */
8999               *sizeof_buf *= 2;
9000               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9001               buf = *buf_p;
9002             }
9003
9004           buf[bc++] = c;
9005           csum += c;
9006           continue;
9007         }
9008     }
9009 }
9010
9011 /* Read a packet from the remote machine, with error checking, and
9012    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9013    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9014    rather than timing out; this is used (in synchronous mode) to wait
9015    for a target that is is executing user code to stop.  */
9016 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9017    don't have to change all the calls to getpkt to deal with the
9018    return value, because at the moment I don't know what the right
9019    thing to do it for those.  */
9020 void
9021 getpkt (char **buf,
9022         long *sizeof_buf,
9023         int forever)
9024 {
9025   getpkt_sane (buf, sizeof_buf, forever);
9026 }
9027
9028
9029 /* Read a packet from the remote machine, with error checking, and
9030    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9031    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9032    rather than timing out; this is used (in synchronous mode) to wait
9033    for a target that is is executing user code to stop.  If FOREVER ==
9034    0, this function is allowed to time out gracefully and return an
9035    indication of this to the caller.  Otherwise return the number of
9036    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9037    enough reason to return to the caller.  *IS_NOTIF is an output
9038    boolean that indicates whether *BUF holds a notification or not
9039    (a regular packet).  */
9040
9041 static int
9042 getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
9043                         int expecting_notif, int *is_notif)
9044 {
9045   struct remote_state *rs = get_remote_state ();
9046   int c;
9047   int tries;
9048   int timeout;
9049   int val = -1;
9050
9051   /* We're reading a new response.  Make sure we don't look at a
9052      previously cached response.  */
9053   rs->cached_wait_status = 0;
9054
9055   strcpy (*buf, "timeout");
9056
9057   if (forever)
9058     timeout = watchdog > 0 ? watchdog : -1;
9059   else if (expecting_notif)
9060     timeout = 0; /* There should already be a char in the buffer.  If
9061                     not, bail out.  */
9062   else
9063     timeout = remote_timeout;
9064
9065 #define MAX_TRIES 3
9066
9067   /* Process any number of notifications, and then return when
9068      we get a packet.  */
9069   for (;;)
9070     {
9071       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9072          times.  */
9073       for (tries = 1; tries <= MAX_TRIES; tries++)
9074         {
9075           /* This can loop forever if the remote side sends us
9076              characters continuously, but if it pauses, we'll get
9077              SERIAL_TIMEOUT from readchar because of timeout.  Then
9078              we'll count that as a retry.
9079
9080              Note that even when forever is set, we will only wait
9081              forever prior to the start of a packet.  After that, we
9082              expect characters to arrive at a brisk pace.  They should
9083              show up within remote_timeout intervals.  */
9084           do
9085             c = readchar (timeout);
9086           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9087
9088           if (c == SERIAL_TIMEOUT)
9089             {
9090               if (expecting_notif)
9091                 return -1; /* Don't complain, it's normal to not get
9092                               anything in this case.  */
9093
9094               if (forever)      /* Watchdog went off?  Kill the target.  */
9095                 {
9096                   remote_unpush_target ();
9097                   throw_error (TARGET_CLOSE_ERROR,
9098                                _("Watchdog timeout has expired.  "
9099                                  "Target detached."));
9100                 }
9101               if (remote_debug)
9102                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9103             }
9104           else
9105             {
9106               /* We've found the start of a packet or notification.
9107                  Now collect the data.  */
9108               val = read_frame (buf, sizeof_buf);
9109               if (val >= 0)
9110                 break;
9111             }
9112
9113           remote_serial_write ("-", 1);
9114         }
9115
9116       if (tries > MAX_TRIES)
9117         {
9118           /* We have tried hard enough, and just can't receive the
9119              packet/notification.  Give up.  */
9120           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9121
9122           /* Skip the ack char if we're in no-ack mode.  */
9123           if (!rs->noack_mode)
9124             remote_serial_write ("+", 1);
9125           return -1;
9126         }
9127
9128       /* If we got an ordinary packet, return that to our caller.  */
9129       if (c == '$')
9130         {
9131           if (remote_debug)
9132             {
9133               std::string str
9134                 = escape_buffer (*buf,
9135                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9136
9137               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9138                                   str.c_str ());
9139
9140               if (val > REMOTE_DEBUG_MAX_CHAR)
9141                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9142                                     val - REMOTE_DEBUG_MAX_CHAR);
9143
9144               fprintf_unfiltered (gdb_stdlog, "\n");
9145             }
9146
9147           /* Skip the ack char if we're in no-ack mode.  */
9148           if (!rs->noack_mode)
9149             remote_serial_write ("+", 1);
9150           if (is_notif != NULL)
9151             *is_notif = 0;
9152           return val;
9153         }
9154
9155        /* If we got a notification, handle it, and go back to looking
9156          for a packet.  */
9157       else
9158         {
9159           gdb_assert (c == '%');
9160
9161           if (remote_debug)
9162             {
9163               std::string str = escape_buffer (*buf, val);
9164
9165               fprintf_unfiltered (gdb_stdlog,
9166                                   "  Notification received: %s\n",
9167                                   str.c_str ());
9168             }
9169           if (is_notif != NULL)
9170             *is_notif = 1;
9171
9172           handle_notification (rs->notif_state, *buf);
9173
9174           /* Notifications require no acknowledgement.  */
9175
9176           if (expecting_notif)
9177             return val;
9178         }
9179     }
9180 }
9181
9182 static int
9183 getpkt_sane (char **buf, long *sizeof_buf, int forever)
9184 {
9185   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9186 }
9187
9188 static int
9189 getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9190                       int *is_notif)
9191 {
9192   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9193                                  is_notif);
9194 }
9195
9196 /* Check whether EVENT is a fork event for the process specified
9197    by the pid passed in DATA, and if it is, kill the fork child.  */
9198
9199 static int
9200 kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9201                             QUEUE_ITER (stop_reply_p) *iter,
9202                             stop_reply_p event,
9203                             void *data)
9204 {
9205   struct queue_iter_param *param = (struct queue_iter_param *) data;
9206   int parent_pid = *(int *) param->input;
9207
9208   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9209     {
9210       struct remote_state *rs = get_remote_state ();
9211       int child_pid = ptid_get_pid (event->ws.value.related_pid);
9212       int res;
9213
9214       res = remote_vkill (child_pid, rs);
9215       if (res != 0)
9216         error (_("Can't kill fork child process %d"), child_pid);
9217     }
9218
9219   return 1;
9220 }
9221
9222 /* Kill any new fork children of process PID that haven't been
9223    processed by follow_fork.  */
9224
9225 static void
9226 kill_new_fork_children (int pid, struct remote_state *rs)
9227 {
9228   struct thread_info *thread;
9229   struct notif_client *notif = &notif_client_stop;
9230   struct queue_iter_param param;
9231
9232   /* Kill the fork child threads of any threads in process PID
9233      that are stopped at a fork event.  */
9234   ALL_NON_EXITED_THREADS (thread)
9235     {
9236       struct target_waitstatus *ws = &thread->pending_follow;
9237
9238       if (is_pending_fork_parent (ws, pid, thread->ptid))
9239         {
9240           struct remote_state *rs = get_remote_state ();
9241           int child_pid = ptid_get_pid (ws->value.related_pid);
9242           int res;
9243
9244           res = remote_vkill (child_pid, rs);
9245           if (res != 0)
9246             error (_("Can't kill fork child process %d"), child_pid);
9247         }
9248     }
9249
9250   /* Check for any pending fork events (not reported or processed yet)
9251      in process PID and kill those fork child threads as well.  */
9252   remote_notif_get_pending_events (notif);
9253   param.input = &pid;
9254   param.output = NULL;
9255   QUEUE_iterate (stop_reply_p, stop_reply_queue,
9256                  kill_child_of_pending_fork, &param);
9257 }
9258
9259 \f
9260 /* Target hook to kill the current inferior.  */
9261
9262 static void
9263 remote_kill (struct target_ops *ops)
9264 {
9265   int res = -1;
9266   int pid = ptid_get_pid (inferior_ptid);
9267   struct remote_state *rs = get_remote_state ();
9268
9269   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9270     {
9271       /* If we're stopped while forking and we haven't followed yet,
9272          kill the child task.  We need to do this before killing the
9273          parent task because if this is a vfork then the parent will
9274          be sleeping.  */
9275       kill_new_fork_children (pid, rs);
9276
9277       res = remote_vkill (pid, rs);
9278       if (res == 0)
9279         {
9280           target_mourn_inferior (inferior_ptid);
9281           return;
9282         }
9283     }
9284
9285   /* If we are in 'target remote' mode and we are killing the only
9286      inferior, then we will tell gdbserver to exit and unpush the
9287      target.  */
9288   if (res == -1 && !remote_multi_process_p (rs)
9289       && number_of_live_inferiors () == 1)
9290     {
9291       remote_kill_k ();
9292
9293       /* We've killed the remote end, we get to mourn it.  If we are
9294          not in extended mode, mourning the inferior also unpushes
9295          remote_ops from the target stack, which closes the remote
9296          connection.  */
9297       target_mourn_inferior (inferior_ptid);
9298
9299       return;
9300     }
9301
9302   error (_("Can't kill process"));
9303 }
9304
9305 /* Send a kill request to the target using the 'vKill' packet.  */
9306
9307 static int
9308 remote_vkill (int pid, struct remote_state *rs)
9309 {
9310   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9311     return -1;
9312
9313   /* Tell the remote target to detach.  */
9314   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9315   putpkt (rs->buf);
9316   getpkt (&rs->buf, &rs->buf_size, 0);
9317
9318   switch (packet_ok (rs->buf,
9319                      &remote_protocol_packets[PACKET_vKill]))
9320     {
9321     case PACKET_OK:
9322       return 0;
9323     case PACKET_ERROR:
9324       return 1;
9325     case PACKET_UNKNOWN:
9326       return -1;
9327     default:
9328       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9329     }
9330 }
9331
9332 /* Send a kill request to the target using the 'k' packet.  */
9333
9334 static void
9335 remote_kill_k (void)
9336 {
9337   /* Catch errors so the user can quit from gdb even when we
9338      aren't on speaking terms with the remote system.  */
9339   TRY
9340     {
9341       putpkt ("k");
9342     }
9343   CATCH (ex, RETURN_MASK_ERROR)
9344     {
9345       if (ex.error == TARGET_CLOSE_ERROR)
9346         {
9347           /* If we got an (EOF) error that caused the target
9348              to go away, then we're done, that's what we wanted.
9349              "k" is susceptible to cause a premature EOF, given
9350              that the remote server isn't actually required to
9351              reply to "k", and it can happen that it doesn't
9352              even get to reply ACK to the "k".  */
9353           return;
9354         }
9355
9356       /* Otherwise, something went wrong.  We didn't actually kill
9357          the target.  Just propagate the exception, and let the
9358          user or higher layers decide what to do.  */
9359       throw_exception (ex);
9360     }
9361   END_CATCH
9362 }
9363
9364 static void
9365 remote_mourn (struct target_ops *target)
9366 {
9367   struct remote_state *rs = get_remote_state ();
9368
9369   /* In 'target remote' mode with one inferior, we close the connection.  */
9370   if (!rs->extended && number_of_live_inferiors () <= 1)
9371     {
9372       unpush_target (target);
9373
9374       /* remote_close takes care of doing most of the clean up.  */
9375       generic_mourn_inferior ();
9376       return;
9377     }
9378
9379   /* In case we got here due to an error, but we're going to stay
9380      connected.  */
9381   rs->waiting_for_stop_reply = 0;
9382
9383   /* If the current general thread belonged to the process we just
9384      detached from or has exited, the remote side current general
9385      thread becomes undefined.  Considering a case like this:
9386
9387      - We just got here due to a detach.
9388      - The process that we're detaching from happens to immediately
9389        report a global breakpoint being hit in non-stop mode, in the
9390        same thread we had selected before.
9391      - GDB attaches to this process again.
9392      - This event happens to be the next event we handle.
9393
9394      GDB would consider that the current general thread didn't need to
9395      be set on the stub side (with Hg), since for all it knew,
9396      GENERAL_THREAD hadn't changed.
9397
9398      Notice that although in all-stop mode, the remote server always
9399      sets the current thread to the thread reporting the stop event,
9400      that doesn't happen in non-stop mode; in non-stop, the stub *must
9401      not* change the current thread when reporting a breakpoint hit,
9402      due to the decoupling of event reporting and event handling.
9403
9404      To keep things simple, we always invalidate our notion of the
9405      current thread.  */
9406   record_currthread (rs, minus_one_ptid);
9407
9408   /* Call common code to mark the inferior as not running.  */
9409   generic_mourn_inferior ();
9410
9411   if (!have_inferiors ())
9412     {
9413       if (!remote_multi_process_p (rs))
9414         {
9415           /* Check whether the target is running now - some remote stubs
9416              automatically restart after kill.  */
9417           putpkt ("?");
9418           getpkt (&rs->buf, &rs->buf_size, 0);
9419
9420           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9421             {
9422               /* Assume that the target has been restarted.  Set
9423                  inferior_ptid so that bits of core GDB realizes
9424                  there's something here, e.g., so that the user can
9425                  say "kill" again.  */
9426               inferior_ptid = magic_null_ptid;
9427             }
9428         }
9429     }
9430 }
9431
9432 static int
9433 extended_remote_supports_disable_randomization (struct target_ops *self)
9434 {
9435   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9436 }
9437
9438 static void
9439 extended_remote_disable_randomization (int val)
9440 {
9441   struct remote_state *rs = get_remote_state ();
9442   char *reply;
9443
9444   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9445              val);
9446   putpkt (rs->buf);
9447   reply = remote_get_noisy_reply ();
9448   if (*reply == '\0')
9449     error (_("Target does not support QDisableRandomization."));
9450   if (strcmp (reply, "OK") != 0)
9451     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9452 }
9453
9454 static int
9455 extended_remote_run (const std::string &args)
9456 {
9457   struct remote_state *rs = get_remote_state ();
9458   int len;
9459   const char *remote_exec_file = get_remote_exec_file ();
9460
9461   /* If the user has disabled vRun support, or we have detected that
9462      support is not available, do not try it.  */
9463   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9464     return -1;
9465
9466   strcpy (rs->buf, "vRun;");
9467   len = strlen (rs->buf);
9468
9469   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9470     error (_("Remote file name too long for run packet"));
9471   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9472                       strlen (remote_exec_file));
9473
9474   if (!args.empty ())
9475     {
9476       int i;
9477
9478       gdb_argv argv (args.c_str ());
9479       for (i = 0; argv[i] != NULL; i++)
9480         {
9481           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9482             error (_("Argument list too long for run packet"));
9483           rs->buf[len++] = ';';
9484           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9485                               strlen (argv[i]));
9486         }
9487     }
9488
9489   rs->buf[len++] = '\0';
9490
9491   putpkt (rs->buf);
9492   getpkt (&rs->buf, &rs->buf_size, 0);
9493
9494   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9495     {
9496     case PACKET_OK:
9497       /* We have a wait response.  All is well.  */
9498       return 0;
9499     case PACKET_UNKNOWN:
9500       return -1;
9501     case PACKET_ERROR:
9502       if (remote_exec_file[0] == '\0')
9503         error (_("Running the default executable on the remote target failed; "
9504                  "try \"set remote exec-file\"?"));
9505       else
9506         error (_("Running \"%s\" on the remote target failed"),
9507                remote_exec_file);
9508     default:
9509       gdb_assert_not_reached (_("bad switch"));
9510     }
9511 }
9512
9513 /* Helper function to send set/unset environment packets.  ACTION is
9514    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
9515    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
9516    sent.  */
9517
9518 static void
9519 send_environment_packet (struct remote_state *rs,
9520                          const char *action,
9521                          const char *packet,
9522                          const char *value)
9523 {
9524   /* Convert the environment variable to an hex string, which
9525      is the best format to be transmitted over the wire.  */
9526   std::string encoded_value = bin2hex ((const gdb_byte *) value,
9527                                          strlen (value));
9528
9529   xsnprintf (rs->buf, get_remote_packet_size (),
9530              "%s:%s", packet, encoded_value.c_str ());
9531
9532   putpkt (rs->buf);
9533   getpkt (&rs->buf, &rs->buf_size, 0);
9534   if (strcmp (rs->buf, "OK") != 0)
9535     warning (_("Unable to %s environment variable '%s' on remote."),
9536              action, value);
9537 }
9538
9539 /* Helper function to handle the QEnvironment* packets.  */
9540
9541 static void
9542 extended_remote_environment_support (struct remote_state *rs)
9543 {
9544   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9545     {
9546       putpkt ("QEnvironmentReset");
9547       getpkt (&rs->buf, &rs->buf_size, 0);
9548       if (strcmp (rs->buf, "OK") != 0)
9549         warning (_("Unable to reset environment on remote."));
9550     }
9551
9552   gdb_environ *e = &current_inferior ()->environment;
9553
9554   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
9555     for (const std::string &el : e->user_set_env ())
9556       send_environment_packet (rs, "set", "QEnvironmentHexEncoded",
9557                                el.c_str ());
9558
9559   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
9560     for (const std::string &el : e->user_unset_env ())
9561       send_environment_packet (rs, "unset", "QEnvironmentUnset", el.c_str ());
9562 }
9563
9564 /* Helper function to set the current working directory for the
9565    inferior in the remote target.  */
9566
9567 static void
9568 extended_remote_set_inferior_cwd (struct remote_state *rs)
9569 {
9570   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
9571     {
9572       const char *inferior_cwd = get_inferior_cwd ();
9573
9574       if (inferior_cwd != NULL)
9575         {
9576           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
9577                                          strlen (inferior_cwd));
9578
9579           xsnprintf (rs->buf, get_remote_packet_size (),
9580                      "QSetWorkingDir:%s", hexpath.c_str ());
9581         }
9582       else
9583         {
9584           /* An empty inferior_cwd means that the user wants us to
9585              reset the remote server's inferior's cwd.  */
9586           xsnprintf (rs->buf, get_remote_packet_size (),
9587                      "QSetWorkingDir:");
9588         }
9589
9590       putpkt (rs->buf);
9591       getpkt (&rs->buf, &rs->buf_size, 0);
9592       if (packet_ok (rs->buf,
9593                      &remote_protocol_packets[PACKET_QSetWorkingDir])
9594           != PACKET_OK)
9595         error (_("\
9596 Remote replied unexpectedly while setting the inferior's working\n\
9597 directory: %s"),
9598                rs->buf);
9599
9600     }
9601 }
9602
9603 /* In the extended protocol we want to be able to do things like
9604    "run" and have them basically work as expected.  So we need
9605    a special create_inferior function.  We support changing the
9606    executable file and the command line arguments, but not the
9607    environment.  */
9608
9609 static void
9610 extended_remote_create_inferior (struct target_ops *ops,
9611                                  const char *exec_file,
9612                                  const std::string &args,
9613                                  char **env, int from_tty)
9614 {
9615   int run_worked;
9616   char *stop_reply;
9617   struct remote_state *rs = get_remote_state ();
9618   const char *remote_exec_file = get_remote_exec_file ();
9619
9620   /* If running asynchronously, register the target file descriptor
9621      with the event loop.  */
9622   if (target_can_async_p ())
9623     target_async (1);
9624
9625   /* Disable address space randomization if requested (and supported).  */
9626   if (extended_remote_supports_disable_randomization (ops))
9627     extended_remote_disable_randomization (disable_randomization);
9628
9629   /* If startup-with-shell is on, we inform gdbserver to start the
9630      remote inferior using a shell.  */
9631   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
9632     {
9633       xsnprintf (rs->buf, get_remote_packet_size (),
9634                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
9635       putpkt (rs->buf);
9636       getpkt (&rs->buf, &rs->buf_size, 0);
9637       if (strcmp (rs->buf, "OK") != 0)
9638         error (_("\
9639 Remote replied unexpectedly while setting startup-with-shell: %s"),
9640                rs->buf);
9641     }
9642
9643   extended_remote_environment_support (rs);
9644
9645   extended_remote_set_inferior_cwd (rs);
9646
9647   /* Now restart the remote server.  */
9648   run_worked = extended_remote_run (args) != -1;
9649   if (!run_worked)
9650     {
9651       /* vRun was not supported.  Fail if we need it to do what the
9652          user requested.  */
9653       if (remote_exec_file[0])
9654         error (_("Remote target does not support \"set remote exec-file\""));
9655       if (!args.empty ())
9656         error (_("Remote target does not support \"set args\" or run <ARGS>"));
9657
9658       /* Fall back to "R".  */
9659       extended_remote_restart ();
9660     }
9661
9662   if (!have_inferiors ())
9663     {
9664       /* Clean up from the last time we ran, before we mark the target
9665          running again.  This will mark breakpoints uninserted, and
9666          get_offsets may insert breakpoints.  */
9667       init_thread_list ();
9668       init_wait_for_inferior ();
9669     }
9670
9671   /* vRun's success return is a stop reply.  */
9672   stop_reply = run_worked ? rs->buf : NULL;
9673   add_current_inferior_and_thread (stop_reply);
9674
9675   /* Get updated offsets, if the stub uses qOffsets.  */
9676   get_offsets ();
9677 }
9678 \f
9679
9680 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
9681    the list of conditions (in agent expression bytecode format), if any, the
9682    target needs to evaluate.  The output is placed into the packet buffer
9683    started from BUF and ended at BUF_END.  */
9684
9685 static int
9686 remote_add_target_side_condition (struct gdbarch *gdbarch,
9687                                   struct bp_target_info *bp_tgt, char *buf,
9688                                   char *buf_end)
9689 {
9690   if (bp_tgt->conditions.empty ())
9691     return 0;
9692
9693   buf += strlen (buf);
9694   xsnprintf (buf, buf_end - buf, "%s", ";");
9695   buf++;
9696
9697   /* Send conditions to the target.  */
9698   for (agent_expr *aexpr : bp_tgt->conditions)
9699     {
9700       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
9701       buf += strlen (buf);
9702       for (int i = 0; i < aexpr->len; ++i)
9703         buf = pack_hex_byte (buf, aexpr->buf[i]);
9704       *buf = '\0';
9705     }
9706   return 0;
9707 }
9708
9709 static void
9710 remote_add_target_side_commands (struct gdbarch *gdbarch,
9711                                  struct bp_target_info *bp_tgt, char *buf)
9712 {
9713   if (bp_tgt->tcommands.empty ())
9714     return;
9715
9716   buf += strlen (buf);
9717
9718   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
9719   buf += strlen (buf);
9720
9721   /* Concatenate all the agent expressions that are commands into the
9722      cmds parameter.  */
9723   for (agent_expr *aexpr : bp_tgt->tcommands)
9724     {
9725       sprintf (buf, "X%x,", aexpr->len);
9726       buf += strlen (buf);
9727       for (int i = 0; i < aexpr->len; ++i)
9728         buf = pack_hex_byte (buf, aexpr->buf[i]);
9729       *buf = '\0';
9730     }
9731 }
9732
9733 /* Insert a breakpoint.  On targets that have software breakpoint
9734    support, we ask the remote target to do the work; on targets
9735    which don't, we insert a traditional memory breakpoint.  */
9736
9737 static int
9738 remote_insert_breakpoint (struct target_ops *ops,
9739                           struct gdbarch *gdbarch,
9740                           struct bp_target_info *bp_tgt)
9741 {
9742   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
9743      If it succeeds, then set the support to PACKET_ENABLE.  If it
9744      fails, and the user has explicitly requested the Z support then
9745      report an error, otherwise, mark it disabled and go on.  */
9746
9747   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9748     {
9749       CORE_ADDR addr = bp_tgt->reqstd_address;
9750       struct remote_state *rs;
9751       char *p, *endbuf;
9752
9753       /* Make sure the remote is pointing at the right process, if
9754          necessary.  */
9755       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9756         set_general_process ();
9757
9758       rs = get_remote_state ();
9759       p = rs->buf;
9760       endbuf = rs->buf + get_remote_packet_size ();
9761
9762       *(p++) = 'Z';
9763       *(p++) = '0';
9764       *(p++) = ',';
9765       addr = (ULONGEST) remote_address_masked (addr);
9766       p += hexnumstr (p, addr);
9767       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9768
9769       if (remote_supports_cond_breakpoints (ops))
9770         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
9771
9772       if (remote_can_run_breakpoint_commands (ops))
9773         remote_add_target_side_commands (gdbarch, bp_tgt, p);
9774
9775       putpkt (rs->buf);
9776       getpkt (&rs->buf, &rs->buf_size, 0);
9777
9778       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
9779         {
9780         case PACKET_ERROR:
9781           return -1;
9782         case PACKET_OK:
9783           return 0;
9784         case PACKET_UNKNOWN:
9785           break;
9786         }
9787     }
9788
9789   /* If this breakpoint has target-side commands but this stub doesn't
9790      support Z0 packets, throw error.  */
9791   if (!bp_tgt->tcommands.empty ())
9792     throw_error (NOT_SUPPORTED_ERROR, _("\
9793 Target doesn't support breakpoints that have target side commands."));
9794
9795   return memory_insert_breakpoint (ops, gdbarch, bp_tgt);
9796 }
9797
9798 static int
9799 remote_remove_breakpoint (struct target_ops *ops,
9800                           struct gdbarch *gdbarch,
9801                           struct bp_target_info *bp_tgt,
9802                           enum remove_bp_reason reason)
9803 {
9804   CORE_ADDR addr = bp_tgt->placed_address;
9805   struct remote_state *rs = get_remote_state ();
9806
9807   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
9808     {
9809       char *p = rs->buf;
9810       char *endbuf = rs->buf + get_remote_packet_size ();
9811
9812       /* Make sure the remote is pointing at the right process, if
9813          necessary.  */
9814       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9815         set_general_process ();
9816
9817       *(p++) = 'z';
9818       *(p++) = '0';
9819       *(p++) = ',';
9820
9821       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
9822       p += hexnumstr (p, addr);
9823       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
9824
9825       putpkt (rs->buf);
9826       getpkt (&rs->buf, &rs->buf_size, 0);
9827
9828       return (rs->buf[0] == 'E');
9829     }
9830
9831   return memory_remove_breakpoint (ops, gdbarch, bp_tgt, reason);
9832 }
9833
9834 static enum Z_packet_type
9835 watchpoint_to_Z_packet (int type)
9836 {
9837   switch (type)
9838     {
9839     case hw_write:
9840       return Z_PACKET_WRITE_WP;
9841       break;
9842     case hw_read:
9843       return Z_PACKET_READ_WP;
9844       break;
9845     case hw_access:
9846       return Z_PACKET_ACCESS_WP;
9847       break;
9848     default:
9849       internal_error (__FILE__, __LINE__,
9850                       _("hw_bp_to_z: bad watchpoint type %d"), type);
9851     }
9852 }
9853
9854 static int
9855 remote_insert_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9856                           enum target_hw_bp_type type, struct expression *cond)
9857 {
9858   struct remote_state *rs = get_remote_state ();
9859   char *endbuf = rs->buf + get_remote_packet_size ();
9860   char *p;
9861   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9862
9863   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9864     return 1;
9865
9866   /* Make sure the remote is pointing at the right process, if
9867      necessary.  */
9868   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9869     set_general_process ();
9870
9871   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
9872   p = strchr (rs->buf, '\0');
9873   addr = remote_address_masked (addr);
9874   p += hexnumstr (p, (ULONGEST) addr);
9875   xsnprintf (p, endbuf - p, ",%x", len);
9876
9877   putpkt (rs->buf);
9878   getpkt (&rs->buf, &rs->buf_size, 0);
9879
9880   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9881     {
9882     case PACKET_ERROR:
9883       return -1;
9884     case PACKET_UNKNOWN:
9885       return 1;
9886     case PACKET_OK:
9887       return 0;
9888     }
9889   internal_error (__FILE__, __LINE__,
9890                   _("remote_insert_watchpoint: reached end of function"));
9891 }
9892
9893 static int
9894 remote_watchpoint_addr_within_range (struct target_ops *target, CORE_ADDR addr,
9895                                      CORE_ADDR start, int length)
9896 {
9897   CORE_ADDR diff = remote_address_masked (addr - start);
9898
9899   return diff < length;
9900 }
9901
9902
9903 static int
9904 remote_remove_watchpoint (struct target_ops *self, CORE_ADDR addr, int len,
9905                           enum target_hw_bp_type type, struct expression *cond)
9906 {
9907   struct remote_state *rs = get_remote_state ();
9908   char *endbuf = rs->buf + get_remote_packet_size ();
9909   char *p;
9910   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
9911
9912   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
9913     return -1;
9914
9915   /* Make sure the remote is pointing at the right process, if
9916      necessary.  */
9917   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
9918     set_general_process ();
9919
9920   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
9921   p = strchr (rs->buf, '\0');
9922   addr = remote_address_masked (addr);
9923   p += hexnumstr (p, (ULONGEST) addr);
9924   xsnprintf (p, endbuf - p, ",%x", len);
9925   putpkt (rs->buf);
9926   getpkt (&rs->buf, &rs->buf_size, 0);
9927
9928   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
9929     {
9930     case PACKET_ERROR:
9931     case PACKET_UNKNOWN:
9932       return -1;
9933     case PACKET_OK:
9934       return 0;
9935     }
9936   internal_error (__FILE__, __LINE__,
9937                   _("remote_remove_watchpoint: reached end of function"));
9938 }
9939
9940
9941 int remote_hw_watchpoint_limit = -1;
9942 int remote_hw_watchpoint_length_limit = -1;
9943 int remote_hw_breakpoint_limit = -1;
9944
9945 static int
9946 remote_region_ok_for_hw_watchpoint (struct target_ops *self,
9947                                     CORE_ADDR addr, int len)
9948 {
9949   if (remote_hw_watchpoint_length_limit == 0)
9950     return 0;
9951   else if (remote_hw_watchpoint_length_limit < 0)
9952     return 1;
9953   else if (len <= remote_hw_watchpoint_length_limit)
9954     return 1;
9955   else
9956     return 0;
9957 }
9958
9959 static int
9960 remote_check_watch_resources (struct target_ops *self,
9961                               enum bptype type, int cnt, int ot)
9962 {
9963   if (type == bp_hardware_breakpoint)
9964     {
9965       if (remote_hw_breakpoint_limit == 0)
9966         return 0;
9967       else if (remote_hw_breakpoint_limit < 0)
9968         return 1;
9969       else if (cnt <= remote_hw_breakpoint_limit)
9970         return 1;
9971     }
9972   else
9973     {
9974       if (remote_hw_watchpoint_limit == 0)
9975         return 0;
9976       else if (remote_hw_watchpoint_limit < 0)
9977         return 1;
9978       else if (ot)
9979         return -1;
9980       else if (cnt <= remote_hw_watchpoint_limit)
9981         return 1;
9982     }
9983   return -1;
9984 }
9985
9986 /* The to_stopped_by_sw_breakpoint method of target remote.  */
9987
9988 static int
9989 remote_stopped_by_sw_breakpoint (struct target_ops *ops)
9990 {
9991   struct thread_info *thread = inferior_thread ();
9992
9993   return (thread->priv != NULL
9994           && (get_remote_thread_info (thread)->stop_reason
9995               == TARGET_STOPPED_BY_SW_BREAKPOINT));
9996 }
9997
9998 /* The to_supports_stopped_by_sw_breakpoint method of target
9999    remote.  */
10000
10001 static int
10002 remote_supports_stopped_by_sw_breakpoint (struct target_ops *ops)
10003 {
10004   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10005 }
10006
10007 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10008
10009 static int
10010 remote_stopped_by_hw_breakpoint (struct target_ops *ops)
10011 {
10012   struct thread_info *thread = inferior_thread ();
10013
10014   return (thread->priv != NULL
10015           && (get_remote_thread_info (thread)->stop_reason
10016               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10017 }
10018
10019 /* The to_supports_stopped_by_hw_breakpoint method of target
10020    remote.  */
10021
10022 static int
10023 remote_supports_stopped_by_hw_breakpoint (struct target_ops *ops)
10024 {
10025   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10026 }
10027
10028 static int
10029 remote_stopped_by_watchpoint (struct target_ops *ops)
10030 {
10031   struct thread_info *thread = inferior_thread ();
10032
10033   return (thread->priv != NULL
10034           && (get_remote_thread_info (thread)->stop_reason
10035               == TARGET_STOPPED_BY_WATCHPOINT));
10036 }
10037
10038 static int
10039 remote_stopped_data_address (struct target_ops *target, CORE_ADDR *addr_p)
10040 {
10041   struct thread_info *thread = inferior_thread ();
10042
10043   if (thread->priv != NULL
10044       && (get_remote_thread_info (thread)->stop_reason
10045           == TARGET_STOPPED_BY_WATCHPOINT))
10046     {
10047       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10048       return 1;
10049     }
10050
10051   return 0;
10052 }
10053
10054
10055 static int
10056 remote_insert_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10057                              struct bp_target_info *bp_tgt)
10058 {
10059   CORE_ADDR addr = bp_tgt->reqstd_address;
10060   struct remote_state *rs;
10061   char *p, *endbuf;
10062   char *message;
10063
10064   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10065     return -1;
10066
10067   /* Make sure the remote is pointing at the right process, if
10068      necessary.  */
10069   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10070     set_general_process ();
10071
10072   rs = get_remote_state ();
10073   p = rs->buf;
10074   endbuf = rs->buf + get_remote_packet_size ();
10075
10076   *(p++) = 'Z';
10077   *(p++) = '1';
10078   *(p++) = ',';
10079
10080   addr = remote_address_masked (addr);
10081   p += hexnumstr (p, (ULONGEST) addr);
10082   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10083
10084   if (remote_supports_cond_breakpoints (self))
10085     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10086
10087   if (remote_can_run_breakpoint_commands (self))
10088     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10089
10090   putpkt (rs->buf);
10091   getpkt (&rs->buf, &rs->buf_size, 0);
10092
10093   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10094     {
10095     case PACKET_ERROR:
10096       if (rs->buf[1] == '.')
10097         {
10098           message = strchr (rs->buf + 2, '.');
10099           if (message)
10100             error (_("Remote failure reply: %s"), message + 1);
10101         }
10102       return -1;
10103     case PACKET_UNKNOWN:
10104       return -1;
10105     case PACKET_OK:
10106       return 0;
10107     }
10108   internal_error (__FILE__, __LINE__,
10109                   _("remote_insert_hw_breakpoint: reached end of function"));
10110 }
10111
10112
10113 static int
10114 remote_remove_hw_breakpoint (struct target_ops *self, struct gdbarch *gdbarch,
10115                              struct bp_target_info *bp_tgt)
10116 {
10117   CORE_ADDR addr;
10118   struct remote_state *rs = get_remote_state ();
10119   char *p = rs->buf;
10120   char *endbuf = rs->buf + get_remote_packet_size ();
10121
10122   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10123     return -1;
10124
10125   /* Make sure the remote is pointing at the right process, if
10126      necessary.  */
10127   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10128     set_general_process ();
10129
10130   *(p++) = 'z';
10131   *(p++) = '1';
10132   *(p++) = ',';
10133
10134   addr = remote_address_masked (bp_tgt->placed_address);
10135   p += hexnumstr (p, (ULONGEST) addr);
10136   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10137
10138   putpkt (rs->buf);
10139   getpkt (&rs->buf, &rs->buf_size, 0);
10140
10141   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10142     {
10143     case PACKET_ERROR:
10144     case PACKET_UNKNOWN:
10145       return -1;
10146     case PACKET_OK:
10147       return 0;
10148     }
10149   internal_error (__FILE__, __LINE__,
10150                   _("remote_remove_hw_breakpoint: reached end of function"));
10151 }
10152
10153 /* Verify memory using the "qCRC:" request.  */
10154
10155 static int
10156 remote_verify_memory (struct target_ops *ops,
10157                       const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10158 {
10159   struct remote_state *rs = get_remote_state ();
10160   unsigned long host_crc, target_crc;
10161   char *tmp;
10162
10163   /* It doesn't make sense to use qCRC if the remote target is
10164      connected but not running.  */
10165   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10166     {
10167       enum packet_result result;
10168
10169       /* Make sure the remote is pointing at the right process.  */
10170       set_general_process ();
10171
10172       /* FIXME: assumes lma can fit into long.  */
10173       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10174                  (long) lma, (long) size);
10175       putpkt (rs->buf);
10176
10177       /* Be clever; compute the host_crc before waiting for target
10178          reply.  */
10179       host_crc = xcrc32 (data, size, 0xffffffff);
10180
10181       getpkt (&rs->buf, &rs->buf_size, 0);
10182
10183       result = packet_ok (rs->buf,
10184                           &remote_protocol_packets[PACKET_qCRC]);
10185       if (result == PACKET_ERROR)
10186         return -1;
10187       else if (result == PACKET_OK)
10188         {
10189           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10190             target_crc = target_crc * 16 + fromhex (*tmp);
10191
10192           return (host_crc == target_crc);
10193         }
10194     }
10195
10196   return simple_verify_memory (ops, data, lma, size);
10197 }
10198
10199 /* compare-sections command
10200
10201    With no arguments, compares each loadable section in the exec bfd
10202    with the same memory range on the target, and reports mismatches.
10203    Useful for verifying the image on the target against the exec file.  */
10204
10205 static void
10206 compare_sections_command (const char *args, int from_tty)
10207 {
10208   asection *s;
10209   const char *sectname;
10210   bfd_size_type size;
10211   bfd_vma lma;
10212   int matched = 0;
10213   int mismatched = 0;
10214   int res;
10215   int read_only = 0;
10216
10217   if (!exec_bfd)
10218     error (_("command cannot be used without an exec file"));
10219
10220   /* Make sure the remote is pointing at the right process.  */
10221   set_general_process ();
10222
10223   if (args != NULL && strcmp (args, "-r") == 0)
10224     {
10225       read_only = 1;
10226       args = NULL;
10227     }
10228
10229   for (s = exec_bfd->sections; s; s = s->next)
10230     {
10231       if (!(s->flags & SEC_LOAD))
10232         continue;               /* Skip non-loadable section.  */
10233
10234       if (read_only && (s->flags & SEC_READONLY) == 0)
10235         continue;               /* Skip writeable sections */
10236
10237       size = bfd_get_section_size (s);
10238       if (size == 0)
10239         continue;               /* Skip zero-length section.  */
10240
10241       sectname = bfd_get_section_name (exec_bfd, s);
10242       if (args && strcmp (args, sectname) != 0)
10243         continue;               /* Not the section selected by user.  */
10244
10245       matched = 1;              /* Do this section.  */
10246       lma = s->lma;
10247
10248       gdb::byte_vector sectdata (size);
10249       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10250
10251       res = target_verify_memory (sectdata.data (), lma, size);
10252
10253       if (res == -1)
10254         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10255                paddress (target_gdbarch (), lma),
10256                paddress (target_gdbarch (), lma + size));
10257
10258       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10259                        paddress (target_gdbarch (), lma),
10260                        paddress (target_gdbarch (), lma + size));
10261       if (res)
10262         printf_filtered ("matched.\n");
10263       else
10264         {
10265           printf_filtered ("MIS-MATCHED!\n");
10266           mismatched++;
10267         }
10268     }
10269   if (mismatched > 0)
10270     warning (_("One or more sections of the target image does not match\n\
10271 the loaded file\n"));
10272   if (args && !matched)
10273     printf_filtered (_("No loaded section named '%s'.\n"), args);
10274 }
10275
10276 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10277    into remote target.  The number of bytes written to the remote
10278    target is returned, or -1 for error.  */
10279
10280 static enum target_xfer_status
10281 remote_write_qxfer (struct target_ops *ops, const char *object_name,
10282                     const char *annex, const gdb_byte *writebuf, 
10283                     ULONGEST offset, LONGEST len, ULONGEST *xfered_len,
10284                     struct packet_config *packet)
10285 {
10286   int i, buf_len;
10287   ULONGEST n;
10288   struct remote_state *rs = get_remote_state ();
10289   int max_size = get_memory_write_packet_size (); 
10290
10291   if (packet_config_support (packet) == PACKET_DISABLE)
10292     return TARGET_XFER_E_IO;
10293
10294   /* Insert header.  */
10295   i = snprintf (rs->buf, max_size, 
10296                 "qXfer:%s:write:%s:%s:",
10297                 object_name, annex ? annex : "",
10298                 phex_nz (offset, sizeof offset));
10299   max_size -= (i + 1);
10300
10301   /* Escape as much data as fits into rs->buf.  */
10302   buf_len = remote_escape_output 
10303     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10304
10305   if (putpkt_binary (rs->buf, i + buf_len) < 0
10306       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10307       || packet_ok (rs->buf, packet) != PACKET_OK)
10308     return TARGET_XFER_E_IO;
10309
10310   unpack_varlen_hex (rs->buf, &n);
10311
10312   *xfered_len = n;
10313   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10314 }
10315
10316 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10317    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10318    number of bytes read is returned, or 0 for EOF, or -1 for error.
10319    The number of bytes read may be less than LEN without indicating an
10320    EOF.  PACKET is checked and updated to indicate whether the remote
10321    target supports this object.  */
10322
10323 static enum target_xfer_status
10324 remote_read_qxfer (struct target_ops *ops, const char *object_name,
10325                    const char *annex,
10326                    gdb_byte *readbuf, ULONGEST offset, LONGEST len,
10327                    ULONGEST *xfered_len,
10328                    struct packet_config *packet)
10329 {
10330   struct remote_state *rs = get_remote_state ();
10331   LONGEST i, n, packet_len;
10332
10333   if (packet_config_support (packet) == PACKET_DISABLE)
10334     return TARGET_XFER_E_IO;
10335
10336   /* Check whether we've cached an end-of-object packet that matches
10337      this request.  */
10338   if (rs->finished_object)
10339     {
10340       if (strcmp (object_name, rs->finished_object) == 0
10341           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10342           && offset == rs->finished_offset)
10343         return TARGET_XFER_EOF;
10344
10345
10346       /* Otherwise, we're now reading something different.  Discard
10347          the cache.  */
10348       xfree (rs->finished_object);
10349       xfree (rs->finished_annex);
10350       rs->finished_object = NULL;
10351       rs->finished_annex = NULL;
10352     }
10353
10354   /* Request only enough to fit in a single packet.  The actual data
10355      may not, since we don't know how much of it will need to be escaped;
10356      the target is free to respond with slightly less data.  We subtract
10357      five to account for the response type and the protocol frame.  */
10358   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10359   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10360             object_name, annex ? annex : "",
10361             phex_nz (offset, sizeof offset),
10362             phex_nz (n, sizeof n));
10363   i = putpkt (rs->buf);
10364   if (i < 0)
10365     return TARGET_XFER_E_IO;
10366
10367   rs->buf[0] = '\0';
10368   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10369   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10370     return TARGET_XFER_E_IO;
10371
10372   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10373     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10374
10375   /* 'm' means there is (or at least might be) more data after this
10376      batch.  That does not make sense unless there's at least one byte
10377      of data in this reply.  */
10378   if (rs->buf[0] == 'm' && packet_len == 1)
10379     error (_("Remote qXfer reply contained no data."));
10380
10381   /* Got some data.  */
10382   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10383                              packet_len - 1, readbuf, n);
10384
10385   /* 'l' is an EOF marker, possibly including a final block of data,
10386      or possibly empty.  If we have the final block of a non-empty
10387      object, record this fact to bypass a subsequent partial read.  */
10388   if (rs->buf[0] == 'l' && offset + i > 0)
10389     {
10390       rs->finished_object = xstrdup (object_name);
10391       rs->finished_annex = xstrdup (annex ? annex : "");
10392       rs->finished_offset = offset + i;
10393     }
10394
10395   if (i == 0)
10396     return TARGET_XFER_EOF;
10397   else
10398     {
10399       *xfered_len = i;
10400       return TARGET_XFER_OK;
10401     }
10402 }
10403
10404 static enum target_xfer_status
10405 remote_xfer_partial (struct target_ops *ops, enum target_object object,
10406                      const char *annex, gdb_byte *readbuf,
10407                      const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10408                      ULONGEST *xfered_len)
10409 {
10410   struct remote_state *rs;
10411   int i;
10412   char *p2;
10413   char query_type;
10414   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10415
10416   set_remote_traceframe ();
10417   set_general_thread (inferior_ptid);
10418
10419   rs = get_remote_state ();
10420
10421   /* Handle memory using the standard memory routines.  */
10422   if (object == TARGET_OBJECT_MEMORY)
10423     {
10424       /* If the remote target is connected but not running, we should
10425          pass this request down to a lower stratum (e.g. the executable
10426          file).  */
10427       if (!target_has_execution)
10428         return TARGET_XFER_EOF;
10429
10430       if (writebuf != NULL)
10431         return remote_write_bytes (offset, writebuf, len, unit_size,
10432                                    xfered_len);
10433       else
10434         return remote_read_bytes (ops, offset, readbuf, len, unit_size,
10435                                   xfered_len);
10436     }
10437
10438   /* Handle SPU memory using qxfer packets.  */
10439   if (object == TARGET_OBJECT_SPU)
10440     {
10441       if (readbuf)
10442         return remote_read_qxfer (ops, "spu", annex, readbuf, offset, len,
10443                                   xfered_len, &remote_protocol_packets
10444                                   [PACKET_qXfer_spu_read]);
10445       else
10446         return remote_write_qxfer (ops, "spu", annex, writebuf, offset, len,
10447                                    xfered_len, &remote_protocol_packets
10448                                    [PACKET_qXfer_spu_write]);
10449     }
10450
10451   /* Handle extra signal info using qxfer packets.  */
10452   if (object == TARGET_OBJECT_SIGNAL_INFO)
10453     {
10454       if (readbuf)
10455         return remote_read_qxfer (ops, "siginfo", annex, readbuf, offset, len,
10456                                   xfered_len, &remote_protocol_packets
10457                                   [PACKET_qXfer_siginfo_read]);
10458       else
10459         return remote_write_qxfer (ops, "siginfo", annex,
10460                                    writebuf, offset, len, xfered_len,
10461                                    &remote_protocol_packets
10462                                    [PACKET_qXfer_siginfo_write]);
10463     }
10464
10465   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10466     {
10467       if (readbuf)
10468         return remote_read_qxfer (ops, "statictrace", annex,
10469                                   readbuf, offset, len, xfered_len,
10470                                   &remote_protocol_packets
10471                                   [PACKET_qXfer_statictrace_read]);
10472       else
10473         return TARGET_XFER_E_IO;
10474     }
10475
10476   /* Only handle flash writes.  */
10477   if (writebuf != NULL)
10478     {
10479       switch (object)
10480         {
10481         case TARGET_OBJECT_FLASH:
10482           return remote_flash_write (ops, offset, len, xfered_len,
10483                                      writebuf);
10484
10485         default:
10486           return TARGET_XFER_E_IO;
10487         }
10488     }
10489
10490   /* Map pre-existing objects onto letters.  DO NOT do this for new
10491      objects!!!  Instead specify new query packets.  */
10492   switch (object)
10493     {
10494     case TARGET_OBJECT_AVR:
10495       query_type = 'R';
10496       break;
10497
10498     case TARGET_OBJECT_AUXV:
10499       gdb_assert (annex == NULL);
10500       return remote_read_qxfer (ops, "auxv", annex, readbuf, offset, len,
10501                                 xfered_len,
10502                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10503
10504     case TARGET_OBJECT_AVAILABLE_FEATURES:
10505       return remote_read_qxfer
10506         (ops, "features", annex, readbuf, offset, len, xfered_len,
10507          &remote_protocol_packets[PACKET_qXfer_features]);
10508
10509     case TARGET_OBJECT_LIBRARIES:
10510       return remote_read_qxfer
10511         (ops, "libraries", annex, readbuf, offset, len, xfered_len,
10512          &remote_protocol_packets[PACKET_qXfer_libraries]);
10513
10514     case TARGET_OBJECT_LIBRARIES_SVR4:
10515       return remote_read_qxfer
10516         (ops, "libraries-svr4", annex, readbuf, offset, len, xfered_len,
10517          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10518
10519     case TARGET_OBJECT_MEMORY_MAP:
10520       gdb_assert (annex == NULL);
10521       return remote_read_qxfer (ops, "memory-map", annex, readbuf, offset, len,
10522                                  xfered_len,
10523                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10524
10525     case TARGET_OBJECT_OSDATA:
10526       /* Should only get here if we're connected.  */
10527       gdb_assert (rs->remote_desc);
10528       return remote_read_qxfer
10529         (ops, "osdata", annex, readbuf, offset, len, xfered_len,
10530         &remote_protocol_packets[PACKET_qXfer_osdata]);
10531
10532     case TARGET_OBJECT_THREADS:
10533       gdb_assert (annex == NULL);
10534       return remote_read_qxfer (ops, "threads", annex, readbuf, offset, len,
10535                                 xfered_len,
10536                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10537
10538     case TARGET_OBJECT_TRACEFRAME_INFO:
10539       gdb_assert (annex == NULL);
10540       return remote_read_qxfer
10541         (ops, "traceframe-info", annex, readbuf, offset, len, xfered_len,
10542          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10543
10544     case TARGET_OBJECT_FDPIC:
10545       return remote_read_qxfer (ops, "fdpic", annex, readbuf, offset, len,
10546                                 xfered_len,
10547                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10548
10549     case TARGET_OBJECT_OPENVMS_UIB:
10550       return remote_read_qxfer (ops, "uib", annex, readbuf, offset, len,
10551                                 xfered_len,
10552                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10553
10554     case TARGET_OBJECT_BTRACE:
10555       return remote_read_qxfer (ops, "btrace", annex, readbuf, offset, len,
10556                                 xfered_len,
10557         &remote_protocol_packets[PACKET_qXfer_btrace]);
10558
10559     case TARGET_OBJECT_BTRACE_CONF:
10560       return remote_read_qxfer (ops, "btrace-conf", annex, readbuf, offset,
10561                                 len, xfered_len,
10562         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
10563
10564     case TARGET_OBJECT_EXEC_FILE:
10565       return remote_read_qxfer (ops, "exec-file", annex, readbuf, offset,
10566                                 len, xfered_len,
10567         &remote_protocol_packets[PACKET_qXfer_exec_file]);
10568
10569     default:
10570       return TARGET_XFER_E_IO;
10571     }
10572
10573   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
10574      large enough let the caller deal with it.  */
10575   if (len < get_remote_packet_size ())
10576     return TARGET_XFER_E_IO;
10577   len = get_remote_packet_size ();
10578
10579   /* Except for querying the minimum buffer size, target must be open.  */
10580   if (!rs->remote_desc)
10581     error (_("remote query is only available after target open"));
10582
10583   gdb_assert (annex != NULL);
10584   gdb_assert (readbuf != NULL);
10585
10586   p2 = rs->buf;
10587   *p2++ = 'q';
10588   *p2++ = query_type;
10589
10590   /* We used one buffer char for the remote protocol q command and
10591      another for the query type.  As the remote protocol encapsulation
10592      uses 4 chars plus one extra in case we are debugging
10593      (remote_debug), we have PBUFZIZ - 7 left to pack the query
10594      string.  */
10595   i = 0;
10596   while (annex[i] && (i < (get_remote_packet_size () - 8)))
10597     {
10598       /* Bad caller may have sent forbidden characters.  */
10599       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
10600       *p2++ = annex[i];
10601       i++;
10602     }
10603   *p2 = '\0';
10604   gdb_assert (annex[i] == '\0');
10605
10606   i = putpkt (rs->buf);
10607   if (i < 0)
10608     return TARGET_XFER_E_IO;
10609
10610   getpkt (&rs->buf, &rs->buf_size, 0);
10611   strcpy ((char *) readbuf, rs->buf);
10612
10613   *xfered_len = strlen ((char *) readbuf);
10614   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10615 }
10616
10617 /* Implementation of to_get_memory_xfer_limit.  */
10618
10619 static ULONGEST
10620 remote_get_memory_xfer_limit (struct target_ops *ops)
10621 {
10622   return get_memory_write_packet_size ();
10623 }
10624
10625 static int
10626 remote_search_memory (struct target_ops* ops,
10627                       CORE_ADDR start_addr, ULONGEST search_space_len,
10628                       const gdb_byte *pattern, ULONGEST pattern_len,
10629                       CORE_ADDR *found_addrp)
10630 {
10631   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
10632   struct remote_state *rs = get_remote_state ();
10633   int max_size = get_memory_write_packet_size ();
10634   struct packet_config *packet =
10635     &remote_protocol_packets[PACKET_qSearch_memory];
10636   /* Number of packet bytes used to encode the pattern;
10637      this could be more than PATTERN_LEN due to escape characters.  */
10638   int escaped_pattern_len;
10639   /* Amount of pattern that was encodable in the packet.  */
10640   int used_pattern_len;
10641   int i;
10642   int found;
10643   ULONGEST found_addr;
10644
10645   /* Don't go to the target if we don't have to.  This is done before
10646      checking packet_config_support to avoid the possibility that a
10647      success for this edge case means the facility works in
10648      general.  */
10649   if (pattern_len > search_space_len)
10650     return 0;
10651   if (pattern_len == 0)
10652     {
10653       *found_addrp = start_addr;
10654       return 1;
10655     }
10656
10657   /* If we already know the packet isn't supported, fall back to the simple
10658      way of searching memory.  */
10659
10660   if (packet_config_support (packet) == PACKET_DISABLE)
10661     {
10662       /* Target doesn't provided special support, fall back and use the
10663          standard support (copy memory and do the search here).  */
10664       return simple_search_memory (ops, start_addr, search_space_len,
10665                                    pattern, pattern_len, found_addrp);
10666     }
10667
10668   /* Make sure the remote is pointing at the right process.  */
10669   set_general_process ();
10670
10671   /* Insert header.  */
10672   i = snprintf (rs->buf, max_size, 
10673                 "qSearch:memory:%s;%s;",
10674                 phex_nz (start_addr, addr_size),
10675                 phex_nz (search_space_len, sizeof (search_space_len)));
10676   max_size -= (i + 1);
10677
10678   /* Escape as much data as fits into rs->buf.  */
10679   escaped_pattern_len =
10680     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
10681                           &used_pattern_len, max_size);
10682
10683   /* Bail if the pattern is too large.  */
10684   if (used_pattern_len != pattern_len)
10685     error (_("Pattern is too large to transmit to remote target."));
10686
10687   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
10688       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10689       || packet_ok (rs->buf, packet) != PACKET_OK)
10690     {
10691       /* The request may not have worked because the command is not
10692          supported.  If so, fall back to the simple way.  */
10693       if (packet_config_support (packet) == PACKET_DISABLE)
10694         {
10695           return simple_search_memory (ops, start_addr, search_space_len,
10696                                        pattern, pattern_len, found_addrp);
10697         }
10698       return -1;
10699     }
10700
10701   if (rs->buf[0] == '0')
10702     found = 0;
10703   else if (rs->buf[0] == '1')
10704     {
10705       found = 1;
10706       if (rs->buf[1] != ',')
10707         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10708       unpack_varlen_hex (rs->buf + 2, &found_addr);
10709       *found_addrp = found_addr;
10710     }
10711   else
10712     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
10713
10714   return found;
10715 }
10716
10717 static void
10718 remote_rcmd (struct target_ops *self, const char *command,
10719              struct ui_file *outbuf)
10720 {
10721   struct remote_state *rs = get_remote_state ();
10722   char *p = rs->buf;
10723
10724   if (!rs->remote_desc)
10725     error (_("remote rcmd is only available after target open"));
10726
10727   /* Send a NULL command across as an empty command.  */
10728   if (command == NULL)
10729     command = "";
10730
10731   /* The query prefix.  */
10732   strcpy (rs->buf, "qRcmd,");
10733   p = strchr (rs->buf, '\0');
10734
10735   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
10736       > get_remote_packet_size ())
10737     error (_("\"monitor\" command ``%s'' is too long."), command);
10738
10739   /* Encode the actual command.  */
10740   bin2hex ((const gdb_byte *) command, p, strlen (command));
10741
10742   if (putpkt (rs->buf) < 0)
10743     error (_("Communication problem with target."));
10744
10745   /* get/display the response */
10746   while (1)
10747     {
10748       char *buf;
10749
10750       /* XXX - see also remote_get_noisy_reply().  */
10751       QUIT;                     /* Allow user to bail out with ^C.  */
10752       rs->buf[0] = '\0';
10753       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
10754         { 
10755           /* Timeout.  Continue to (try to) read responses.
10756              This is better than stopping with an error, assuming the stub
10757              is still executing the (long) monitor command.
10758              If needed, the user can interrupt gdb using C-c, obtaining
10759              an effect similar to stop on timeout.  */
10760           continue;
10761         }
10762       buf = rs->buf;
10763       if (buf[0] == '\0')
10764         error (_("Target does not support this command."));
10765       if (buf[0] == 'O' && buf[1] != 'K')
10766         {
10767           remote_console_output (buf + 1); /* 'O' message from stub.  */
10768           continue;
10769         }
10770       if (strcmp (buf, "OK") == 0)
10771         break;
10772       if (strlen (buf) == 3 && buf[0] == 'E'
10773           && isdigit (buf[1]) && isdigit (buf[2]))
10774         {
10775           error (_("Protocol error with Rcmd"));
10776         }
10777       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
10778         {
10779           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
10780
10781           fputc_unfiltered (c, outbuf);
10782         }
10783       break;
10784     }
10785 }
10786
10787 static std::vector<mem_region>
10788 remote_memory_map (struct target_ops *ops)
10789 {
10790   std::vector<mem_region> result;
10791   gdb::optional<gdb::char_vector> text
10792     = target_read_stralloc (&current_target, TARGET_OBJECT_MEMORY_MAP, NULL);
10793
10794   if (text)
10795     result = parse_memory_map (text->data ());
10796
10797   return result;
10798 }
10799
10800 static void
10801 packet_command (const char *args, int from_tty)
10802 {
10803   struct remote_state *rs = get_remote_state ();
10804
10805   if (!rs->remote_desc)
10806     error (_("command can only be used with remote target"));
10807
10808   if (!args)
10809     error (_("remote-packet command requires packet text as argument"));
10810
10811   puts_filtered ("sending: ");
10812   print_packet (args);
10813   puts_filtered ("\n");
10814   putpkt (args);
10815
10816   getpkt (&rs->buf, &rs->buf_size, 0);
10817   puts_filtered ("received: ");
10818   print_packet (rs->buf);
10819   puts_filtered ("\n");
10820 }
10821
10822 #if 0
10823 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
10824
10825 static void display_thread_info (struct gdb_ext_thread_info *info);
10826
10827 static void threadset_test_cmd (char *cmd, int tty);
10828
10829 static void threadalive_test (char *cmd, int tty);
10830
10831 static void threadlist_test_cmd (char *cmd, int tty);
10832
10833 int get_and_display_threadinfo (threadref *ref);
10834
10835 static void threadinfo_test_cmd (char *cmd, int tty);
10836
10837 static int thread_display_step (threadref *ref, void *context);
10838
10839 static void threadlist_update_test_cmd (char *cmd, int tty);
10840
10841 static void init_remote_threadtests (void);
10842
10843 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
10844
10845 static void
10846 threadset_test_cmd (const char *cmd, int tty)
10847 {
10848   int sample_thread = SAMPLE_THREAD;
10849
10850   printf_filtered (_("Remote threadset test\n"));
10851   set_general_thread (sample_thread);
10852 }
10853
10854
10855 static void
10856 threadalive_test (const char *cmd, int tty)
10857 {
10858   int sample_thread = SAMPLE_THREAD;
10859   int pid = ptid_get_pid (inferior_ptid);
10860   ptid_t ptid = ptid_build (pid, sample_thread, 0);
10861
10862   if (remote_thread_alive (ptid))
10863     printf_filtered ("PASS: Thread alive test\n");
10864   else
10865     printf_filtered ("FAIL: Thread alive test\n");
10866 }
10867
10868 void output_threadid (char *title, threadref *ref);
10869
10870 void
10871 output_threadid (char *title, threadref *ref)
10872 {
10873   char hexid[20];
10874
10875   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
10876   hexid[16] = 0;
10877   printf_filtered ("%s  %s\n", title, (&hexid[0]));
10878 }
10879
10880 static void
10881 threadlist_test_cmd (const char *cmd, int tty)
10882 {
10883   int startflag = 1;
10884   threadref nextthread;
10885   int done, result_count;
10886   threadref threadlist[3];
10887
10888   printf_filtered ("Remote Threadlist test\n");
10889   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
10890                               &result_count, &threadlist[0]))
10891     printf_filtered ("FAIL: threadlist test\n");
10892   else
10893     {
10894       threadref *scan = threadlist;
10895       threadref *limit = scan + result_count;
10896
10897       while (scan < limit)
10898         output_threadid (" thread ", scan++);
10899     }
10900 }
10901
10902 void
10903 display_thread_info (struct gdb_ext_thread_info *info)
10904 {
10905   output_threadid ("Threadid: ", &info->threadid);
10906   printf_filtered ("Name: %s\n ", info->shortname);
10907   printf_filtered ("State: %s\n", info->display);
10908   printf_filtered ("other: %s\n\n", info->more_display);
10909 }
10910
10911 int
10912 get_and_display_threadinfo (threadref *ref)
10913 {
10914   int result;
10915   int set;
10916   struct gdb_ext_thread_info threadinfo;
10917
10918   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
10919     | TAG_MOREDISPLAY | TAG_DISPLAY;
10920   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
10921     display_thread_info (&threadinfo);
10922   return result;
10923 }
10924
10925 static void
10926 threadinfo_test_cmd (const char *cmd, int tty)
10927 {
10928   int athread = SAMPLE_THREAD;
10929   threadref thread;
10930   int set;
10931
10932   int_to_threadref (&thread, athread);
10933   printf_filtered ("Remote Threadinfo test\n");
10934   if (!get_and_display_threadinfo (&thread))
10935     printf_filtered ("FAIL cannot get thread info\n");
10936 }
10937
10938 static int
10939 thread_display_step (threadref *ref, void *context)
10940 {
10941   /* output_threadid(" threadstep ",ref); *//* simple test */
10942   return get_and_display_threadinfo (ref);
10943 }
10944
10945 static void
10946 threadlist_update_test_cmd (const char *cmd, int tty)
10947 {
10948   printf_filtered ("Remote Threadlist update test\n");
10949   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
10950 }
10951
10952 static void
10953 init_remote_threadtests (void)
10954 {
10955   add_com ("tlist", class_obscure, threadlist_test_cmd,
10956            _("Fetch and print the remote list of "
10957              "thread identifiers, one pkt only"));
10958   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
10959            _("Fetch and display info about one thread"));
10960   add_com ("tset", class_obscure, threadset_test_cmd,
10961            _("Test setting to a different thread"));
10962   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
10963            _("Iterate through updating all remote thread info"));
10964   add_com ("talive", class_obscure, threadalive_test,
10965            _(" Remote thread alive test "));
10966 }
10967
10968 #endif /* 0 */
10969
10970 /* Convert a thread ID to a string.  Returns the string in a static
10971    buffer.  */
10972
10973 static const char *
10974 remote_pid_to_str (struct target_ops *ops, ptid_t ptid)
10975 {
10976   static char buf[64];
10977   struct remote_state *rs = get_remote_state ();
10978
10979   if (ptid_equal (ptid, null_ptid))
10980     return normal_pid_to_str (ptid);
10981   else if (ptid_is_pid (ptid))
10982     {
10983       /* Printing an inferior target id.  */
10984
10985       /* When multi-process extensions are off, there's no way in the
10986          remote protocol to know the remote process id, if there's any
10987          at all.  There's one exception --- when we're connected with
10988          target extended-remote, and we manually attached to a process
10989          with "attach PID".  We don't record anywhere a flag that
10990          allows us to distinguish that case from the case of
10991          connecting with extended-remote and the stub already being
10992          attached to a process, and reporting yes to qAttached, hence
10993          no smart special casing here.  */
10994       if (!remote_multi_process_p (rs))
10995         {
10996           xsnprintf (buf, sizeof buf, "Remote target");
10997           return buf;
10998         }
10999
11000       return normal_pid_to_str (ptid);
11001     }
11002   else
11003     {
11004       if (ptid_equal (magic_null_ptid, ptid))
11005         xsnprintf (buf, sizeof buf, "Thread <main>");
11006       else if (remote_multi_process_p (rs))
11007         if (ptid_get_lwp (ptid) == 0)
11008           return normal_pid_to_str (ptid);
11009         else
11010           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11011                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
11012       else
11013         xsnprintf (buf, sizeof buf, "Thread %ld",
11014                    ptid_get_lwp (ptid));
11015       return buf;
11016     }
11017 }
11018
11019 /* Get the address of the thread local variable in OBJFILE which is
11020    stored at OFFSET within the thread local storage for thread PTID.  */
11021
11022 static CORE_ADDR
11023 remote_get_thread_local_address (struct target_ops *ops,
11024                                  ptid_t ptid, CORE_ADDR lm, CORE_ADDR offset)
11025 {
11026   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11027     {
11028       struct remote_state *rs = get_remote_state ();
11029       char *p = rs->buf;
11030       char *endp = rs->buf + get_remote_packet_size ();
11031       enum packet_result result;
11032
11033       strcpy (p, "qGetTLSAddr:");
11034       p += strlen (p);
11035       p = write_ptid (p, endp, ptid);
11036       *p++ = ',';
11037       p += hexnumstr (p, offset);
11038       *p++ = ',';
11039       p += hexnumstr (p, lm);
11040       *p++ = '\0';
11041
11042       putpkt (rs->buf);
11043       getpkt (&rs->buf, &rs->buf_size, 0);
11044       result = packet_ok (rs->buf,
11045                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11046       if (result == PACKET_OK)
11047         {
11048           ULONGEST result;
11049
11050           unpack_varlen_hex (rs->buf, &result);
11051           return result;
11052         }
11053       else if (result == PACKET_UNKNOWN)
11054         throw_error (TLS_GENERIC_ERROR,
11055                      _("Remote target doesn't support qGetTLSAddr packet"));
11056       else
11057         throw_error (TLS_GENERIC_ERROR,
11058                      _("Remote target failed to process qGetTLSAddr request"));
11059     }
11060   else
11061     throw_error (TLS_GENERIC_ERROR,
11062                  _("TLS not supported or disabled on this target"));
11063   /* Not reached.  */
11064   return 0;
11065 }
11066
11067 /* Provide thread local base, i.e. Thread Information Block address.
11068    Returns 1 if ptid is found and thread_local_base is non zero.  */
11069
11070 static int
11071 remote_get_tib_address (struct target_ops *self, ptid_t ptid, CORE_ADDR *addr)
11072 {
11073   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11074     {
11075       struct remote_state *rs = get_remote_state ();
11076       char *p = rs->buf;
11077       char *endp = rs->buf + get_remote_packet_size ();
11078       enum packet_result result;
11079
11080       strcpy (p, "qGetTIBAddr:");
11081       p += strlen (p);
11082       p = write_ptid (p, endp, ptid);
11083       *p++ = '\0';
11084
11085       putpkt (rs->buf);
11086       getpkt (&rs->buf, &rs->buf_size, 0);
11087       result = packet_ok (rs->buf,
11088                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11089       if (result == PACKET_OK)
11090         {
11091           ULONGEST result;
11092
11093           unpack_varlen_hex (rs->buf, &result);
11094           if (addr)
11095             *addr = (CORE_ADDR) result;
11096           return 1;
11097         }
11098       else if (result == PACKET_UNKNOWN)
11099         error (_("Remote target doesn't support qGetTIBAddr packet"));
11100       else
11101         error (_("Remote target failed to process qGetTIBAddr request"));
11102     }
11103   else
11104     error (_("qGetTIBAddr not supported or disabled on this target"));
11105   /* Not reached.  */
11106   return 0;
11107 }
11108
11109 /* Support for inferring a target description based on the current
11110    architecture and the size of a 'g' packet.  While the 'g' packet
11111    can have any size (since optional registers can be left off the
11112    end), some sizes are easily recognizable given knowledge of the
11113    approximate architecture.  */
11114
11115 struct remote_g_packet_guess
11116 {
11117   int bytes;
11118   const struct target_desc *tdesc;
11119 };
11120 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11121 DEF_VEC_O(remote_g_packet_guess_s);
11122
11123 struct remote_g_packet_data
11124 {
11125   VEC(remote_g_packet_guess_s) *guesses;
11126 };
11127
11128 static struct gdbarch_data *remote_g_packet_data_handle;
11129
11130 static void *
11131 remote_g_packet_data_init (struct obstack *obstack)
11132 {
11133   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11134 }
11135
11136 void
11137 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11138                                 const struct target_desc *tdesc)
11139 {
11140   struct remote_g_packet_data *data
11141     = ((struct remote_g_packet_data *)
11142        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11143   struct remote_g_packet_guess new_guess, *guess;
11144   int ix;
11145
11146   gdb_assert (tdesc != NULL);
11147
11148   for (ix = 0;
11149        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11150        ix++)
11151     if (guess->bytes == bytes)
11152       internal_error (__FILE__, __LINE__,
11153                       _("Duplicate g packet description added for size %d"),
11154                       bytes);
11155
11156   new_guess.bytes = bytes;
11157   new_guess.tdesc = tdesc;
11158   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11159 }
11160
11161 /* Return 1 if remote_read_description would do anything on this target
11162    and architecture, 0 otherwise.  */
11163
11164 static int
11165 remote_read_description_p (struct target_ops *target)
11166 {
11167   struct remote_g_packet_data *data
11168     = ((struct remote_g_packet_data *)
11169        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11170
11171   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11172     return 1;
11173
11174   return 0;
11175 }
11176
11177 static const struct target_desc *
11178 remote_read_description (struct target_ops *target)
11179 {
11180   struct remote_g_packet_data *data
11181     = ((struct remote_g_packet_data *)
11182        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11183
11184   /* Do not try this during initial connection, when we do not know
11185      whether there is a running but stopped thread.  */
11186   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11187     return target->beneath->to_read_description (target->beneath);
11188
11189   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11190     {
11191       struct remote_g_packet_guess *guess;
11192       int ix;
11193       int bytes = send_g_packet ();
11194
11195       for (ix = 0;
11196            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11197            ix++)
11198         if (guess->bytes == bytes)
11199           return guess->tdesc;
11200
11201       /* We discard the g packet.  A minor optimization would be to
11202          hold on to it, and fill the register cache once we have selected
11203          an architecture, but it's too tricky to do safely.  */
11204     }
11205
11206   return target->beneath->to_read_description (target->beneath);
11207 }
11208
11209 /* Remote file transfer support.  This is host-initiated I/O, not
11210    target-initiated; for target-initiated, see remote-fileio.c.  */
11211
11212 /* If *LEFT is at least the length of STRING, copy STRING to
11213    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11214    decrease *LEFT.  Otherwise raise an error.  */
11215
11216 static void
11217 remote_buffer_add_string (char **buffer, int *left, const char *string)
11218 {
11219   int len = strlen (string);
11220
11221   if (len > *left)
11222     error (_("Packet too long for target."));
11223
11224   memcpy (*buffer, string, len);
11225   *buffer += len;
11226   *left -= len;
11227
11228   /* NUL-terminate the buffer as a convenience, if there is
11229      room.  */
11230   if (*left)
11231     **buffer = '\0';
11232 }
11233
11234 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11235    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11236    decrease *LEFT.  Otherwise raise an error.  */
11237
11238 static void
11239 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11240                          int len)
11241 {
11242   if (2 * len > *left)
11243     error (_("Packet too long for target."));
11244
11245   bin2hex (bytes, *buffer, len);
11246   *buffer += 2 * len;
11247   *left -= 2 * len;
11248
11249   /* NUL-terminate the buffer as a convenience, if there is
11250      room.  */
11251   if (*left)
11252     **buffer = '\0';
11253 }
11254
11255 /* If *LEFT is large enough, convert VALUE to hex and add it to
11256    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11257    decrease *LEFT.  Otherwise raise an error.  */
11258
11259 static void
11260 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11261 {
11262   int len = hexnumlen (value);
11263
11264   if (len > *left)
11265     error (_("Packet too long for target."));
11266
11267   hexnumstr (*buffer, value);
11268   *buffer += len;
11269   *left -= len;
11270
11271   /* NUL-terminate the buffer as a convenience, if there is
11272      room.  */
11273   if (*left)
11274     **buffer = '\0';
11275 }
11276
11277 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11278    value, *REMOTE_ERRNO to the remote error number or zero if none
11279    was included, and *ATTACHMENT to point to the start of the annex
11280    if any.  The length of the packet isn't needed here; there may
11281    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11282
11283    Return 0 if the packet could be parsed, -1 if it could not.  If
11284    -1 is returned, the other variables may not be initialized.  */
11285
11286 static int
11287 remote_hostio_parse_result (char *buffer, int *retcode,
11288                             int *remote_errno, char **attachment)
11289 {
11290   char *p, *p2;
11291
11292   *remote_errno = 0;
11293   *attachment = NULL;
11294
11295   if (buffer[0] != 'F')
11296     return -1;
11297
11298   errno = 0;
11299   *retcode = strtol (&buffer[1], &p, 16);
11300   if (errno != 0 || p == &buffer[1])
11301     return -1;
11302
11303   /* Check for ",errno".  */
11304   if (*p == ',')
11305     {
11306       errno = 0;
11307       *remote_errno = strtol (p + 1, &p2, 16);
11308       if (errno != 0 || p + 1 == p2)
11309         return -1;
11310       p = p2;
11311     }
11312
11313   /* Check for ";attachment".  If there is no attachment, the
11314      packet should end here.  */
11315   if (*p == ';')
11316     {
11317       *attachment = p + 1;
11318       return 0;
11319     }
11320   else if (*p == '\0')
11321     return 0;
11322   else
11323     return -1;
11324 }
11325
11326 /* Send a prepared I/O packet to the target and read its response.
11327    The prepared packet is in the global RS->BUF before this function
11328    is called, and the answer is there when we return.
11329
11330    COMMAND_BYTES is the length of the request to send, which may include
11331    binary data.  WHICH_PACKET is the packet configuration to check
11332    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11333    is set to the error number and -1 is returned.  Otherwise the value
11334    returned by the function is returned.
11335
11336    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11337    attachment is expected; an error will be reported if there's a
11338    mismatch.  If one is found, *ATTACHMENT will be set to point into
11339    the packet buffer and *ATTACHMENT_LEN will be set to the
11340    attachment's length.  */
11341
11342 static int
11343 remote_hostio_send_command (int command_bytes, int which_packet,
11344                             int *remote_errno, char **attachment,
11345                             int *attachment_len)
11346 {
11347   struct remote_state *rs = get_remote_state ();
11348   int ret, bytes_read;
11349   char *attachment_tmp;
11350
11351   if (packet_support (which_packet) == PACKET_DISABLE)
11352     {
11353       *remote_errno = FILEIO_ENOSYS;
11354       return -1;
11355     }
11356
11357   putpkt_binary (rs->buf, command_bytes);
11358   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11359
11360   /* If it timed out, something is wrong.  Don't try to parse the
11361      buffer.  */
11362   if (bytes_read < 0)
11363     {
11364       *remote_errno = FILEIO_EINVAL;
11365       return -1;
11366     }
11367
11368   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11369     {
11370     case PACKET_ERROR:
11371       *remote_errno = FILEIO_EINVAL;
11372       return -1;
11373     case PACKET_UNKNOWN:
11374       *remote_errno = FILEIO_ENOSYS;
11375       return -1;
11376     case PACKET_OK:
11377       break;
11378     }
11379
11380   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11381                                   &attachment_tmp))
11382     {
11383       *remote_errno = FILEIO_EINVAL;
11384       return -1;
11385     }
11386
11387   /* Make sure we saw an attachment if and only if we expected one.  */
11388   if ((attachment_tmp == NULL && attachment != NULL)
11389       || (attachment_tmp != NULL && attachment == NULL))
11390     {
11391       *remote_errno = FILEIO_EINVAL;
11392       return -1;
11393     }
11394
11395   /* If an attachment was found, it must point into the packet buffer;
11396      work out how many bytes there were.  */
11397   if (attachment_tmp != NULL)
11398     {
11399       *attachment = attachment_tmp;
11400       *attachment_len = bytes_read - (*attachment - rs->buf);
11401     }
11402
11403   return ret;
11404 }
11405
11406 /* Invalidate the readahead cache.  */
11407
11408 static void
11409 readahead_cache_invalidate (void)
11410 {
11411   struct remote_state *rs = get_remote_state ();
11412
11413   rs->readahead_cache.fd = -1;
11414 }
11415
11416 /* Invalidate the readahead cache if it is holding data for FD.  */
11417
11418 static void
11419 readahead_cache_invalidate_fd (int fd)
11420 {
11421   struct remote_state *rs = get_remote_state ();
11422
11423   if (rs->readahead_cache.fd == fd)
11424     rs->readahead_cache.fd = -1;
11425 }
11426
11427 /* Set the filesystem remote_hostio functions that take FILENAME
11428    arguments will use.  Return 0 on success, or -1 if an error
11429    occurs (and set *REMOTE_ERRNO).  */
11430
11431 static int
11432 remote_hostio_set_filesystem (struct inferior *inf, int *remote_errno)
11433 {
11434   struct remote_state *rs = get_remote_state ();
11435   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11436   char *p = rs->buf;
11437   int left = get_remote_packet_size () - 1;
11438   char arg[9];
11439   int ret;
11440
11441   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11442     return 0;
11443
11444   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11445     return 0;
11446
11447   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11448
11449   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11450   remote_buffer_add_string (&p, &left, arg);
11451
11452   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11453                                     remote_errno, NULL, NULL);
11454
11455   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11456     return 0;
11457
11458   if (ret == 0)
11459     rs->fs_pid = required_pid;
11460
11461   return ret;
11462 }
11463
11464 /* Implementation of to_fileio_open.  */
11465
11466 static int
11467 remote_hostio_open (struct target_ops *self,
11468                     struct inferior *inf, const char *filename,
11469                     int flags, int mode, int warn_if_slow,
11470                     int *remote_errno)
11471 {
11472   struct remote_state *rs = get_remote_state ();
11473   char *p = rs->buf;
11474   int left = get_remote_packet_size () - 1;
11475
11476   if (warn_if_slow)
11477     {
11478       static int warning_issued = 0;
11479
11480       printf_unfiltered (_("Reading %s from remote target...\n"),
11481                          filename);
11482
11483       if (!warning_issued)
11484         {
11485           warning (_("File transfers from remote targets can be slow."
11486                      " Use \"set sysroot\" to access files locally"
11487                      " instead."));
11488           warning_issued = 1;
11489         }
11490     }
11491
11492   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11493     return -1;
11494
11495   remote_buffer_add_string (&p, &left, "vFile:open:");
11496
11497   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11498                            strlen (filename));
11499   remote_buffer_add_string (&p, &left, ",");
11500
11501   remote_buffer_add_int (&p, &left, flags);
11502   remote_buffer_add_string (&p, &left, ",");
11503
11504   remote_buffer_add_int (&p, &left, mode);
11505
11506   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11507                                      remote_errno, NULL, NULL);
11508 }
11509
11510 /* Implementation of to_fileio_pwrite.  */
11511
11512 static int
11513 remote_hostio_pwrite (struct target_ops *self,
11514                       int fd, const gdb_byte *write_buf, int len,
11515                       ULONGEST offset, int *remote_errno)
11516 {
11517   struct remote_state *rs = get_remote_state ();
11518   char *p = rs->buf;
11519   int left = get_remote_packet_size ();
11520   int out_len;
11521
11522   readahead_cache_invalidate_fd (fd);
11523
11524   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11525
11526   remote_buffer_add_int (&p, &left, fd);
11527   remote_buffer_add_string (&p, &left, ",");
11528
11529   remote_buffer_add_int (&p, &left, offset);
11530   remote_buffer_add_string (&p, &left, ",");
11531
11532   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11533                              get_remote_packet_size () - (p - rs->buf));
11534
11535   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
11536                                      remote_errno, NULL, NULL);
11537 }
11538
11539 /* Helper for the implementation of to_fileio_pread.  Read the file
11540    from the remote side with vFile:pread.  */
11541
11542 static int
11543 remote_hostio_pread_vFile (struct target_ops *self,
11544                            int fd, gdb_byte *read_buf, int len,
11545                            ULONGEST offset, int *remote_errno)
11546 {
11547   struct remote_state *rs = get_remote_state ();
11548   char *p = rs->buf;
11549   char *attachment;
11550   int left = get_remote_packet_size ();
11551   int ret, attachment_len;
11552   int read_len;
11553
11554   remote_buffer_add_string (&p, &left, "vFile:pread:");
11555
11556   remote_buffer_add_int (&p, &left, fd);
11557   remote_buffer_add_string (&p, &left, ",");
11558
11559   remote_buffer_add_int (&p, &left, len);
11560   remote_buffer_add_string (&p, &left, ",");
11561
11562   remote_buffer_add_int (&p, &left, offset);
11563
11564   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
11565                                     remote_errno, &attachment,
11566                                     &attachment_len);
11567
11568   if (ret < 0)
11569     return ret;
11570
11571   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11572                                     read_buf, len);
11573   if (read_len != ret)
11574     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
11575
11576   return ret;
11577 }
11578
11579 /* Serve pread from the readahead cache.  Returns number of bytes
11580    read, or 0 if the request can't be served from the cache.  */
11581
11582 static int
11583 remote_hostio_pread_from_cache (struct remote_state *rs,
11584                                 int fd, gdb_byte *read_buf, size_t len,
11585                                 ULONGEST offset)
11586 {
11587   struct readahead_cache *cache = &rs->readahead_cache;
11588
11589   if (cache->fd == fd
11590       && cache->offset <= offset
11591       && offset < cache->offset + cache->bufsize)
11592     {
11593       ULONGEST max = cache->offset + cache->bufsize;
11594
11595       if (offset + len > max)
11596         len = max - offset;
11597
11598       memcpy (read_buf, cache->buf + offset - cache->offset, len);
11599       return len;
11600     }
11601
11602   return 0;
11603 }
11604
11605 /* Implementation of to_fileio_pread.  */
11606
11607 static int
11608 remote_hostio_pread (struct target_ops *self,
11609                      int fd, gdb_byte *read_buf, int len,
11610                      ULONGEST offset, int *remote_errno)
11611 {
11612   int ret;
11613   struct remote_state *rs = get_remote_state ();
11614   struct readahead_cache *cache = &rs->readahead_cache;
11615
11616   ret = remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11617   if (ret > 0)
11618     {
11619       cache->hit_count++;
11620
11621       if (remote_debug)
11622         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
11623                             pulongest (cache->hit_count));
11624       return ret;
11625     }
11626
11627   cache->miss_count++;
11628   if (remote_debug)
11629     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
11630                         pulongest (cache->miss_count));
11631
11632   cache->fd = fd;
11633   cache->offset = offset;
11634   cache->bufsize = get_remote_packet_size ();
11635   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
11636
11637   ret = remote_hostio_pread_vFile (self, cache->fd, cache->buf, cache->bufsize,
11638                                    cache->offset, remote_errno);
11639   if (ret <= 0)
11640     {
11641       readahead_cache_invalidate_fd (fd);
11642       return ret;
11643     }
11644
11645   cache->bufsize = ret;
11646   return remote_hostio_pread_from_cache (rs, fd, read_buf, len, offset);
11647 }
11648
11649 /* Implementation of to_fileio_close.  */
11650
11651 static int
11652 remote_hostio_close (struct target_ops *self, int fd, int *remote_errno)
11653 {
11654   struct remote_state *rs = get_remote_state ();
11655   char *p = rs->buf;
11656   int left = get_remote_packet_size () - 1;
11657
11658   readahead_cache_invalidate_fd (fd);
11659
11660   remote_buffer_add_string (&p, &left, "vFile:close:");
11661
11662   remote_buffer_add_int (&p, &left, fd);
11663
11664   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
11665                                      remote_errno, NULL, NULL);
11666 }
11667
11668 /* Implementation of to_fileio_unlink.  */
11669
11670 static int
11671 remote_hostio_unlink (struct target_ops *self,
11672                       struct inferior *inf, const char *filename,
11673                       int *remote_errno)
11674 {
11675   struct remote_state *rs = get_remote_state ();
11676   char *p = rs->buf;
11677   int left = get_remote_packet_size () - 1;
11678
11679   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11680     return -1;
11681
11682   remote_buffer_add_string (&p, &left, "vFile:unlink:");
11683
11684   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11685                            strlen (filename));
11686
11687   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
11688                                      remote_errno, NULL, NULL);
11689 }
11690
11691 /* Implementation of to_fileio_readlink.  */
11692
11693 static gdb::optional<std::string>
11694 remote_hostio_readlink (struct target_ops *self,
11695                         struct inferior *inf, const char *filename,
11696                         int *remote_errno)
11697 {
11698   struct remote_state *rs = get_remote_state ();
11699   char *p = rs->buf;
11700   char *attachment;
11701   int left = get_remote_packet_size ();
11702   int len, attachment_len;
11703   int read_len;
11704
11705   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11706     return {};
11707
11708   remote_buffer_add_string (&p, &left, "vFile:readlink:");
11709
11710   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11711                            strlen (filename));
11712
11713   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
11714                                     remote_errno, &attachment,
11715                                     &attachment_len);
11716
11717   if (len < 0)
11718     return {};
11719
11720   std::string ret (len, '\0');
11721
11722   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11723                                     (gdb_byte *) &ret[0], len);
11724   if (read_len != len)
11725     error (_("Readlink returned %d, but %d bytes."), len, read_len);
11726
11727   return ret;
11728 }
11729
11730 /* Implementation of to_fileio_fstat.  */
11731
11732 static int
11733 remote_hostio_fstat (struct target_ops *self,
11734                      int fd, struct stat *st,
11735                      int *remote_errno)
11736 {
11737   struct remote_state *rs = get_remote_state ();
11738   char *p = rs->buf;
11739   int left = get_remote_packet_size ();
11740   int attachment_len, ret;
11741   char *attachment;
11742   struct fio_stat fst;
11743   int read_len;
11744
11745   remote_buffer_add_string (&p, &left, "vFile:fstat:");
11746
11747   remote_buffer_add_int (&p, &left, fd);
11748
11749   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
11750                                     remote_errno, &attachment,
11751                                     &attachment_len);
11752   if (ret < 0)
11753     {
11754       if (*remote_errno != FILEIO_ENOSYS)
11755         return ret;
11756
11757       /* Strictly we should return -1, ENOSYS here, but when
11758          "set sysroot remote:" was implemented in August 2008
11759          BFD's need for a stat function was sidestepped with
11760          this hack.  This was not remedied until March 2015
11761          so we retain the previous behavior to avoid breaking
11762          compatibility.
11763
11764          Note that the memset is a March 2015 addition; older
11765          GDBs set st_size *and nothing else* so the structure
11766          would have garbage in all other fields.  This might
11767          break something but retaining the previous behavior
11768          here would be just too wrong.  */
11769
11770       memset (st, 0, sizeof (struct stat));
11771       st->st_size = INT_MAX;
11772       return 0;
11773     }
11774
11775   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
11776                                     (gdb_byte *) &fst, sizeof (fst));
11777
11778   if (read_len != ret)
11779     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
11780
11781   if (read_len != sizeof (fst))
11782     error (_("vFile:fstat returned %d bytes, but expecting %d."),
11783            read_len, (int) sizeof (fst));
11784
11785   remote_fileio_to_host_stat (&fst, st);
11786
11787   return 0;
11788 }
11789
11790 /* Implementation of to_filesystem_is_local.  */
11791
11792 static int
11793 remote_filesystem_is_local (struct target_ops *self)
11794 {
11795   /* Valgrind GDB presents itself as a remote target but works
11796      on the local filesystem: it does not implement remote get
11797      and users are not expected to set a sysroot.  To handle
11798      this case we treat the remote filesystem as local if the
11799      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
11800      does not support vFile:open.  */
11801   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
11802     {
11803       enum packet_support ps = packet_support (PACKET_vFile_open);
11804
11805       if (ps == PACKET_SUPPORT_UNKNOWN)
11806         {
11807           int fd, remote_errno;
11808
11809           /* Try opening a file to probe support.  The supplied
11810              filename is irrelevant, we only care about whether
11811              the stub recognizes the packet or not.  */
11812           fd = remote_hostio_open (self, NULL, "just probing",
11813                                    FILEIO_O_RDONLY, 0700, 0,
11814                                    &remote_errno);
11815
11816           if (fd >= 0)
11817             remote_hostio_close (self, fd, &remote_errno);
11818
11819           ps = packet_support (PACKET_vFile_open);
11820         }
11821
11822       if (ps == PACKET_DISABLE)
11823         {
11824           static int warning_issued = 0;
11825
11826           if (!warning_issued)
11827             {
11828               warning (_("remote target does not support file"
11829                          " transfer, attempting to access files"
11830                          " from local filesystem."));
11831               warning_issued = 1;
11832             }
11833
11834           return 1;
11835         }
11836     }
11837
11838   return 0;
11839 }
11840
11841 static int
11842 remote_fileio_errno_to_host (int errnum)
11843 {
11844   switch (errnum)
11845     {
11846       case FILEIO_EPERM:
11847         return EPERM;
11848       case FILEIO_ENOENT:
11849         return ENOENT;
11850       case FILEIO_EINTR:
11851         return EINTR;
11852       case FILEIO_EIO:
11853         return EIO;
11854       case FILEIO_EBADF:
11855         return EBADF;
11856       case FILEIO_EACCES:
11857         return EACCES;
11858       case FILEIO_EFAULT:
11859         return EFAULT;
11860       case FILEIO_EBUSY:
11861         return EBUSY;
11862       case FILEIO_EEXIST:
11863         return EEXIST;
11864       case FILEIO_ENODEV:
11865         return ENODEV;
11866       case FILEIO_ENOTDIR:
11867         return ENOTDIR;
11868       case FILEIO_EISDIR:
11869         return EISDIR;
11870       case FILEIO_EINVAL:
11871         return EINVAL;
11872       case FILEIO_ENFILE:
11873         return ENFILE;
11874       case FILEIO_EMFILE:
11875         return EMFILE;
11876       case FILEIO_EFBIG:
11877         return EFBIG;
11878       case FILEIO_ENOSPC:
11879         return ENOSPC;
11880       case FILEIO_ESPIPE:
11881         return ESPIPE;
11882       case FILEIO_EROFS:
11883         return EROFS;
11884       case FILEIO_ENOSYS:
11885         return ENOSYS;
11886       case FILEIO_ENAMETOOLONG:
11887         return ENAMETOOLONG;
11888     }
11889   return -1;
11890 }
11891
11892 static char *
11893 remote_hostio_error (int errnum)
11894 {
11895   int host_error = remote_fileio_errno_to_host (errnum);
11896
11897   if (host_error == -1)
11898     error (_("Unknown remote I/O error %d"), errnum);
11899   else
11900     error (_("Remote I/O error: %s"), safe_strerror (host_error));
11901 }
11902
11903 static void
11904 remote_hostio_close_cleanup (void *opaque)
11905 {
11906   int fd = *(int *) opaque;
11907   int remote_errno;
11908
11909   remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno);
11910 }
11911
11912 void
11913 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
11914 {
11915   struct cleanup *back_to, *close_cleanup;
11916   int retcode, fd, remote_errno, bytes, io_size;
11917   gdb_byte *buffer;
11918   int bytes_in_buffer;
11919   int saw_eof;
11920   ULONGEST offset;
11921   struct remote_state *rs = get_remote_state ();
11922
11923   if (!rs->remote_desc)
11924     error (_("command can only be used with remote target"));
11925
11926   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
11927   if (file == NULL)
11928     perror_with_name (local_file);
11929
11930   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
11931                            remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
11932                                          | FILEIO_O_TRUNC),
11933                            0700, 0, &remote_errno);
11934   if (fd == -1)
11935     remote_hostio_error (remote_errno);
11936
11937   /* Send up to this many bytes at once.  They won't all fit in the
11938      remote packet limit, so we'll transfer slightly fewer.  */
11939   io_size = get_remote_packet_size ();
11940   buffer = (gdb_byte *) xmalloc (io_size);
11941   back_to = make_cleanup (xfree, buffer);
11942
11943   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
11944
11945   bytes_in_buffer = 0;
11946   saw_eof = 0;
11947   offset = 0;
11948   while (bytes_in_buffer || !saw_eof)
11949     {
11950       if (!saw_eof)
11951         {
11952           bytes = fread (buffer + bytes_in_buffer, 1,
11953                          io_size - bytes_in_buffer,
11954                          file.get ());
11955           if (bytes == 0)
11956             {
11957               if (ferror (file.get ()))
11958                 error (_("Error reading %s."), local_file);
11959               else
11960                 {
11961                   /* EOF.  Unless there is something still in the
11962                      buffer from the last iteration, we are done.  */
11963                   saw_eof = 1;
11964                   if (bytes_in_buffer == 0)
11965                     break;
11966                 }
11967             }
11968         }
11969       else
11970         bytes = 0;
11971
11972       bytes += bytes_in_buffer;
11973       bytes_in_buffer = 0;
11974
11975       retcode = remote_hostio_pwrite (find_target_at (process_stratum),
11976                                       fd, buffer, bytes,
11977                                       offset, &remote_errno);
11978
11979       if (retcode < 0)
11980         remote_hostio_error (remote_errno);
11981       else if (retcode == 0)
11982         error (_("Remote write of %d bytes returned 0!"), bytes);
11983       else if (retcode < bytes)
11984         {
11985           /* Short write.  Save the rest of the read data for the next
11986              write.  */
11987           bytes_in_buffer = bytes - retcode;
11988           memmove (buffer, buffer + retcode, bytes_in_buffer);
11989         }
11990
11991       offset += retcode;
11992     }
11993
11994   discard_cleanups (close_cleanup);
11995   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
11996     remote_hostio_error (remote_errno);
11997
11998   if (from_tty)
11999     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12000   do_cleanups (back_to);
12001 }
12002
12003 void
12004 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12005 {
12006   struct cleanup *back_to, *close_cleanup;
12007   int fd, remote_errno, bytes, io_size;
12008   gdb_byte *buffer;
12009   ULONGEST offset;
12010   struct remote_state *rs = get_remote_state ();
12011
12012   if (!rs->remote_desc)
12013     error (_("command can only be used with remote target"));
12014
12015   fd = remote_hostio_open (find_target_at (process_stratum), NULL,
12016                            remote_file, FILEIO_O_RDONLY, 0, 0,
12017                            &remote_errno);
12018   if (fd == -1)
12019     remote_hostio_error (remote_errno);
12020
12021   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12022   if (file == NULL)
12023     perror_with_name (local_file);
12024
12025   /* Send up to this many bytes at once.  They won't all fit in the
12026      remote packet limit, so we'll transfer slightly fewer.  */
12027   io_size = get_remote_packet_size ();
12028   buffer = (gdb_byte *) xmalloc (io_size);
12029   back_to = make_cleanup (xfree, buffer);
12030
12031   close_cleanup = make_cleanup (remote_hostio_close_cleanup, &fd);
12032
12033   offset = 0;
12034   while (1)
12035     {
12036       bytes = remote_hostio_pread (find_target_at (process_stratum),
12037                                    fd, buffer, io_size, offset, &remote_errno);
12038       if (bytes == 0)
12039         /* Success, but no bytes, means end-of-file.  */
12040         break;
12041       if (bytes == -1)
12042         remote_hostio_error (remote_errno);
12043
12044       offset += bytes;
12045
12046       bytes = fwrite (buffer, 1, bytes, file.get ());
12047       if (bytes == 0)
12048         perror_with_name (local_file);
12049     }
12050
12051   discard_cleanups (close_cleanup);
12052   if (remote_hostio_close (find_target_at (process_stratum), fd, &remote_errno))
12053     remote_hostio_error (remote_errno);
12054
12055   if (from_tty)
12056     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12057   do_cleanups (back_to);
12058 }
12059
12060 void
12061 remote_file_delete (const char *remote_file, int from_tty)
12062 {
12063   int retcode, remote_errno;
12064   struct remote_state *rs = get_remote_state ();
12065
12066   if (!rs->remote_desc)
12067     error (_("command can only be used with remote target"));
12068
12069   retcode = remote_hostio_unlink (find_target_at (process_stratum),
12070                                   NULL, remote_file, &remote_errno);
12071   if (retcode == -1)
12072     remote_hostio_error (remote_errno);
12073
12074   if (from_tty)
12075     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12076 }
12077
12078 static void
12079 remote_put_command (const char *args, int from_tty)
12080 {
12081   if (args == NULL)
12082     error_no_arg (_("file to put"));
12083
12084   gdb_argv argv (args);
12085   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12086     error (_("Invalid parameters to remote put"));
12087
12088   remote_file_put (argv[0], argv[1], from_tty);
12089 }
12090
12091 static void
12092 remote_get_command (const char *args, int from_tty)
12093 {
12094   if (args == NULL)
12095     error_no_arg (_("file to get"));
12096
12097   gdb_argv argv (args);
12098   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12099     error (_("Invalid parameters to remote get"));
12100
12101   remote_file_get (argv[0], argv[1], from_tty);
12102 }
12103
12104 static void
12105 remote_delete_command (const char *args, int from_tty)
12106 {
12107   if (args == NULL)
12108     error_no_arg (_("file to delete"));
12109
12110   gdb_argv argv (args);
12111   if (argv[0] == NULL || argv[1] != NULL)
12112     error (_("Invalid parameters to remote delete"));
12113
12114   remote_file_delete (argv[0], from_tty);
12115 }
12116
12117 static void
12118 remote_command (const char *args, int from_tty)
12119 {
12120   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12121 }
12122
12123 static int
12124 remote_can_execute_reverse (struct target_ops *self)
12125 {
12126   if (packet_support (PACKET_bs) == PACKET_ENABLE
12127       || packet_support (PACKET_bc) == PACKET_ENABLE)
12128     return 1;
12129   else
12130     return 0;
12131 }
12132
12133 static int
12134 remote_supports_non_stop (struct target_ops *self)
12135 {
12136   return 1;
12137 }
12138
12139 static int
12140 remote_supports_disable_randomization (struct target_ops *self)
12141 {
12142   /* Only supported in extended mode.  */
12143   return 0;
12144 }
12145
12146 static int
12147 remote_supports_multi_process (struct target_ops *self)
12148 {
12149   struct remote_state *rs = get_remote_state ();
12150
12151   return remote_multi_process_p (rs);
12152 }
12153
12154 static int
12155 remote_supports_cond_tracepoints (void)
12156 {
12157   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12158 }
12159
12160 static int
12161 remote_supports_cond_breakpoints (struct target_ops *self)
12162 {
12163   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12164 }
12165
12166 static int
12167 remote_supports_fast_tracepoints (void)
12168 {
12169   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12170 }
12171
12172 static int
12173 remote_supports_static_tracepoints (void)
12174 {
12175   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12176 }
12177
12178 static int
12179 remote_supports_install_in_trace (void)
12180 {
12181   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12182 }
12183
12184 static int
12185 remote_supports_enable_disable_tracepoint (struct target_ops *self)
12186 {
12187   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12188           == PACKET_ENABLE);
12189 }
12190
12191 static int
12192 remote_supports_string_tracing (struct target_ops *self)
12193 {
12194   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12195 }
12196
12197 static int
12198 remote_can_run_breakpoint_commands (struct target_ops *self)
12199 {
12200   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12201 }
12202
12203 static void
12204 remote_trace_init (struct target_ops *self)
12205 {
12206   struct remote_state *rs = get_remote_state ();
12207
12208   putpkt ("QTinit");
12209   remote_get_noisy_reply ();
12210   if (strcmp (rs->buf, "OK") != 0)
12211     error (_("Target does not support this command."));
12212 }
12213
12214 /* Recursive routine to walk through command list including loops, and
12215    download packets for each command.  */
12216
12217 static void
12218 remote_download_command_source (int num, ULONGEST addr,
12219                                 struct command_line *cmds)
12220 {
12221   struct remote_state *rs = get_remote_state ();
12222   struct command_line *cmd;
12223
12224   for (cmd = cmds; cmd; cmd = cmd->next)
12225     {
12226       QUIT;     /* Allow user to bail out with ^C.  */
12227       strcpy (rs->buf, "QTDPsrc:");
12228       encode_source_string (num, addr, "cmd", cmd->line,
12229                             rs->buf + strlen (rs->buf),
12230                             rs->buf_size - strlen (rs->buf));
12231       putpkt (rs->buf);
12232       remote_get_noisy_reply ();
12233       if (strcmp (rs->buf, "OK"))
12234         warning (_("Target does not support source download."));
12235
12236       if (cmd->control_type == while_control
12237           || cmd->control_type == while_stepping_control)
12238         {
12239           remote_download_command_source (num, addr, *cmd->body_list);
12240
12241           QUIT; /* Allow user to bail out with ^C.  */
12242           strcpy (rs->buf, "QTDPsrc:");
12243           encode_source_string (num, addr, "cmd", "end",
12244                                 rs->buf + strlen (rs->buf),
12245                                 rs->buf_size - strlen (rs->buf));
12246           putpkt (rs->buf);
12247           remote_get_noisy_reply ();
12248           if (strcmp (rs->buf, "OK"))
12249             warning (_("Target does not support source download."));
12250         }
12251     }
12252 }
12253
12254 static void
12255 remote_download_tracepoint (struct target_ops *self, struct bp_location *loc)
12256 {
12257 #define BUF_SIZE 2048
12258
12259   CORE_ADDR tpaddr;
12260   char addrbuf[40];
12261   char buf[BUF_SIZE];
12262   std::vector<std::string> tdp_actions;
12263   std::vector<std::string> stepping_actions;
12264   char *pkt;
12265   struct breakpoint *b = loc->owner;
12266   struct tracepoint *t = (struct tracepoint *) b;
12267   struct remote_state *rs = get_remote_state ();
12268
12269   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12270
12271   tpaddr = loc->address;
12272   sprintf_vma (addrbuf, tpaddr);
12273   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12274              addrbuf, /* address */
12275              (b->enable_state == bp_enabled ? 'E' : 'D'),
12276              t->step_count, t->pass_count);
12277   /* Fast tracepoints are mostly handled by the target, but we can
12278      tell the target how big of an instruction block should be moved
12279      around.  */
12280   if (b->type == bp_fast_tracepoint)
12281     {
12282       /* Only test for support at download time; we may not know
12283          target capabilities at definition time.  */
12284       if (remote_supports_fast_tracepoints ())
12285         {
12286           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12287                                                 NULL))
12288             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12289                        gdb_insn_length (loc->gdbarch, tpaddr));
12290           else
12291             /* If it passed validation at definition but fails now,
12292                something is very wrong.  */
12293             internal_error (__FILE__, __LINE__,
12294                             _("Fast tracepoint not "
12295                               "valid during download"));
12296         }
12297       else
12298         /* Fast tracepoints are functionally identical to regular
12299            tracepoints, so don't take lack of support as a reason to
12300            give up on the trace run.  */
12301         warning (_("Target does not support fast tracepoints, "
12302                    "downloading %d as regular tracepoint"), b->number);
12303     }
12304   else if (b->type == bp_static_tracepoint)
12305     {
12306       /* Only test for support at download time; we may not know
12307          target capabilities at definition time.  */
12308       if (remote_supports_static_tracepoints ())
12309         {
12310           struct static_tracepoint_marker marker;
12311
12312           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12313             strcat (buf, ":S");
12314           else
12315             error (_("Static tracepoint not valid during download"));
12316         }
12317       else
12318         /* Fast tracepoints are functionally identical to regular
12319            tracepoints, so don't take lack of support as a reason
12320            to give up on the trace run.  */
12321         error (_("Target does not support static tracepoints"));
12322     }
12323   /* If the tracepoint has a conditional, make it into an agent
12324      expression and append to the definition.  */
12325   if (loc->cond)
12326     {
12327       /* Only test support at download time, we may not know target
12328          capabilities at definition time.  */
12329       if (remote_supports_cond_tracepoints ())
12330         {
12331           agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12332           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12333                      aexpr->len);
12334           pkt = buf + strlen (buf);
12335           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12336             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12337           *pkt = '\0';
12338         }
12339       else
12340         warning (_("Target does not support conditional tracepoints, "
12341                    "ignoring tp %d cond"), b->number);
12342     }
12343
12344   if (b->commands || *default_collect)
12345     strcat (buf, "-");
12346   putpkt (buf);
12347   remote_get_noisy_reply ();
12348   if (strcmp (rs->buf, "OK"))
12349     error (_("Target does not support tracepoints."));
12350
12351   /* do_single_steps (t); */
12352   for (auto action_it = tdp_actions.begin ();
12353        action_it != tdp_actions.end (); action_it++)
12354     {
12355       QUIT;     /* Allow user to bail out with ^C.  */
12356
12357       bool has_more = (action_it != tdp_actions.end ()
12358                        || !stepping_actions.empty ());
12359
12360       xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12361                  b->number, addrbuf, /* address */
12362                  action_it->c_str (),
12363                  has_more ? '-' : 0);
12364       putpkt (buf);
12365       remote_get_noisy_reply ();
12366       if (strcmp (rs->buf, "OK"))
12367         error (_("Error on target while setting tracepoints."));
12368     }
12369
12370     for (auto action_it = stepping_actions.begin ();
12371          action_it != stepping_actions.end (); action_it++)
12372       {
12373         QUIT;   /* Allow user to bail out with ^C.  */
12374
12375         bool is_first = action_it == stepping_actions.begin ();
12376         bool has_more = action_it != stepping_actions.end ();
12377
12378         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12379                    b->number, addrbuf, /* address */
12380                    is_first ? "S" : "",
12381                    action_it->c_str (),
12382                    has_more ? "-" : "");
12383         putpkt (buf);
12384         remote_get_noisy_reply ();
12385         if (strcmp (rs->buf, "OK"))
12386           error (_("Error on target while setting tracepoints."));
12387       }
12388
12389   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12390     {
12391       if (b->location != NULL)
12392         {
12393           strcpy (buf, "QTDPsrc:");
12394           encode_source_string (b->number, loc->address, "at",
12395                                 event_location_to_string (b->location.get ()),
12396                                 buf + strlen (buf), 2048 - strlen (buf));
12397           putpkt (buf);
12398           remote_get_noisy_reply ();
12399           if (strcmp (rs->buf, "OK"))
12400             warning (_("Target does not support source download."));
12401         }
12402       if (b->cond_string)
12403         {
12404           strcpy (buf, "QTDPsrc:");
12405           encode_source_string (b->number, loc->address,
12406                                 "cond", b->cond_string, buf + strlen (buf),
12407                                 2048 - strlen (buf));
12408           putpkt (buf);
12409           remote_get_noisy_reply ();
12410           if (strcmp (rs->buf, "OK"))
12411             warning (_("Target does not support source download."));
12412         }
12413       remote_download_command_source (b->number, loc->address,
12414                                       breakpoint_commands (b));
12415     }
12416 }
12417
12418 static int
12419 remote_can_download_tracepoint (struct target_ops *self)
12420 {
12421   struct remote_state *rs = get_remote_state ();
12422   struct trace_status *ts;
12423   int status;
12424
12425   /* Don't try to install tracepoints until we've relocated our
12426      symbols, and fetched and merged the target's tracepoint list with
12427      ours.  */
12428   if (rs->starting_up)
12429     return 0;
12430
12431   ts = current_trace_status ();
12432   status = remote_get_trace_status (self, ts);
12433
12434   if (status == -1 || !ts->running_known || !ts->running)
12435     return 0;
12436
12437   /* If we are in a tracing experiment, but remote stub doesn't support
12438      installing tracepoint in trace, we have to return.  */
12439   if (!remote_supports_install_in_trace ())
12440     return 0;
12441
12442   return 1;
12443 }
12444
12445
12446 static void
12447 remote_download_trace_state_variable (struct target_ops *self,
12448                                       const trace_state_variable &tsv)
12449 {
12450   struct remote_state *rs = get_remote_state ();
12451   char *p;
12452
12453   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12454              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12455              tsv.builtin);
12456   p = rs->buf + strlen (rs->buf);
12457   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12458     error (_("Trace state variable name too long for tsv definition packet"));
12459   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12460   *p++ = '\0';
12461   putpkt (rs->buf);
12462   remote_get_noisy_reply ();
12463   if (*rs->buf == '\0')
12464     error (_("Target does not support this command."));
12465   if (strcmp (rs->buf, "OK") != 0)
12466     error (_("Error on target while downloading trace state variable."));
12467 }
12468
12469 static void
12470 remote_enable_tracepoint (struct target_ops *self,
12471                           struct bp_location *location)
12472 {
12473   struct remote_state *rs = get_remote_state ();
12474   char addr_buf[40];
12475
12476   sprintf_vma (addr_buf, location->address);
12477   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
12478              location->owner->number, addr_buf);
12479   putpkt (rs->buf);
12480   remote_get_noisy_reply ();
12481   if (*rs->buf == '\0')
12482     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
12483   if (strcmp (rs->buf, "OK") != 0)
12484     error (_("Error on target while enabling tracepoint."));
12485 }
12486
12487 static void
12488 remote_disable_tracepoint (struct target_ops *self,
12489                            struct bp_location *location)
12490 {
12491   struct remote_state *rs = get_remote_state ();
12492   char addr_buf[40];
12493
12494   sprintf_vma (addr_buf, location->address);
12495   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
12496              location->owner->number, addr_buf);
12497   putpkt (rs->buf);
12498   remote_get_noisy_reply ();
12499   if (*rs->buf == '\0')
12500     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
12501   if (strcmp (rs->buf, "OK") != 0)
12502     error (_("Error on target while disabling tracepoint."));
12503 }
12504
12505 static void
12506 remote_trace_set_readonly_regions (struct target_ops *self)
12507 {
12508   asection *s;
12509   bfd *abfd = NULL;
12510   bfd_size_type size;
12511   bfd_vma vma;
12512   int anysecs = 0;
12513   int offset = 0;
12514
12515   if (!exec_bfd)
12516     return;                     /* No information to give.  */
12517
12518   struct remote_state *rs = get_remote_state ();
12519
12520   strcpy (rs->buf, "QTro");
12521   offset = strlen (rs->buf);
12522   for (s = exec_bfd->sections; s; s = s->next)
12523     {
12524       char tmp1[40], tmp2[40];
12525       int sec_length;
12526
12527       if ((s->flags & SEC_LOAD) == 0 ||
12528       /*  (s->flags & SEC_CODE) == 0 || */
12529           (s->flags & SEC_READONLY) == 0)
12530         continue;
12531
12532       anysecs = 1;
12533       vma = bfd_get_section_vma (abfd, s);
12534       size = bfd_get_section_size (s);
12535       sprintf_vma (tmp1, vma);
12536       sprintf_vma (tmp2, vma + size);
12537       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
12538       if (offset + sec_length + 1 > rs->buf_size)
12539         {
12540           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
12541             warning (_("\
12542 Too many sections for read-only sections definition packet."));
12543           break;
12544         }
12545       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
12546                  tmp1, tmp2);
12547       offset += sec_length;
12548     }
12549   if (anysecs)
12550     {
12551       putpkt (rs->buf);
12552       getpkt (&rs->buf, &rs->buf_size, 0);
12553     }
12554 }
12555
12556 static void
12557 remote_trace_start (struct target_ops *self)
12558 {
12559   struct remote_state *rs = get_remote_state ();
12560
12561   putpkt ("QTStart");
12562   remote_get_noisy_reply ();
12563   if (*rs->buf == '\0')
12564     error (_("Target does not support this command."));
12565   if (strcmp (rs->buf, "OK") != 0)
12566     error (_("Bogus reply from target: %s"), rs->buf);
12567 }
12568
12569 static int
12570 remote_get_trace_status (struct target_ops *self, struct trace_status *ts)
12571 {
12572   /* Initialize it just to avoid a GCC false warning.  */
12573   char *p = NULL;
12574   /* FIXME we need to get register block size some other way.  */
12575   extern int trace_regblock_size;
12576   enum packet_result result;
12577   struct remote_state *rs = get_remote_state ();
12578
12579   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
12580     return -1;
12581
12582   trace_regblock_size
12583     = get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
12584
12585   putpkt ("qTStatus");
12586
12587   TRY
12588     {
12589       p = remote_get_noisy_reply ();
12590     }
12591   CATCH (ex, RETURN_MASK_ERROR)
12592     {
12593       if (ex.error != TARGET_CLOSE_ERROR)
12594         {
12595           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
12596           return -1;
12597         }
12598       throw_exception (ex);
12599     }
12600   END_CATCH
12601
12602   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
12603
12604   /* If the remote target doesn't do tracing, flag it.  */
12605   if (result == PACKET_UNKNOWN)
12606     return -1;
12607
12608   /* We're working with a live target.  */
12609   ts->filename = NULL;
12610
12611   if (*p++ != 'T')
12612     error (_("Bogus trace status reply from target: %s"), rs->buf);
12613
12614   /* Function 'parse_trace_status' sets default value of each field of
12615      'ts' at first, so we don't have to do it here.  */
12616   parse_trace_status (p, ts);
12617
12618   return ts->running;
12619 }
12620
12621 static void
12622 remote_get_tracepoint_status (struct target_ops *self, struct breakpoint *bp,
12623                               struct uploaded_tp *utp)
12624 {
12625   struct remote_state *rs = get_remote_state ();
12626   char *reply;
12627   struct bp_location *loc;
12628   struct tracepoint *tp = (struct tracepoint *) bp;
12629   size_t size = get_remote_packet_size ();
12630
12631   if (tp)
12632     {
12633       tp->hit_count = 0;
12634       tp->traceframe_usage = 0;
12635       for (loc = tp->loc; loc; loc = loc->next)
12636         {
12637           /* If the tracepoint was never downloaded, don't go asking for
12638              any status.  */
12639           if (tp->number_on_target == 0)
12640             continue;
12641           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
12642                      phex_nz (loc->address, 0));
12643           putpkt (rs->buf);
12644           reply = remote_get_noisy_reply ();
12645           if (reply && *reply)
12646             {
12647               if (*reply == 'V')
12648                 parse_tracepoint_status (reply + 1, bp, utp);
12649             }
12650         }
12651     }
12652   else if (utp)
12653     {
12654       utp->hit_count = 0;
12655       utp->traceframe_usage = 0;
12656       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
12657                  phex_nz (utp->addr, 0));
12658       putpkt (rs->buf);
12659       reply = remote_get_noisy_reply ();
12660       if (reply && *reply)
12661         {
12662           if (*reply == 'V')
12663             parse_tracepoint_status (reply + 1, bp, utp);
12664         }
12665     }
12666 }
12667
12668 static void
12669 remote_trace_stop (struct target_ops *self)
12670 {
12671   struct remote_state *rs = get_remote_state ();
12672
12673   putpkt ("QTStop");
12674   remote_get_noisy_reply ();
12675   if (*rs->buf == '\0')
12676     error (_("Target does not support this command."));
12677   if (strcmp (rs->buf, "OK") != 0)
12678     error (_("Bogus reply from target: %s"), rs->buf);
12679 }
12680
12681 static int
12682 remote_trace_find (struct target_ops *self,
12683                    enum trace_find_type type, int num,
12684                    CORE_ADDR addr1, CORE_ADDR addr2,
12685                    int *tpp)
12686 {
12687   struct remote_state *rs = get_remote_state ();
12688   char *endbuf = rs->buf + get_remote_packet_size ();
12689   char *p, *reply;
12690   int target_frameno = -1, target_tracept = -1;
12691
12692   /* Lookups other than by absolute frame number depend on the current
12693      trace selected, so make sure it is correct on the remote end
12694      first.  */
12695   if (type != tfind_number)
12696     set_remote_traceframe ();
12697
12698   p = rs->buf;
12699   strcpy (p, "QTFrame:");
12700   p = strchr (p, '\0');
12701   switch (type)
12702     {
12703     case tfind_number:
12704       xsnprintf (p, endbuf - p, "%x", num);
12705       break;
12706     case tfind_pc:
12707       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
12708       break;
12709     case tfind_tp:
12710       xsnprintf (p, endbuf - p, "tdp:%x", num);
12711       break;
12712     case tfind_range:
12713       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
12714                  phex_nz (addr2, 0));
12715       break;
12716     case tfind_outside:
12717       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
12718                  phex_nz (addr2, 0));
12719       break;
12720     default:
12721       error (_("Unknown trace find type %d"), type);
12722     }
12723
12724   putpkt (rs->buf);
12725   reply = remote_get_noisy_reply ();
12726   if (*reply == '\0')
12727     error (_("Target does not support this command."));
12728
12729   while (reply && *reply)
12730     switch (*reply)
12731       {
12732       case 'F':
12733         p = ++reply;
12734         target_frameno = (int) strtol (p, &reply, 16);
12735         if (reply == p)
12736           error (_("Unable to parse trace frame number"));
12737         /* Don't update our remote traceframe number cache on failure
12738            to select a remote traceframe.  */
12739         if (target_frameno == -1)
12740           return -1;
12741         break;
12742       case 'T':
12743         p = ++reply;
12744         target_tracept = (int) strtol (p, &reply, 16);
12745         if (reply == p)
12746           error (_("Unable to parse tracepoint number"));
12747         break;
12748       case 'O':         /* "OK"? */
12749         if (reply[1] == 'K' && reply[2] == '\0')
12750           reply += 2;
12751         else
12752           error (_("Bogus reply from target: %s"), reply);
12753         break;
12754       default:
12755         error (_("Bogus reply from target: %s"), reply);
12756       }
12757   if (tpp)
12758     *tpp = target_tracept;
12759
12760   rs->remote_traceframe_number = target_frameno;
12761   return target_frameno;
12762 }
12763
12764 static int
12765 remote_get_trace_state_variable_value (struct target_ops *self,
12766                                        int tsvnum, LONGEST *val)
12767 {
12768   struct remote_state *rs = get_remote_state ();
12769   char *reply;
12770   ULONGEST uval;
12771
12772   set_remote_traceframe ();
12773
12774   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
12775   putpkt (rs->buf);
12776   reply = remote_get_noisy_reply ();
12777   if (reply && *reply)
12778     {
12779       if (*reply == 'V')
12780         {
12781           unpack_varlen_hex (reply + 1, &uval);
12782           *val = (LONGEST) uval;
12783           return 1;
12784         }
12785     }
12786   return 0;
12787 }
12788
12789 static int
12790 remote_save_trace_data (struct target_ops *self, const char *filename)
12791 {
12792   struct remote_state *rs = get_remote_state ();
12793   char *p, *reply;
12794
12795   p = rs->buf;
12796   strcpy (p, "QTSave:");
12797   p += strlen (p);
12798   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
12799     error (_("Remote file name too long for trace save packet"));
12800   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
12801   *p++ = '\0';
12802   putpkt (rs->buf);
12803   reply = remote_get_noisy_reply ();
12804   if (*reply == '\0')
12805     error (_("Target does not support this command."));
12806   if (strcmp (reply, "OK") != 0)
12807     error (_("Bogus reply from target: %s"), reply);
12808   return 0;
12809 }
12810
12811 /* This is basically a memory transfer, but needs to be its own packet
12812    because we don't know how the target actually organizes its trace
12813    memory, plus we want to be able to ask for as much as possible, but
12814    not be unhappy if we don't get as much as we ask for.  */
12815
12816 static LONGEST
12817 remote_get_raw_trace_data (struct target_ops *self,
12818                            gdb_byte *buf, ULONGEST offset, LONGEST len)
12819 {
12820   struct remote_state *rs = get_remote_state ();
12821   char *reply;
12822   char *p;
12823   int rslt;
12824
12825   p = rs->buf;
12826   strcpy (p, "qTBuffer:");
12827   p += strlen (p);
12828   p += hexnumstr (p, offset);
12829   *p++ = ',';
12830   p += hexnumstr (p, len);
12831   *p++ = '\0';
12832
12833   putpkt (rs->buf);
12834   reply = remote_get_noisy_reply ();
12835   if (reply && *reply)
12836     {
12837       /* 'l' by itself means we're at the end of the buffer and
12838          there is nothing more to get.  */
12839       if (*reply == 'l')
12840         return 0;
12841
12842       /* Convert the reply into binary.  Limit the number of bytes to
12843          convert according to our passed-in buffer size, rather than
12844          what was returned in the packet; if the target is
12845          unexpectedly generous and gives us a bigger reply than we
12846          asked for, we don't want to crash.  */
12847       rslt = hex2bin (reply, buf, len);
12848       return rslt;
12849     }
12850
12851   /* Something went wrong, flag as an error.  */
12852   return -1;
12853 }
12854
12855 static void
12856 remote_set_disconnected_tracing (struct target_ops *self, int val)
12857 {
12858   struct remote_state *rs = get_remote_state ();
12859
12860   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
12861     {
12862       char *reply;
12863
12864       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
12865       putpkt (rs->buf);
12866       reply = remote_get_noisy_reply ();
12867       if (*reply == '\0')
12868         error (_("Target does not support this command."));
12869       if (strcmp (reply, "OK") != 0)
12870         error (_("Bogus reply from target: %s"), reply);
12871     }
12872   else if (val)
12873     warning (_("Target does not support disconnected tracing."));
12874 }
12875
12876 static int
12877 remote_core_of_thread (struct target_ops *ops, ptid_t ptid)
12878 {
12879   struct thread_info *info = find_thread_ptid (ptid);
12880
12881   if (info != NULL && info->priv != NULL)
12882     return get_remote_thread_info (info)->core;
12883
12884   return -1;
12885 }
12886
12887 static void
12888 remote_set_circular_trace_buffer (struct target_ops *self, int val)
12889 {
12890   struct remote_state *rs = get_remote_state ();
12891   char *reply;
12892
12893   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
12894   putpkt (rs->buf);
12895   reply = remote_get_noisy_reply ();
12896   if (*reply == '\0')
12897     error (_("Target does not support this command."));
12898   if (strcmp (reply, "OK") != 0)
12899     error (_("Bogus reply from target: %s"), reply);
12900 }
12901
12902 static traceframe_info_up
12903 remote_traceframe_info (struct target_ops *self)
12904 {
12905   gdb::optional<gdb::char_vector> text
12906     = target_read_stralloc (&current_target, TARGET_OBJECT_TRACEFRAME_INFO,
12907                             NULL);
12908   if (text)
12909     return parse_traceframe_info (text->data ());
12910
12911   return NULL;
12912 }
12913
12914 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
12915    instruction on which a fast tracepoint may be placed.  Returns -1
12916    if the packet is not supported, and 0 if the minimum instruction
12917    length is unknown.  */
12918
12919 static int
12920 remote_get_min_fast_tracepoint_insn_len (struct target_ops *self)
12921 {
12922   struct remote_state *rs = get_remote_state ();
12923   char *reply;
12924
12925   /* If we're not debugging a process yet, the IPA can't be
12926      loaded.  */
12927   if (!target_has_execution)
12928     return 0;
12929
12930   /* Make sure the remote is pointing at the right process.  */
12931   set_general_process ();
12932
12933   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
12934   putpkt (rs->buf);
12935   reply = remote_get_noisy_reply ();
12936   if (*reply == '\0')
12937     return -1;
12938   else
12939     {
12940       ULONGEST min_insn_len;
12941
12942       unpack_varlen_hex (reply, &min_insn_len);
12943
12944       return (int) min_insn_len;
12945     }
12946 }
12947
12948 static void
12949 remote_set_trace_buffer_size (struct target_ops *self, LONGEST val)
12950 {
12951   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
12952     {
12953       struct remote_state *rs = get_remote_state ();
12954       char *buf = rs->buf;
12955       char *endbuf = rs->buf + get_remote_packet_size ();
12956       enum packet_result result;
12957
12958       gdb_assert (val >= 0 || val == -1);
12959       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
12960       /* Send -1 as literal "-1" to avoid host size dependency.  */
12961       if (val < 0)
12962         {
12963           *buf++ = '-';
12964           buf += hexnumstr (buf, (ULONGEST) -val);
12965         }
12966       else
12967         buf += hexnumstr (buf, (ULONGEST) val);
12968
12969       putpkt (rs->buf);
12970       remote_get_noisy_reply ();
12971       result = packet_ok (rs->buf,
12972                   &remote_protocol_packets[PACKET_QTBuffer_size]);
12973
12974       if (result != PACKET_OK)
12975         warning (_("Bogus reply from target: %s"), rs->buf);
12976     }
12977 }
12978
12979 static int
12980 remote_set_trace_notes (struct target_ops *self,
12981                         const char *user, const char *notes,
12982                         const char *stop_notes)
12983 {
12984   struct remote_state *rs = get_remote_state ();
12985   char *reply;
12986   char *buf = rs->buf;
12987   char *endbuf = rs->buf + get_remote_packet_size ();
12988   int nbytes;
12989
12990   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
12991   if (user)
12992     {
12993       buf += xsnprintf (buf, endbuf - buf, "user:");
12994       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
12995       buf += 2 * nbytes;
12996       *buf++ = ';';
12997     }
12998   if (notes)
12999     {
13000       buf += xsnprintf (buf, endbuf - buf, "notes:");
13001       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13002       buf += 2 * nbytes;
13003       *buf++ = ';';
13004     }
13005   if (stop_notes)
13006     {
13007       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13008       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13009       buf += 2 * nbytes;
13010       *buf++ = ';';
13011     }
13012   /* Ensure the buffer is terminated.  */
13013   *buf = '\0';
13014
13015   putpkt (rs->buf);
13016   reply = remote_get_noisy_reply ();
13017   if (*reply == '\0')
13018     return 0;
13019
13020   if (strcmp (reply, "OK") != 0)
13021     error (_("Bogus reply from target: %s"), reply);
13022
13023   return 1;
13024 }
13025
13026 static int
13027 remote_use_agent (struct target_ops *self, int use)
13028 {
13029   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13030     {
13031       struct remote_state *rs = get_remote_state ();
13032
13033       /* If the stub supports QAgent.  */
13034       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13035       putpkt (rs->buf);
13036       getpkt (&rs->buf, &rs->buf_size, 0);
13037
13038       if (strcmp (rs->buf, "OK") == 0)
13039         {
13040           use_agent = use;
13041           return 1;
13042         }
13043     }
13044
13045   return 0;
13046 }
13047
13048 static int
13049 remote_can_use_agent (struct target_ops *self)
13050 {
13051   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13052 }
13053
13054 struct btrace_target_info
13055 {
13056   /* The ptid of the traced thread.  */
13057   ptid_t ptid;
13058
13059   /* The obtained branch trace configuration.  */
13060   struct btrace_config conf;
13061 };
13062
13063 /* Reset our idea of our target's btrace configuration.  */
13064
13065 static void
13066 remote_btrace_reset (void)
13067 {
13068   struct remote_state *rs = get_remote_state ();
13069
13070   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13071 }
13072
13073 /* Synchronize the configuration with the target.  */
13074
13075 static void
13076 btrace_sync_conf (const struct btrace_config *conf)
13077 {
13078   struct packet_config *packet;
13079   struct remote_state *rs;
13080   char *buf, *pos, *endbuf;
13081
13082   rs = get_remote_state ();
13083   buf = rs->buf;
13084   endbuf = buf + get_remote_packet_size ();
13085
13086   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13087   if (packet_config_support (packet) == PACKET_ENABLE
13088       && conf->bts.size != rs->btrace_config.bts.size)
13089     {
13090       pos = buf;
13091       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13092                         conf->bts.size);
13093
13094       putpkt (buf);
13095       getpkt (&buf, &rs->buf_size, 0);
13096
13097       if (packet_ok (buf, packet) == PACKET_ERROR)
13098         {
13099           if (buf[0] == 'E' && buf[1] == '.')
13100             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13101           else
13102             error (_("Failed to configure the BTS buffer size."));
13103         }
13104
13105       rs->btrace_config.bts.size = conf->bts.size;
13106     }
13107
13108   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13109   if (packet_config_support (packet) == PACKET_ENABLE
13110       && conf->pt.size != rs->btrace_config.pt.size)
13111     {
13112       pos = buf;
13113       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13114                         conf->pt.size);
13115
13116       putpkt (buf);
13117       getpkt (&buf, &rs->buf_size, 0);
13118
13119       if (packet_ok (buf, packet) == PACKET_ERROR)
13120         {
13121           if (buf[0] == 'E' && buf[1] == '.')
13122             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13123           else
13124             error (_("Failed to configure the trace buffer size."));
13125         }
13126
13127       rs->btrace_config.pt.size = conf->pt.size;
13128     }
13129 }
13130
13131 /* Read the current thread's btrace configuration from the target and
13132    store it into CONF.  */
13133
13134 static void
13135 btrace_read_config (struct btrace_config *conf)
13136 {
13137   gdb::optional<gdb::char_vector> xml
13138     = target_read_stralloc (&current_target, TARGET_OBJECT_BTRACE_CONF, "");
13139   if (xml)
13140     parse_xml_btrace_conf (conf, xml->data ());
13141 }
13142
13143 /* Maybe reopen target btrace.  */
13144
13145 static void
13146 remote_btrace_maybe_reopen (void)
13147 {
13148   struct remote_state *rs = get_remote_state ();
13149   struct thread_info *tp;
13150   int btrace_target_pushed = 0;
13151   int warned = 0;
13152
13153   scoped_restore_current_thread restore_thread;
13154
13155   ALL_NON_EXITED_THREADS (tp)
13156     {
13157       set_general_thread (tp->ptid);
13158
13159       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13160       btrace_read_config (&rs->btrace_config);
13161
13162       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13163         continue;
13164
13165 #if !defined (HAVE_LIBIPT)
13166       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13167         {
13168           if (!warned)
13169             {
13170               warned = 1;
13171               warning (_("Target is recording using Intel Processor Trace "
13172                          "but support was disabled at compile time."));
13173             }
13174
13175           continue;
13176         }
13177 #endif /* !defined (HAVE_LIBIPT) */
13178
13179       /* Push target, once, but before anything else happens.  This way our
13180          changes to the threads will be cleaned up by unpushing the target
13181          in case btrace_read_config () throws.  */
13182       if (!btrace_target_pushed)
13183         {
13184           btrace_target_pushed = 1;
13185           record_btrace_push_target ();
13186           printf_filtered (_("Target is recording using %s.\n"),
13187                            btrace_format_string (rs->btrace_config.format));
13188         }
13189
13190       tp->btrace.target = XCNEW (struct btrace_target_info);
13191       tp->btrace.target->ptid = tp->ptid;
13192       tp->btrace.target->conf = rs->btrace_config;
13193     }
13194 }
13195
13196 /* Enable branch tracing.  */
13197
13198 static struct btrace_target_info *
13199 remote_enable_btrace (struct target_ops *self, ptid_t ptid,
13200                       const struct btrace_config *conf)
13201 {
13202   struct btrace_target_info *tinfo = NULL;
13203   struct packet_config *packet = NULL;
13204   struct remote_state *rs = get_remote_state ();
13205   char *buf = rs->buf;
13206   char *endbuf = rs->buf + get_remote_packet_size ();
13207
13208   switch (conf->format)
13209     {
13210       case BTRACE_FORMAT_BTS:
13211         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13212         break;
13213
13214       case BTRACE_FORMAT_PT:
13215         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13216         break;
13217     }
13218
13219   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13220     error (_("Target does not support branch tracing."));
13221
13222   btrace_sync_conf (conf);
13223
13224   set_general_thread (ptid);
13225
13226   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13227   putpkt (rs->buf);
13228   getpkt (&rs->buf, &rs->buf_size, 0);
13229
13230   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13231     {
13232       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13233         error (_("Could not enable branch tracing for %s: %s"),
13234                target_pid_to_str (ptid), rs->buf + 2);
13235       else
13236         error (_("Could not enable branch tracing for %s."),
13237                target_pid_to_str (ptid));
13238     }
13239
13240   tinfo = XCNEW (struct btrace_target_info);
13241   tinfo->ptid = ptid;
13242
13243   /* If we fail to read the configuration, we lose some information, but the
13244      tracing itself is not impacted.  */
13245   TRY
13246     {
13247       btrace_read_config (&tinfo->conf);
13248     }
13249   CATCH (err, RETURN_MASK_ERROR)
13250     {
13251       if (err.message != NULL)
13252         warning ("%s", err.message);
13253     }
13254   END_CATCH
13255
13256   return tinfo;
13257 }
13258
13259 /* Disable branch tracing.  */
13260
13261 static void
13262 remote_disable_btrace (struct target_ops *self,
13263                        struct btrace_target_info *tinfo)
13264 {
13265   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13266   struct remote_state *rs = get_remote_state ();
13267   char *buf = rs->buf;
13268   char *endbuf = rs->buf + get_remote_packet_size ();
13269
13270   if (packet_config_support (packet) != PACKET_ENABLE)
13271     error (_("Target does not support branch tracing."));
13272
13273   set_general_thread (tinfo->ptid);
13274
13275   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13276   putpkt (rs->buf);
13277   getpkt (&rs->buf, &rs->buf_size, 0);
13278
13279   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13280     {
13281       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13282         error (_("Could not disable branch tracing for %s: %s"),
13283                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13284       else
13285         error (_("Could not disable branch tracing for %s."),
13286                target_pid_to_str (tinfo->ptid));
13287     }
13288
13289   xfree (tinfo);
13290 }
13291
13292 /* Teardown branch tracing.  */
13293
13294 static void
13295 remote_teardown_btrace (struct target_ops *self,
13296                         struct btrace_target_info *tinfo)
13297 {
13298   /* We must not talk to the target during teardown.  */
13299   xfree (tinfo);
13300 }
13301
13302 /* Read the branch trace.  */
13303
13304 static enum btrace_error
13305 remote_read_btrace (struct target_ops *self,
13306                     struct btrace_data *btrace,
13307                     struct btrace_target_info *tinfo,
13308                     enum btrace_read_type type)
13309 {
13310   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13311   const char *annex;
13312
13313   if (packet_config_support (packet) != PACKET_ENABLE)
13314     error (_("Target does not support branch tracing."));
13315
13316 #if !defined(HAVE_LIBEXPAT)
13317   error (_("Cannot process branch tracing result. XML parsing not supported."));
13318 #endif
13319
13320   switch (type)
13321     {
13322     case BTRACE_READ_ALL:
13323       annex = "all";
13324       break;
13325     case BTRACE_READ_NEW:
13326       annex = "new";
13327       break;
13328     case BTRACE_READ_DELTA:
13329       annex = "delta";
13330       break;
13331     default:
13332       internal_error (__FILE__, __LINE__,
13333                       _("Bad branch tracing read type: %u."),
13334                       (unsigned int) type);
13335     }
13336
13337   gdb::optional<gdb::char_vector> xml
13338     = target_read_stralloc (&current_target, TARGET_OBJECT_BTRACE, annex);
13339   if (!xml)
13340     return BTRACE_ERR_UNKNOWN;
13341
13342   parse_xml_btrace (btrace, xml->data ());
13343
13344   return BTRACE_ERR_NONE;
13345 }
13346
13347 static const struct btrace_config *
13348 remote_btrace_conf (struct target_ops *self,
13349                     const struct btrace_target_info *tinfo)
13350 {
13351   return &tinfo->conf;
13352 }
13353
13354 static int
13355 remote_augmented_libraries_svr4_read (struct target_ops *self)
13356 {
13357   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13358           == PACKET_ENABLE);
13359 }
13360
13361 /* Implementation of to_load.  */
13362
13363 static void
13364 remote_load (struct target_ops *self, const char *name, int from_tty)
13365 {
13366   generic_load (name, from_tty);
13367 }
13368
13369 /* Accepts an integer PID; returns a string representing a file that
13370    can be opened on the remote side to get the symbols for the child
13371    process.  Returns NULL if the operation is not supported.  */
13372
13373 static char *
13374 remote_pid_to_exec_file (struct target_ops *self, int pid)
13375 {
13376   static gdb::optional<gdb::char_vector> filename;
13377   struct inferior *inf;
13378   char *annex = NULL;
13379
13380   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13381     return NULL;
13382
13383   inf = find_inferior_pid (pid);
13384   if (inf == NULL)
13385     internal_error (__FILE__, __LINE__,
13386                     _("not currently attached to process %d"), pid);
13387
13388   if (!inf->fake_pid_p)
13389     {
13390       const int annex_size = 9;
13391
13392       annex = (char *) alloca (annex_size);
13393       xsnprintf (annex, annex_size, "%x", pid);
13394     }
13395
13396   filename = target_read_stralloc (&current_target,
13397                                    TARGET_OBJECT_EXEC_FILE, annex);
13398
13399   return filename ? filename->data () : nullptr;
13400 }
13401
13402 /* Implement the to_can_do_single_step target_ops method.  */
13403
13404 static int
13405 remote_can_do_single_step (struct target_ops *ops)
13406 {
13407   /* We can only tell whether target supports single step or not by
13408      supported s and S vCont actions if the stub supports vContSupported
13409      feature.  If the stub doesn't support vContSupported feature,
13410      we have conservatively to think target doesn't supports single
13411      step.  */
13412   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13413     {
13414       struct remote_state *rs = get_remote_state ();
13415
13416       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13417         remote_vcont_probe (rs);
13418
13419       return rs->supports_vCont.s && rs->supports_vCont.S;
13420     }
13421   else
13422     return 0;
13423 }
13424
13425 /* Implementation of the to_execution_direction method for the remote
13426    target.  */
13427
13428 static enum exec_direction_kind
13429 remote_execution_direction (struct target_ops *self)
13430 {
13431   struct remote_state *rs = get_remote_state ();
13432
13433   return rs->last_resume_exec_dir;
13434 }
13435
13436 /* Return pointer to the thread_info struct which corresponds to
13437    THREAD_HANDLE (having length HANDLE_LEN).  */
13438
13439 static struct thread_info *
13440 remote_thread_handle_to_thread_info (struct target_ops *ops,
13441                                      const gdb_byte *thread_handle,
13442                                      int handle_len,
13443                                      struct inferior *inf)
13444 {
13445   struct thread_info *tp;
13446
13447   ALL_NON_EXITED_THREADS (tp)
13448     {
13449       remote_thread_info *priv = get_remote_thread_info (tp);
13450
13451       if (tp->inf == inf && priv != NULL)
13452         {
13453           if (handle_len != priv->thread_handle.size ())
13454             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13455                    handle_len, priv->thread_handle.size ());
13456           if (memcmp (thread_handle, priv->thread_handle.data (),
13457                       handle_len) == 0)
13458             return tp;
13459         }
13460     }
13461
13462   return NULL;
13463 }
13464
13465 static void
13466 init_remote_ops (void)
13467 {
13468   remote_ops.to_shortname = "remote";
13469   remote_ops.to_longname = "Remote serial target in gdb-specific protocol";
13470   remote_ops.to_doc =
13471     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13472 Specify the serial device it is connected to\n\
13473 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).";
13474   remote_ops.to_open = remote_open;
13475   remote_ops.to_close = remote_close;
13476   remote_ops.to_detach = remote_detach;
13477   remote_ops.to_disconnect = remote_disconnect;
13478   remote_ops.to_resume = remote_resume;
13479   remote_ops.to_commit_resume = remote_commit_resume;
13480   remote_ops.to_wait = remote_wait;
13481   remote_ops.to_fetch_registers = remote_fetch_registers;
13482   remote_ops.to_store_registers = remote_store_registers;
13483   remote_ops.to_prepare_to_store = remote_prepare_to_store;
13484   remote_ops.to_files_info = remote_files_info;
13485   remote_ops.to_insert_breakpoint = remote_insert_breakpoint;
13486   remote_ops.to_remove_breakpoint = remote_remove_breakpoint;
13487   remote_ops.to_stopped_by_sw_breakpoint = remote_stopped_by_sw_breakpoint;
13488   remote_ops.to_supports_stopped_by_sw_breakpoint = remote_supports_stopped_by_sw_breakpoint;
13489   remote_ops.to_stopped_by_hw_breakpoint = remote_stopped_by_hw_breakpoint;
13490   remote_ops.to_supports_stopped_by_hw_breakpoint = remote_supports_stopped_by_hw_breakpoint;
13491   remote_ops.to_stopped_by_watchpoint = remote_stopped_by_watchpoint;
13492   remote_ops.to_stopped_data_address = remote_stopped_data_address;
13493   remote_ops.to_watchpoint_addr_within_range =
13494     remote_watchpoint_addr_within_range;
13495   remote_ops.to_can_use_hw_breakpoint = remote_check_watch_resources;
13496   remote_ops.to_insert_hw_breakpoint = remote_insert_hw_breakpoint;
13497   remote_ops.to_remove_hw_breakpoint = remote_remove_hw_breakpoint;
13498   remote_ops.to_region_ok_for_hw_watchpoint
13499      = remote_region_ok_for_hw_watchpoint;
13500   remote_ops.to_insert_watchpoint = remote_insert_watchpoint;
13501   remote_ops.to_remove_watchpoint = remote_remove_watchpoint;
13502   remote_ops.to_kill = remote_kill;
13503   remote_ops.to_load = remote_load;
13504   remote_ops.to_mourn_inferior = remote_mourn;
13505   remote_ops.to_pass_signals = remote_pass_signals;
13506   remote_ops.to_set_syscall_catchpoint = remote_set_syscall_catchpoint;
13507   remote_ops.to_program_signals = remote_program_signals;
13508   remote_ops.to_thread_alive = remote_thread_alive;
13509   remote_ops.to_thread_name = remote_thread_name;
13510   remote_ops.to_update_thread_list = remote_update_thread_list;
13511   remote_ops.to_pid_to_str = remote_pid_to_str;
13512   remote_ops.to_extra_thread_info = remote_threads_extra_info;
13513   remote_ops.to_get_ada_task_ptid = remote_get_ada_task_ptid;
13514   remote_ops.to_stop = remote_stop;
13515   remote_ops.to_interrupt = remote_interrupt;
13516   remote_ops.to_pass_ctrlc = remote_pass_ctrlc;
13517   remote_ops.to_xfer_partial = remote_xfer_partial;
13518   remote_ops.to_get_memory_xfer_limit = remote_get_memory_xfer_limit;
13519   remote_ops.to_rcmd = remote_rcmd;
13520   remote_ops.to_pid_to_exec_file = remote_pid_to_exec_file;
13521   remote_ops.to_log_command = serial_log_command;
13522   remote_ops.to_get_thread_local_address = remote_get_thread_local_address;
13523   remote_ops.to_stratum = process_stratum;
13524   remote_ops.to_has_all_memory = default_child_has_all_memory;
13525   remote_ops.to_has_memory = default_child_has_memory;
13526   remote_ops.to_has_stack = default_child_has_stack;
13527   remote_ops.to_has_registers = default_child_has_registers;
13528   remote_ops.to_has_execution = default_child_has_execution;
13529   remote_ops.to_has_thread_control = tc_schedlock;    /* can lock scheduler */
13530   remote_ops.to_can_execute_reverse = remote_can_execute_reverse;
13531   remote_ops.to_magic = OPS_MAGIC;
13532   remote_ops.to_memory_map = remote_memory_map;
13533   remote_ops.to_flash_erase = remote_flash_erase;
13534   remote_ops.to_flash_done = remote_flash_done;
13535   remote_ops.to_read_description = remote_read_description;
13536   remote_ops.to_search_memory = remote_search_memory;
13537   remote_ops.to_can_async_p = remote_can_async_p;
13538   remote_ops.to_is_async_p = remote_is_async_p;
13539   remote_ops.to_async = remote_async;
13540   remote_ops.to_thread_events = remote_thread_events;
13541   remote_ops.to_can_do_single_step = remote_can_do_single_step;
13542   remote_ops.to_terminal_inferior = remote_terminal_inferior;
13543   remote_ops.to_terminal_ours = remote_terminal_ours;
13544   remote_ops.to_supports_non_stop = remote_supports_non_stop;
13545   remote_ops.to_supports_multi_process = remote_supports_multi_process;
13546   remote_ops.to_supports_disable_randomization
13547     = remote_supports_disable_randomization;
13548   remote_ops.to_filesystem_is_local = remote_filesystem_is_local;
13549   remote_ops.to_fileio_open = remote_hostio_open;
13550   remote_ops.to_fileio_pwrite = remote_hostio_pwrite;
13551   remote_ops.to_fileio_pread = remote_hostio_pread;
13552   remote_ops.to_fileio_fstat = remote_hostio_fstat;
13553   remote_ops.to_fileio_close = remote_hostio_close;
13554   remote_ops.to_fileio_unlink = remote_hostio_unlink;
13555   remote_ops.to_fileio_readlink = remote_hostio_readlink;
13556   remote_ops.to_supports_enable_disable_tracepoint = remote_supports_enable_disable_tracepoint;
13557   remote_ops.to_supports_string_tracing = remote_supports_string_tracing;
13558   remote_ops.to_supports_evaluation_of_breakpoint_conditions = remote_supports_cond_breakpoints;
13559   remote_ops.to_can_run_breakpoint_commands = remote_can_run_breakpoint_commands;
13560   remote_ops.to_trace_init = remote_trace_init;
13561   remote_ops.to_download_tracepoint = remote_download_tracepoint;
13562   remote_ops.to_can_download_tracepoint = remote_can_download_tracepoint;
13563   remote_ops.to_download_trace_state_variable
13564     = remote_download_trace_state_variable;
13565   remote_ops.to_enable_tracepoint = remote_enable_tracepoint;
13566   remote_ops.to_disable_tracepoint = remote_disable_tracepoint;
13567   remote_ops.to_trace_set_readonly_regions = remote_trace_set_readonly_regions;
13568   remote_ops.to_trace_start = remote_trace_start;
13569   remote_ops.to_get_trace_status = remote_get_trace_status;
13570   remote_ops.to_get_tracepoint_status = remote_get_tracepoint_status;
13571   remote_ops.to_trace_stop = remote_trace_stop;
13572   remote_ops.to_trace_find = remote_trace_find;
13573   remote_ops.to_get_trace_state_variable_value
13574     = remote_get_trace_state_variable_value;
13575   remote_ops.to_save_trace_data = remote_save_trace_data;
13576   remote_ops.to_upload_tracepoints = remote_upload_tracepoints;
13577   remote_ops.to_upload_trace_state_variables
13578     = remote_upload_trace_state_variables;
13579   remote_ops.to_get_raw_trace_data = remote_get_raw_trace_data;
13580   remote_ops.to_get_min_fast_tracepoint_insn_len = remote_get_min_fast_tracepoint_insn_len;
13581   remote_ops.to_set_disconnected_tracing = remote_set_disconnected_tracing;
13582   remote_ops.to_set_circular_trace_buffer = remote_set_circular_trace_buffer;
13583   remote_ops.to_set_trace_buffer_size = remote_set_trace_buffer_size;
13584   remote_ops.to_set_trace_notes = remote_set_trace_notes;
13585   remote_ops.to_core_of_thread = remote_core_of_thread;
13586   remote_ops.to_verify_memory = remote_verify_memory;
13587   remote_ops.to_get_tib_address = remote_get_tib_address;
13588   remote_ops.to_set_permissions = remote_set_permissions;
13589   remote_ops.to_static_tracepoint_marker_at
13590     = remote_static_tracepoint_marker_at;
13591   remote_ops.to_static_tracepoint_markers_by_strid
13592     = remote_static_tracepoint_markers_by_strid;
13593   remote_ops.to_traceframe_info = remote_traceframe_info;
13594   remote_ops.to_use_agent = remote_use_agent;
13595   remote_ops.to_can_use_agent = remote_can_use_agent;
13596   remote_ops.to_enable_btrace = remote_enable_btrace;
13597   remote_ops.to_disable_btrace = remote_disable_btrace;
13598   remote_ops.to_teardown_btrace = remote_teardown_btrace;
13599   remote_ops.to_read_btrace = remote_read_btrace;
13600   remote_ops.to_btrace_conf = remote_btrace_conf;
13601   remote_ops.to_augmented_libraries_svr4_read =
13602     remote_augmented_libraries_svr4_read;
13603   remote_ops.to_follow_fork = remote_follow_fork;
13604   remote_ops.to_follow_exec = remote_follow_exec;
13605   remote_ops.to_insert_fork_catchpoint = remote_insert_fork_catchpoint;
13606   remote_ops.to_remove_fork_catchpoint = remote_remove_fork_catchpoint;
13607   remote_ops.to_insert_vfork_catchpoint = remote_insert_vfork_catchpoint;
13608   remote_ops.to_remove_vfork_catchpoint = remote_remove_vfork_catchpoint;
13609   remote_ops.to_insert_exec_catchpoint = remote_insert_exec_catchpoint;
13610   remote_ops.to_remove_exec_catchpoint = remote_remove_exec_catchpoint;
13611   remote_ops.to_execution_direction = remote_execution_direction;
13612   remote_ops.to_thread_handle_to_thread_info =
13613     remote_thread_handle_to_thread_info;
13614 }
13615
13616 /* Set up the extended remote vector by making a copy of the standard
13617    remote vector and adding to it.  */
13618
13619 static void
13620 init_extended_remote_ops (void)
13621 {
13622   extended_remote_ops = remote_ops;
13623
13624   extended_remote_ops.to_shortname = "extended-remote";
13625   extended_remote_ops.to_longname =
13626     "Extended remote serial target in gdb-specific protocol";
13627   extended_remote_ops.to_doc =
13628     "Use a remote computer via a serial line, using a gdb-specific protocol.\n\
13629 Specify the serial device it is connected to (e.g. /dev/ttya).";
13630   extended_remote_ops.to_open = extended_remote_open;
13631   extended_remote_ops.to_create_inferior = extended_remote_create_inferior;
13632   extended_remote_ops.to_detach = extended_remote_detach;
13633   extended_remote_ops.to_attach = extended_remote_attach;
13634   extended_remote_ops.to_post_attach = extended_remote_post_attach;
13635   extended_remote_ops.to_supports_disable_randomization
13636     = extended_remote_supports_disable_randomization;
13637 }
13638
13639 static int
13640 remote_can_async_p (struct target_ops *ops)
13641 {
13642   struct remote_state *rs = get_remote_state ();
13643
13644   /* We don't go async if the user has explicitly prevented it with the
13645      "maint set target-async" command.  */
13646   if (!target_async_permitted)
13647     return 0;
13648
13649   /* We're async whenever the serial device is.  */
13650   return serial_can_async_p (rs->remote_desc);
13651 }
13652
13653 static int
13654 remote_is_async_p (struct target_ops *ops)
13655 {
13656   struct remote_state *rs = get_remote_state ();
13657
13658   if (!target_async_permitted)
13659     /* We only enable async when the user specifically asks for it.  */
13660     return 0;
13661
13662   /* We're async whenever the serial device is.  */
13663   return serial_is_async_p (rs->remote_desc);
13664 }
13665
13666 /* Pass the SERIAL event on and up to the client.  One day this code
13667    will be able to delay notifying the client of an event until the
13668    point where an entire packet has been received.  */
13669
13670 static serial_event_ftype remote_async_serial_handler;
13671
13672 static void
13673 remote_async_serial_handler (struct serial *scb, void *context)
13674 {
13675   /* Don't propogate error information up to the client.  Instead let
13676      the client find out about the error by querying the target.  */
13677   inferior_event_handler (INF_REG_EVENT, NULL);
13678 }
13679
13680 static void
13681 remote_async_inferior_event_handler (gdb_client_data data)
13682 {
13683   inferior_event_handler (INF_REG_EVENT, NULL);
13684 }
13685
13686 static void
13687 remote_async (struct target_ops *ops, int enable)
13688 {
13689   struct remote_state *rs = get_remote_state ();
13690
13691   if (enable)
13692     {
13693       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
13694
13695       /* If there are pending events in the stop reply queue tell the
13696          event loop to process them.  */
13697       if (!QUEUE_is_empty (stop_reply_p, stop_reply_queue))
13698         mark_async_event_handler (remote_async_inferior_event_token);
13699       /* For simplicity, below we clear the pending events token
13700          without remembering whether it is marked, so here we always
13701          mark it.  If there's actually no pending notification to
13702          process, this ends up being a no-op (other than a spurious
13703          event-loop wakeup).  */
13704       if (target_is_non_stop_p ())
13705         mark_async_event_handler (rs->notif_state->get_pending_events_token);
13706     }
13707   else
13708     {
13709       serial_async (rs->remote_desc, NULL, NULL);
13710       /* If the core is disabling async, it doesn't want to be
13711          disturbed with target events.  Clear all async event sources
13712          too.  */
13713       clear_async_event_handler (remote_async_inferior_event_token);
13714       if (target_is_non_stop_p ())
13715         clear_async_event_handler (rs->notif_state->get_pending_events_token);
13716     }
13717 }
13718
13719 /* Implementation of the to_thread_events method.  */
13720
13721 static void
13722 remote_thread_events (struct target_ops *ops, int enable)
13723 {
13724   struct remote_state *rs = get_remote_state ();
13725   size_t size = get_remote_packet_size ();
13726
13727   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
13728     return;
13729
13730   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
13731   putpkt (rs->buf);
13732   getpkt (&rs->buf, &rs->buf_size, 0);
13733
13734   switch (packet_ok (rs->buf,
13735                      &remote_protocol_packets[PACKET_QThreadEvents]))
13736     {
13737     case PACKET_OK:
13738       if (strcmp (rs->buf, "OK") != 0)
13739         error (_("Remote refused setting thread events: %s"), rs->buf);
13740       break;
13741     case PACKET_ERROR:
13742       warning (_("Remote failure reply: %s"), rs->buf);
13743       break;
13744     case PACKET_UNKNOWN:
13745       break;
13746     }
13747 }
13748
13749 static void
13750 set_remote_cmd (const char *args, int from_tty)
13751 {
13752   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
13753 }
13754
13755 static void
13756 show_remote_cmd (const char *args, int from_tty)
13757 {
13758   /* We can't just use cmd_show_list here, because we want to skip
13759      the redundant "show remote Z-packet" and the legacy aliases.  */
13760   struct cmd_list_element *list = remote_show_cmdlist;
13761   struct ui_out *uiout = current_uiout;
13762
13763   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
13764   for (; list != NULL; list = list->next)
13765     if (strcmp (list->name, "Z-packet") == 0)
13766       continue;
13767     else if (list->type == not_set_cmd)
13768       /* Alias commands are exactly like the original, except they
13769          don't have the normal type.  */
13770       continue;
13771     else
13772       {
13773         ui_out_emit_tuple option_emitter (uiout, "option");
13774
13775         uiout->field_string ("name", list->name);
13776         uiout->text (":  ");
13777         if (list->type == show_cmd)
13778           do_show_command (NULL, from_tty, list);
13779         else
13780           cmd_func (list, NULL, from_tty);
13781       }
13782 }
13783
13784
13785 /* Function to be called whenever a new objfile (shlib) is detected.  */
13786 static void
13787 remote_new_objfile (struct objfile *objfile)
13788 {
13789   struct remote_state *rs = get_remote_state ();
13790
13791   if (rs->remote_desc != 0)             /* Have a remote connection.  */
13792     remote_check_symbols ();
13793 }
13794
13795 /* Pull all the tracepoints defined on the target and create local
13796    data structures representing them.  We don't want to create real
13797    tracepoints yet, we don't want to mess up the user's existing
13798    collection.  */
13799   
13800 static int
13801 remote_upload_tracepoints (struct target_ops *self, struct uploaded_tp **utpp)
13802 {
13803   struct remote_state *rs = get_remote_state ();
13804   char *p;
13805
13806   /* Ask for a first packet of tracepoint definition.  */
13807   putpkt ("qTfP");
13808   getpkt (&rs->buf, &rs->buf_size, 0);
13809   p = rs->buf;
13810   while (*p && *p != 'l')
13811     {
13812       parse_tracepoint_definition (p, utpp);
13813       /* Ask for another packet of tracepoint definition.  */
13814       putpkt ("qTsP");
13815       getpkt (&rs->buf, &rs->buf_size, 0);
13816       p = rs->buf;
13817     }
13818   return 0;
13819 }
13820
13821 static int
13822 remote_upload_trace_state_variables (struct target_ops *self,
13823                                      struct uploaded_tsv **utsvp)
13824 {
13825   struct remote_state *rs = get_remote_state ();
13826   char *p;
13827
13828   /* Ask for a first packet of variable definition.  */
13829   putpkt ("qTfV");
13830   getpkt (&rs->buf, &rs->buf_size, 0);
13831   p = rs->buf;
13832   while (*p && *p != 'l')
13833     {
13834       parse_tsv_definition (p, utsvp);
13835       /* Ask for another packet of variable definition.  */
13836       putpkt ("qTsV");
13837       getpkt (&rs->buf, &rs->buf_size, 0);
13838       p = rs->buf;
13839     }
13840   return 0;
13841 }
13842
13843 /* The "set/show range-stepping" show hook.  */
13844
13845 static void
13846 show_range_stepping (struct ui_file *file, int from_tty,
13847                      struct cmd_list_element *c,
13848                      const char *value)
13849 {
13850   fprintf_filtered (file,
13851                     _("Debugger's willingness to use range stepping "
13852                       "is %s.\n"), value);
13853 }
13854
13855 /* The "set/show range-stepping" set hook.  */
13856
13857 static void
13858 set_range_stepping (const char *ignore_args, int from_tty,
13859                     struct cmd_list_element *c)
13860 {
13861   struct remote_state *rs = get_remote_state ();
13862
13863   /* Whene enabling, check whether range stepping is actually
13864      supported by the target, and warn if not.  */
13865   if (use_range_stepping)
13866     {
13867       if (rs->remote_desc != NULL)
13868         {
13869           if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13870             remote_vcont_probe (rs);
13871
13872           if (packet_support (PACKET_vCont) == PACKET_ENABLE
13873               && rs->supports_vCont.r)
13874             return;
13875         }
13876
13877       warning (_("Range stepping is not supported by the current target"));
13878     }
13879 }
13880
13881 void
13882 _initialize_remote (void)
13883 {
13884   struct cmd_list_element *cmd;
13885   const char *cmd_name;
13886
13887   /* architecture specific data */
13888   remote_gdbarch_data_handle =
13889     gdbarch_data_register_post_init (init_remote_state);
13890   remote_g_packet_data_handle =
13891     gdbarch_data_register_pre_init (remote_g_packet_data_init);
13892
13893   remote_pspace_data
13894     = register_program_space_data_with_cleanup (NULL,
13895                                                 remote_pspace_data_cleanup);
13896
13897   /* Initialize the per-target state.  At the moment there is only one
13898      of these, not one per target.  Only one target is active at a
13899      time.  */
13900   remote_state = new_remote_state ();
13901
13902   init_remote_ops ();
13903   add_target (&remote_ops);
13904
13905   init_extended_remote_ops ();
13906   add_target (&extended_remote_ops);
13907
13908   /* Hook into new objfile notification.  */
13909   gdb::observers::new_objfile.attach (remote_new_objfile);
13910   /* We're no longer interested in notification events of an inferior
13911      when it exits.  */
13912   gdb::observers::inferior_exit.attach (discard_pending_stop_replies);
13913
13914 #if 0
13915   init_remote_threadtests ();
13916 #endif
13917
13918   stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
13919   /* set/show remote ...  */
13920
13921   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
13922 Remote protocol specific variables\n\
13923 Configure various remote-protocol specific variables such as\n\
13924 the packets being used"),
13925                   &remote_set_cmdlist, "set remote ",
13926                   0 /* allow-unknown */, &setlist);
13927   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
13928 Remote protocol specific variables\n\
13929 Configure various remote-protocol specific variables such as\n\
13930 the packets being used"),
13931                   &remote_show_cmdlist, "show remote ",
13932                   0 /* allow-unknown */, &showlist);
13933
13934   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
13935 Compare section data on target to the exec file.\n\
13936 Argument is a single section name (default: all loaded sections).\n\
13937 To compare only read-only loaded sections, specify the -r option."),
13938            &cmdlist);
13939
13940   add_cmd ("packet", class_maintenance, packet_command, _("\
13941 Send an arbitrary packet to a remote target.\n\
13942    maintenance packet TEXT\n\
13943 If GDB is talking to an inferior via the GDB serial protocol, then\n\
13944 this command sends the string TEXT to the inferior, and displays the\n\
13945 response packet.  GDB supplies the initial `$' character, and the\n\
13946 terminating `#' character and checksum."),
13947            &maintenancelist);
13948
13949   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
13950 Set whether to send break if interrupted."), _("\
13951 Show whether to send break if interrupted."), _("\
13952 If set, a break, instead of a cntrl-c, is sent to the remote target."),
13953                            set_remotebreak, show_remotebreak,
13954                            &setlist, &showlist);
13955   cmd_name = "remotebreak";
13956   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
13957   deprecate_cmd (cmd, "set remote interrupt-sequence");
13958   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
13959   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
13960   deprecate_cmd (cmd, "show remote interrupt-sequence");
13961
13962   add_setshow_enum_cmd ("interrupt-sequence", class_support,
13963                         interrupt_sequence_modes, &interrupt_sequence_mode,
13964                         _("\
13965 Set interrupt sequence to remote target."), _("\
13966 Show interrupt sequence to remote target."), _("\
13967 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
13968                         NULL, show_interrupt_sequence,
13969                         &remote_set_cmdlist,
13970                         &remote_show_cmdlist);
13971
13972   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
13973                            &interrupt_on_connect, _("\
13974 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
13975 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
13976 If set, interrupt sequence is sent to remote target."),
13977                            NULL, NULL,
13978                            &remote_set_cmdlist, &remote_show_cmdlist);
13979
13980   /* Install commands for configuring memory read/write packets.  */
13981
13982   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
13983 Set the maximum number of bytes per memory write packet (deprecated)."),
13984            &setlist);
13985   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
13986 Show the maximum number of bytes per memory write packet (deprecated)."),
13987            &showlist);
13988   add_cmd ("memory-write-packet-size", no_class,
13989            set_memory_write_packet_size, _("\
13990 Set the maximum number of bytes per memory-write packet.\n\
13991 Specify the number of bytes in a packet or 0 (zero) for the\n\
13992 default packet size.  The actual limit is further reduced\n\
13993 dependent on the target.  Specify ``fixed'' to disable the\n\
13994 further restriction and ``limit'' to enable that restriction."),
13995            &remote_set_cmdlist);
13996   add_cmd ("memory-read-packet-size", no_class,
13997            set_memory_read_packet_size, _("\
13998 Set the maximum number of bytes per memory-read packet.\n\
13999 Specify the number of bytes in a packet or 0 (zero) for the\n\
14000 default packet size.  The actual limit is further reduced\n\
14001 dependent on the target.  Specify ``fixed'' to disable the\n\
14002 further restriction and ``limit'' to enable that restriction."),
14003            &remote_set_cmdlist);
14004   add_cmd ("memory-write-packet-size", no_class,
14005            show_memory_write_packet_size,
14006            _("Show the maximum number of bytes per memory-write packet."),
14007            &remote_show_cmdlist);
14008   add_cmd ("memory-read-packet-size", no_class,
14009            show_memory_read_packet_size,
14010            _("Show the maximum number of bytes per memory-read packet."),
14011            &remote_show_cmdlist);
14012
14013   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14014                             &remote_hw_watchpoint_limit, _("\
14015 Set the maximum number of target hardware watchpoints."), _("\
14016 Show the maximum number of target hardware watchpoints."), _("\
14017 Specify a negative limit for unlimited."),
14018                             NULL, NULL, /* FIXME: i18n: The maximum
14019                                            number of target hardware
14020                                            watchpoints is %s.  */
14021                             &remote_set_cmdlist, &remote_show_cmdlist);
14022   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14023                             &remote_hw_watchpoint_length_limit, _("\
14024 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14025 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14026 Specify a negative limit for unlimited."),
14027                             NULL, NULL, /* FIXME: i18n: The maximum
14028                                            length (in bytes) of a target
14029                                            hardware watchpoint is %s.  */
14030                             &remote_set_cmdlist, &remote_show_cmdlist);
14031   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14032                             &remote_hw_breakpoint_limit, _("\
14033 Set the maximum number of target hardware breakpoints."), _("\
14034 Show the maximum number of target hardware breakpoints."), _("\
14035 Specify a negative limit for unlimited."),
14036                             NULL, NULL, /* FIXME: i18n: The maximum
14037                                            number of target hardware
14038                                            breakpoints is %s.  */
14039                             &remote_set_cmdlist, &remote_show_cmdlist);
14040
14041   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14042                              &remote_address_size, _("\
14043 Set the maximum size of the address (in bits) in a memory packet."), _("\
14044 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14045                              NULL,
14046                              NULL, /* FIXME: i18n: */
14047                              &setlist, &showlist);
14048
14049   init_all_packet_configs ();
14050
14051   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14052                          "X", "binary-download", 1);
14053
14054   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14055                          "vCont", "verbose-resume", 0);
14056
14057   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14058                          "QPassSignals", "pass-signals", 0);
14059
14060   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14061                          "QCatchSyscalls", "catch-syscalls", 0);
14062
14063   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14064                          "QProgramSignals", "program-signals", 0);
14065
14066   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14067                          "QSetWorkingDir", "set-working-dir", 0);
14068
14069   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14070                          "QStartupWithShell", "startup-with-shell", 0);
14071
14072   add_packet_config_cmd (&remote_protocol_packets
14073                          [PACKET_QEnvironmentHexEncoded],
14074                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14075                          0);
14076
14077   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14078                          "QEnvironmentReset", "environment-reset",
14079                          0);
14080
14081   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14082                          "QEnvironmentUnset", "environment-unset",
14083                          0);
14084
14085   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14086                          "qSymbol", "symbol-lookup", 0);
14087
14088   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14089                          "P", "set-register", 1);
14090
14091   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14092                          "p", "fetch-register", 1);
14093
14094   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14095                          "Z0", "software-breakpoint", 0);
14096
14097   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14098                          "Z1", "hardware-breakpoint", 0);
14099
14100   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14101                          "Z2", "write-watchpoint", 0);
14102
14103   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14104                          "Z3", "read-watchpoint", 0);
14105
14106   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14107                          "Z4", "access-watchpoint", 0);
14108
14109   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14110                          "qXfer:auxv:read", "read-aux-vector", 0);
14111
14112   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14113                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14114
14115   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14116                          "qXfer:features:read", "target-features", 0);
14117
14118   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14119                          "qXfer:libraries:read", "library-info", 0);
14120
14121   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14122                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14123
14124   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14125                          "qXfer:memory-map:read", "memory-map", 0);
14126
14127   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14128                          "qXfer:spu:read", "read-spu-object", 0);
14129
14130   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14131                          "qXfer:spu:write", "write-spu-object", 0);
14132
14133   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14134                         "qXfer:osdata:read", "osdata", 0);
14135
14136   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14137                          "qXfer:threads:read", "threads", 0);
14138
14139   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14140                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14141
14142   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14143                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14144
14145   add_packet_config_cmd
14146     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14147      "qXfer:traceframe-info:read", "traceframe-info", 0);
14148
14149   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14150                          "qXfer:uib:read", "unwind-info-block", 0);
14151
14152   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14153                          "qGetTLSAddr", "get-thread-local-storage-address",
14154                          0);
14155
14156   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14157                          "qGetTIBAddr", "get-thread-information-block-address",
14158                          0);
14159
14160   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14161                          "bc", "reverse-continue", 0);
14162
14163   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14164                          "bs", "reverse-step", 0);
14165
14166   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14167                          "qSupported", "supported-packets", 0);
14168
14169   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14170                          "qSearch:memory", "search-memory", 0);
14171
14172   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14173                          "qTStatus", "trace-status", 0);
14174
14175   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14176                          "vFile:setfs", "hostio-setfs", 0);
14177
14178   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14179                          "vFile:open", "hostio-open", 0);
14180
14181   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14182                          "vFile:pread", "hostio-pread", 0);
14183
14184   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14185                          "vFile:pwrite", "hostio-pwrite", 0);
14186
14187   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14188                          "vFile:close", "hostio-close", 0);
14189
14190   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14191                          "vFile:unlink", "hostio-unlink", 0);
14192
14193   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14194                          "vFile:readlink", "hostio-readlink", 0);
14195
14196   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14197                          "vFile:fstat", "hostio-fstat", 0);
14198
14199   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14200                          "vAttach", "attach", 0);
14201
14202   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14203                          "vRun", "run", 0);
14204
14205   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14206                          "QStartNoAckMode", "noack", 0);
14207
14208   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14209                          "vKill", "kill", 0);
14210
14211   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14212                          "qAttached", "query-attached", 0);
14213
14214   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14215                          "ConditionalTracepoints",
14216                          "conditional-tracepoints", 0);
14217
14218   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14219                          "ConditionalBreakpoints",
14220                          "conditional-breakpoints", 0);
14221
14222   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14223                          "BreakpointCommands",
14224                          "breakpoint-commands", 0);
14225
14226   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14227                          "FastTracepoints", "fast-tracepoints", 0);
14228
14229   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14230                          "TracepointSource", "TracepointSource", 0);
14231
14232   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14233                          "QAllow", "allow", 0);
14234
14235   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14236                          "StaticTracepoints", "static-tracepoints", 0);
14237
14238   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14239                          "InstallInTrace", "install-in-trace", 0);
14240
14241   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14242                          "qXfer:statictrace:read", "read-sdata-object", 0);
14243
14244   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14245                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14246
14247   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14248                          "QDisableRandomization", "disable-randomization", 0);
14249
14250   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14251                          "QAgent", "agent", 0);
14252
14253   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14254                          "QTBuffer:size", "trace-buffer-size", 0);
14255
14256   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14257        "Qbtrace:off", "disable-btrace", 0);
14258
14259   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14260        "Qbtrace:bts", "enable-btrace-bts", 0);
14261
14262   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14263        "Qbtrace:pt", "enable-btrace-pt", 0);
14264
14265   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14266        "qXfer:btrace", "read-btrace", 0);
14267
14268   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14269        "qXfer:btrace-conf", "read-btrace-conf", 0);
14270
14271   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14272        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14273
14274   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14275        "multiprocess-feature", "multiprocess-feature", 0);
14276
14277   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14278                          "swbreak-feature", "swbreak-feature", 0);
14279
14280   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14281                          "hwbreak-feature", "hwbreak-feature", 0);
14282
14283   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14284                          "fork-event-feature", "fork-event-feature", 0);
14285
14286   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14287                          "vfork-event-feature", "vfork-event-feature", 0);
14288
14289   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14290        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14291
14292   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14293                          "vContSupported", "verbose-resume-supported", 0);
14294
14295   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14296                          "exec-event-feature", "exec-event-feature", 0);
14297
14298   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14299                          "vCtrlC", "ctrl-c", 0);
14300
14301   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14302                          "QThreadEvents", "thread-events", 0);
14303
14304   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14305                          "N stop reply", "no-resumed-stop-reply", 0);
14306
14307   /* Assert that we've registered "set remote foo-packet" commands
14308      for all packet configs.  */
14309   {
14310     int i;
14311
14312     for (i = 0; i < PACKET_MAX; i++)
14313       {
14314         /* Ideally all configs would have a command associated.  Some
14315            still don't though.  */
14316         int excepted;
14317
14318         switch (i)
14319           {
14320           case PACKET_QNonStop:
14321           case PACKET_EnableDisableTracepoints_feature:
14322           case PACKET_tracenz_feature:
14323           case PACKET_DisconnectedTracing_feature:
14324           case PACKET_augmented_libraries_svr4_read_feature:
14325           case PACKET_qCRC:
14326             /* Additions to this list need to be well justified:
14327                pre-existing packets are OK; new packets are not.  */
14328             excepted = 1;
14329             break;
14330           default:
14331             excepted = 0;
14332             break;
14333           }
14334
14335         /* This catches both forgetting to add a config command, and
14336            forgetting to remove a packet from the exception list.  */
14337         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14338       }
14339   }
14340
14341   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14342      Z sub-packet has its own set and show commands, but users may
14343      have sets to this variable in their .gdbinit files (or in their
14344      documentation).  */
14345   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14346                                 &remote_Z_packet_detect, _("\
14347 Set use of remote protocol `Z' packets"), _("\
14348 Show use of remote protocol `Z' packets "), _("\
14349 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14350 packets."),
14351                                 set_remote_protocol_Z_packet_cmd,
14352                                 show_remote_protocol_Z_packet_cmd,
14353                                 /* FIXME: i18n: Use of remote protocol
14354                                    `Z' packets is %s.  */
14355                                 &remote_set_cmdlist, &remote_show_cmdlist);
14356
14357   add_prefix_cmd ("remote", class_files, remote_command, _("\
14358 Manipulate files on the remote system\n\
14359 Transfer files to and from the remote target system."),
14360                   &remote_cmdlist, "remote ",
14361                   0 /* allow-unknown */, &cmdlist);
14362
14363   add_cmd ("put", class_files, remote_put_command,
14364            _("Copy a local file to the remote system."),
14365            &remote_cmdlist);
14366
14367   add_cmd ("get", class_files, remote_get_command,
14368            _("Copy a remote file to the local system."),
14369            &remote_cmdlist);
14370
14371   add_cmd ("delete", class_files, remote_delete_command,
14372            _("Delete a remote file."),
14373            &remote_cmdlist);
14374
14375   add_setshow_string_noescape_cmd ("exec-file", class_files,
14376                                    &remote_exec_file_var, _("\
14377 Set the remote pathname for \"run\""), _("\
14378 Show the remote pathname for \"run\""), NULL,
14379                                    set_remote_exec_file,
14380                                    show_remote_exec_file,
14381                                    &remote_set_cmdlist,
14382                                    &remote_show_cmdlist);
14383
14384   add_setshow_boolean_cmd ("range-stepping", class_run,
14385                            &use_range_stepping, _("\
14386 Enable or disable range stepping."), _("\
14387 Show whether target-assisted range stepping is enabled."), _("\
14388 If on, and the target supports it, when stepping a source line, GDB\n\
14389 tells the target to step the corresponding range of addresses itself instead\n\
14390 of issuing multiple single-steps.  This speeds up source level\n\
14391 stepping.  If off, GDB always issues single-steps, even if range\n\
14392 stepping is supported by the target.  The default is on."),
14393                            set_range_stepping,
14394                            show_range_stepping,
14395                            &setlist,
14396                            &showlist);
14397
14398   /* Eventually initialize fileio.  See fileio.c */
14399   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14400
14401   /* Take advantage of the fact that the TID field is not used, to tag
14402      special ptids with it set to != 0.  */
14403   magic_null_ptid = ptid_build (42000, -1, 1);
14404   not_sent_ptid = ptid_build (42000, -2, 1);
14405   any_thread_ptid = ptid_build (42000, 0, 1);
14406 }