Fix crash with empty Rust enum
[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 #include <unordered_map>
79
80 /* The remote target.  */
81
82 static const char remote_doc[] = N_("\
83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84 Specify the serial device it is connected to\n\
85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
87 #define OPAQUETHREADBYTES 8
88
89 /* a 64 bit opaque identifier */
90 typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92 struct gdb_ext_thread_info;
93 struct threads_listing_context;
94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
95 struct protocol_feature;
96 struct packet_reg;
97
98 struct stop_reply;
99 static void stop_reply_xfree (struct stop_reply *);
100
101 struct stop_reply_deleter
102 {
103   void operator() (stop_reply *r) const
104   {
105     stop_reply_xfree (r);
106   }
107 };
108
109 typedef std::unique_ptr<stop_reply, stop_reply_deleter> stop_reply_up;
110
111 /* Generic configuration support for packets the stub optionally
112    supports.  Allows the user to specify the use of the packet as well
113    as allowing GDB to auto-detect support in the remote stub.  */
114
115 enum packet_support
116   {
117     PACKET_SUPPORT_UNKNOWN = 0,
118     PACKET_ENABLE,
119     PACKET_DISABLE
120   };
121
122 /* Analyze a packet's return value and update the packet config
123    accordingly.  */
124
125 enum packet_result
126 {
127   PACKET_ERROR,
128   PACKET_OK,
129   PACKET_UNKNOWN
130 };
131
132 struct threads_listing_context;
133
134 /* Stub vCont actions support.
135
136    Each field is a boolean flag indicating whether the stub reports
137    support for the corresponding action.  */
138
139 struct vCont_action_support
140 {
141   /* vCont;t */
142   bool t = false;
143
144   /* vCont;r */
145   bool r = false;
146
147   /* vCont;s */
148   bool s = false;
149
150   /* vCont;S */
151   bool S = false;
152 };
153
154 /* About this many threadisds fit in a packet.  */
155
156 #define MAXTHREADLISTRESULTS 32
157
158 /* Data for the vFile:pread readahead cache.  */
159
160 struct readahead_cache
161 {
162   /* Invalidate the readahead cache.  */
163   void invalidate ();
164
165   /* Invalidate the readahead cache if it is holding data for FD.  */
166   void invalidate_fd (int fd);
167
168   /* Serve pread from the readahead cache.  Returns number of bytes
169      read, or 0 if the request can't be served from the cache.  */
170   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
171
172   /* The file descriptor for the file that is being cached.  -1 if the
173      cache is invalid.  */
174   int fd = -1;
175
176   /* The offset into the file that the cache buffer corresponds
177      to.  */
178   ULONGEST offset = 0;
179
180   /* The buffer holding the cache contents.  */
181   gdb_byte *buf = nullptr;
182   /* The buffer's size.  We try to read as much as fits into a packet
183      at a time.  */
184   size_t bufsize = 0;
185
186   /* Cache hit and miss counters.  */
187   ULONGEST hit_count = 0;
188   ULONGEST miss_count = 0;
189 };
190
191 /* Description of the remote protocol for a given architecture.  */
192
193 struct packet_reg
194 {
195   long offset; /* Offset into G packet.  */
196   long regnum; /* GDB's internal register number.  */
197   LONGEST pnum; /* Remote protocol register number.  */
198   int in_g_packet; /* Always part of G packet.  */
199   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
200      at present.  */
201   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
202      at present.  */
203 };
204
205 struct remote_arch_state
206 {
207   explicit remote_arch_state (struct gdbarch *gdbarch);
208
209   /* Description of the remote protocol registers.  */
210   long sizeof_g_packet;
211
212   /* Description of the remote protocol registers indexed by REGNUM
213      (making an array gdbarch_num_regs in size).  */
214   std::unique_ptr<packet_reg[]> regs;
215
216   /* This is the size (in chars) of the first response to the ``g''
217      packet.  It is used as a heuristic when determining the maximum
218      size of memory-read and memory-write packets.  A target will
219      typically only reserve a buffer large enough to hold the ``g''
220      packet.  The size does not include packet overhead (headers and
221      trailers).  */
222   long actual_register_packet_size;
223
224   /* This is the maximum size (in chars) of a non read/write packet.
225      It is also used as a cap on the size of read/write packets.  */
226   long remote_packet_size;
227 };
228
229 /* Description of the remote protocol state for the currently
230    connected target.  This is per-target state, and independent of the
231    selected architecture.  */
232
233 class remote_state
234 {
235 public:
236
237   remote_state ();
238   ~remote_state ();
239
240   /* Get the remote arch state for GDBARCH.  */
241   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
242
243 public: /* data */
244
245   /* A buffer to use for incoming packets, and its current size.  The
246      buffer is grown dynamically for larger incoming packets.
247      Outgoing packets may also be constructed in this buffer.
248      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
249      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
250      packets.  */
251   char *buf;
252   long buf_size;
253
254   /* True if we're going through initial connection setup (finding out
255      about the remote side's threads, relocating symbols, etc.).  */
256   bool starting_up = false;
257
258   /* If we negotiated packet size explicitly (and thus can bypass
259      heuristics for the largest packet size that will not overflow
260      a buffer in the stub), this will be set to that packet size.
261      Otherwise zero, meaning to use the guessed size.  */
262   long explicit_packet_size = 0;
263
264   /* remote_wait is normally called when the target is running and
265      waits for a stop reply packet.  But sometimes we need to call it
266      when the target is already stopped.  We can send a "?" packet
267      and have remote_wait read the response.  Or, if we already have
268      the response, we can stash it in BUF and tell remote_wait to
269      skip calling getpkt.  This flag is set when BUF contains a
270      stop reply packet and the target is not waiting.  */
271   int cached_wait_status = 0;
272
273   /* True, if in no ack mode.  That is, neither GDB nor the stub will
274      expect acks from each other.  The connection is assumed to be
275      reliable.  */
276   bool noack_mode = false;
277
278   /* True if we're connected in extended remote mode.  */
279   bool extended = false;
280
281   /* True if we resumed the target and we're waiting for the target to
282      stop.  In the mean time, we can't start another command/query.
283      The remote server wouldn't be ready to process it, so we'd
284      timeout waiting for a reply that would never come and eventually
285      we'd close the connection.  This can happen in asynchronous mode
286      because we allow GDB commands while the target is running.  */
287   bool waiting_for_stop_reply = false;
288
289   /* The status of the stub support for the various vCont actions.  */
290   vCont_action_support supports_vCont;
291
292   /* True if the user has pressed Ctrl-C, but the target hasn't
293      responded to that.  */
294   bool ctrlc_pending_p = false;
295
296   /* True if we saw a Ctrl-C while reading or writing from/to the
297      remote descriptor.  At that point it is not safe to send a remote
298      interrupt packet, so we instead remember we saw the Ctrl-C and
299      process it once we're done with sending/receiving the current
300      packet, which should be shortly.  If however that takes too long,
301      and the user presses Ctrl-C again, we offer to disconnect.  */
302   bool got_ctrlc_during_io = false;
303
304   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
305      remote_open knows that we don't have a file open when the program
306      starts.  */
307   struct serial *remote_desc = nullptr;
308
309   /* These are the threads which we last sent to the remote system.  The
310      TID member will be -1 for all or -2 for not sent yet.  */
311   ptid_t general_thread = null_ptid;
312   ptid_t continue_thread = null_ptid;
313
314   /* This is the traceframe which we last selected on the remote system.
315      It will be -1 if no traceframe is selected.  */
316   int remote_traceframe_number = -1;
317
318   char *last_pass_packet = nullptr;
319
320   /* The last QProgramSignals packet sent to the target.  We bypass
321      sending a new program signals list down to the target if the new
322      packet is exactly the same as the last we sent.  IOW, we only let
323      the target know about program signals list changes.  */
324   char *last_program_signals_packet = nullptr;
325
326   gdb_signal last_sent_signal = GDB_SIGNAL_0;
327
328   bool last_sent_step = false;
329
330   /* The execution direction of the last resume we got.  */
331   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
332
333   char *finished_object = nullptr;
334   char *finished_annex = nullptr;
335   ULONGEST finished_offset = 0;
336
337   /* Should we try the 'ThreadInfo' query packet?
338
339      This variable (NOT available to the user: auto-detect only!)
340      determines whether GDB will use the new, simpler "ThreadInfo"
341      query or the older, more complex syntax for thread queries.
342      This is an auto-detect variable (set to true at each connect,
343      and set to false when the target fails to recognize it).  */
344   bool use_threadinfo_query = false;
345   bool use_threadextra_query = false;
346
347   threadref echo_nextthread {};
348   threadref nextthread {};
349   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
350
351   /* The state of remote notification.  */
352   struct remote_notif_state *notif_state = nullptr;
353
354   /* The branch trace configuration.  */
355   struct btrace_config btrace_config {};
356
357   /* The argument to the last "vFile:setfs:" packet we sent, used
358      to avoid sending repeated unnecessary "vFile:setfs:" packets.
359      Initialized to -1 to indicate that no "vFile:setfs:" packet
360      has yet been sent.  */
361   int fs_pid = -1;
362
363   /* A readahead cache for vFile:pread.  Often, reading a binary
364      involves a sequence of small reads.  E.g., when parsing an ELF
365      file.  A readahead cache helps mostly the case of remote
366      debugging on a connection with higher latency, due to the
367      request/reply nature of the RSP.  We only cache data for a single
368      file descriptor at a time.  */
369   struct readahead_cache readahead_cache;
370
371   /* The list of already fetched and acknowledged stop events.  This
372      queue is used for notification Stop, and other notifications
373      don't need queue for their events, because the notification
374      events of Stop can't be consumed immediately, so that events
375      should be queued first, and be consumed by remote_wait_{ns,as}
376      one per time.  Other notifications can consume their events
377      immediately, so queue is not needed for them.  */
378   std::vector<stop_reply_up> stop_reply_queue;
379
380   /* Asynchronous signal handle registered as event loop source for
381      when we have pending events ready to be passed to the core.  */
382   struct async_event_handler *remote_async_inferior_event_token = nullptr;
383
384   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
385      ``forever'' still use the normal timeout mechanism.  This is
386      currently used by the ASYNC code to guarentee that target reads
387      during the initial connect always time-out.  Once getpkt has been
388      modified to return a timeout indication and, in turn
389      remote_wait()/wait_for_inferior() have gained a timeout parameter
390      this can go away.  */
391   int wait_forever_enabled_p = 1;
392
393 private:
394   /* Mapping of remote protocol data for each gdbarch.  Usually there
395      is only one entry here, though we may see more with stubs that
396      support multi-process.  */
397   std::unordered_map<struct gdbarch *, remote_arch_state>
398     m_arch_states;
399 };
400
401 static const target_info remote_target_info = {
402   "remote",
403   N_("Remote serial target in gdb-specific protocol"),
404   remote_doc
405 };
406
407 class remote_target : public target_ops
408 {
409 public:
410   remote_target ()
411   {
412     to_stratum = process_stratum;
413   }
414   ~remote_target () override;
415
416   const target_info &info () const override
417   { return remote_target_info; }
418
419   thread_control_capabilities get_thread_control_capabilities () override
420   { return tc_schedlock; }
421
422   /* Open a remote connection.  */
423   static void open (const char *, int);
424
425   void close () override;
426
427   void detach (inferior *, int) override;
428   void disconnect (const char *, int) override;
429
430   void commit_resume () override;
431   void resume (ptid_t, int, enum gdb_signal) override;
432   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
433
434   void fetch_registers (struct regcache *, int) override;
435   void store_registers (struct regcache *, int) override;
436   void prepare_to_store (struct regcache *) override;
437
438   void files_info () override;
439
440   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
441
442   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
443                          enum remove_bp_reason) override;
444
445
446   bool stopped_by_sw_breakpoint () override;
447   bool supports_stopped_by_sw_breakpoint () override;
448
449   bool stopped_by_hw_breakpoint () override;
450
451   bool supports_stopped_by_hw_breakpoint () override;
452
453   bool stopped_by_watchpoint () override;
454
455   bool stopped_data_address (CORE_ADDR *) override;
456
457   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
458
459   int can_use_hw_breakpoint (enum bptype, int, int) override;
460
461   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
462
463   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
464
465   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
466
467   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
468                          struct expression *) override;
469
470   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
471                          struct expression *) override;
472
473   void kill () override;
474
475   void load (const char *, int) override;
476
477   void mourn_inferior () override;
478
479   void pass_signals (int, unsigned char *) override;
480
481   int set_syscall_catchpoint (int, bool, int,
482                               gdb::array_view<const int>) override;
483
484   void program_signals (int, unsigned char *) override;
485
486   bool thread_alive (ptid_t ptid) override;
487
488   const char *thread_name (struct thread_info *) override;
489
490   void update_thread_list () override;
491
492   const char *pid_to_str (ptid_t) override;
493
494   const char *extra_thread_info (struct thread_info *) override;
495
496   ptid_t get_ada_task_ptid (long lwp, long thread) override;
497
498   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
499                                              int handle_len,
500                                              inferior *inf) override;
501
502   void stop (ptid_t) override;
503
504   void interrupt () override;
505
506   void pass_ctrlc () override;
507
508   enum target_xfer_status xfer_partial (enum target_object object,
509                                         const char *annex,
510                                         gdb_byte *readbuf,
511                                         const gdb_byte *writebuf,
512                                         ULONGEST offset, ULONGEST len,
513                                         ULONGEST *xfered_len) override;
514
515   ULONGEST get_memory_xfer_limit () override;
516
517   void rcmd (const char *command, struct ui_file *output) override;
518
519   char *pid_to_exec_file (int pid) override;
520
521   void log_command (const char *cmd) override
522   {
523     serial_log_command (this, cmd);
524   }
525
526   CORE_ADDR get_thread_local_address (ptid_t ptid,
527                                       CORE_ADDR load_module_addr,
528                                       CORE_ADDR offset) override;
529
530   bool has_all_memory ()  override { return default_child_has_all_memory (); }
531   bool has_memory ()  override { return default_child_has_memory (); }
532   bool has_stack ()  override { return default_child_has_stack (); }
533   bool has_registers ()  override { return default_child_has_registers (); }
534   bool has_execution (ptid_t ptid)  override { return default_child_has_execution (ptid); }
535
536   bool can_execute_reverse () override;
537
538   std::vector<mem_region> memory_map () override;
539
540   void flash_erase (ULONGEST address, LONGEST length) override;
541
542   void flash_done () override;
543
544   const struct target_desc *read_description () override;
545
546   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
547                      const gdb_byte *pattern, ULONGEST pattern_len,
548                      CORE_ADDR *found_addrp) override;
549
550   bool can_async_p () override;
551
552   bool is_async_p () override;
553
554   void async (int) override;
555
556   void thread_events (int) override;
557
558   int can_do_single_step () override;
559
560   void terminal_inferior () override;
561
562   void terminal_ours () override;
563
564   bool supports_non_stop () override;
565
566   bool supports_multi_process () override;
567
568   bool supports_disable_randomization () override;
569
570   bool filesystem_is_local () override;
571
572
573   int fileio_open (struct inferior *inf, const char *filename,
574                    int flags, int mode, int warn_if_slow,
575                    int *target_errno) override;
576
577   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
578                      ULONGEST offset, int *target_errno) override;
579
580   int fileio_pread (int fd, gdb_byte *read_buf, int len,
581                     ULONGEST offset, int *target_errno) override;
582
583   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
584
585   int fileio_close (int fd, int *target_errno) override;
586
587   int fileio_unlink (struct inferior *inf,
588                      const char *filename,
589                      int *target_errno) override;
590
591   gdb::optional<std::string>
592     fileio_readlink (struct inferior *inf,
593                      const char *filename,
594                      int *target_errno) override;
595
596   bool supports_enable_disable_tracepoint () override;
597
598   bool supports_string_tracing () override;
599
600   bool supports_evaluation_of_breakpoint_conditions () override;
601
602   bool can_run_breakpoint_commands () override;
603
604   void trace_init () override;
605
606   void download_tracepoint (struct bp_location *location) override;
607
608   bool can_download_tracepoint () override;
609
610   void download_trace_state_variable (const trace_state_variable &tsv) override;
611
612   void enable_tracepoint (struct bp_location *location) override;
613
614   void disable_tracepoint (struct bp_location *location) override;
615
616   void trace_set_readonly_regions () override;
617
618   void trace_start () override;
619
620   int get_trace_status (struct trace_status *ts) override;
621
622   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
623     override;
624
625   void trace_stop () override;
626
627   int trace_find (enum trace_find_type type, int num,
628                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
629
630   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
631
632   int save_trace_data (const char *filename) override;
633
634   int upload_tracepoints (struct uploaded_tp **utpp) override;
635
636   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
637
638   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
639
640   int get_min_fast_tracepoint_insn_len () override;
641
642   void set_disconnected_tracing (int val) override;
643
644   void set_circular_trace_buffer (int val) override;
645
646   void set_trace_buffer_size (LONGEST val) override;
647
648   bool set_trace_notes (const char *user, const char *notes,
649                         const char *stopnotes) override;
650
651   int core_of_thread (ptid_t ptid) override;
652
653   int verify_memory (const gdb_byte *data,
654                      CORE_ADDR memaddr, ULONGEST size) override;
655
656
657   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
658
659   void set_permissions () override;
660
661   bool static_tracepoint_marker_at (CORE_ADDR,
662                                     struct static_tracepoint_marker *marker)
663     override;
664
665   std::vector<static_tracepoint_marker>
666     static_tracepoint_markers_by_strid (const char *id) override;
667
668   traceframe_info_up traceframe_info () override;
669
670   bool use_agent (bool use) override;
671   bool can_use_agent () override;
672
673   struct btrace_target_info *enable_btrace (ptid_t ptid,
674                                             const struct btrace_config *conf) override;
675
676   void disable_btrace (struct btrace_target_info *tinfo) override;
677
678   void teardown_btrace (struct btrace_target_info *tinfo) override;
679
680   enum btrace_error read_btrace (struct btrace_data *data,
681                                  struct btrace_target_info *btinfo,
682                                  enum btrace_read_type type) override;
683
684   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
685   bool augmented_libraries_svr4_read () override;
686   int follow_fork (int, int) override;
687   void follow_exec (struct inferior *, char *) override;
688   int insert_fork_catchpoint (int) override;
689   int remove_fork_catchpoint (int) override;
690   int insert_vfork_catchpoint (int) override;
691   int remove_vfork_catchpoint (int) override;
692   int insert_exec_catchpoint (int) override;
693   int remove_exec_catchpoint (int) override;
694   enum exec_direction_kind execution_direction () override;
695
696 public: /* Remote specific methods.  */
697
698   void remote_download_command_source (int num, ULONGEST addr,
699                                        struct command_line *cmds);
700
701   void remote_file_put (const char *local_file, const char *remote_file,
702                         int from_tty);
703   void remote_file_get (const char *remote_file, const char *local_file,
704                         int from_tty);
705   void remote_file_delete (const char *remote_file, int from_tty);
706
707   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
708                            ULONGEST offset, int *remote_errno);
709   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
710                             ULONGEST offset, int *remote_errno);
711   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
712                                  ULONGEST offset, int *remote_errno);
713
714   int remote_hostio_send_command (int command_bytes, int which_packet,
715                                   int *remote_errno, char **attachment,
716                                   int *attachment_len);
717   int remote_hostio_set_filesystem (struct inferior *inf,
718                                     int *remote_errno);
719   /* We should get rid of this and use fileio_open directly.  */
720   int remote_hostio_open (struct inferior *inf, const char *filename,
721                           int flags, int mode, int warn_if_slow,
722                           int *remote_errno);
723   int remote_hostio_close (int fd, int *remote_errno);
724
725   int remote_hostio_unlink (inferior *inf, const char *filename,
726                             int *remote_errno);
727
728   struct remote_state *get_remote_state ();
729
730   long get_remote_packet_size (void);
731   long get_memory_packet_size (struct memory_packet_config *config);
732
733   long get_memory_write_packet_size ();
734   long get_memory_read_packet_size ();
735
736   char *append_pending_thread_resumptions (char *p, char *endp,
737                                            ptid_t ptid);
738   static void open_1 (const char *name, int from_tty, int extended_p);
739   void start_remote (int from_tty, int extended_p);
740   void remote_detach_1 (struct inferior *inf, int from_tty);
741
742   char *append_resumption (char *p, char *endp,
743                            ptid_t ptid, int step, gdb_signal siggnal);
744   int remote_resume_with_vcont (ptid_t ptid, int step,
745                                 gdb_signal siggnal);
746
747   void add_current_inferior_and_thread (char *wait_status);
748
749   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
750                   int options);
751   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
752                   int options);
753
754   ptid_t process_stop_reply (struct stop_reply *stop_reply,
755                              target_waitstatus *status);
756
757   void remote_notice_new_inferior (ptid_t currthread, int executing);
758
759   void process_initial_stop_replies (int from_tty);
760
761   thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
762
763   void btrace_sync_conf (const btrace_config *conf);
764
765   void remote_btrace_maybe_reopen ();
766
767   void remove_new_fork_children (threads_listing_context *context);
768   void kill_new_fork_children (int pid);
769   void discard_pending_stop_replies (struct inferior *inf);
770   int stop_reply_queue_length ();
771
772   void check_pending_events_prevent_wildcard_vcont
773     (int *may_global_wildcard_vcont);
774
775   void discard_pending_stop_replies_in_queue ();
776   struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
777   struct stop_reply *queued_stop_reply (ptid_t ptid);
778   int peek_stop_reply (ptid_t ptid);
779   void remote_parse_stop_reply (char *buf, stop_reply *event);
780
781   void remote_stop_ns (ptid_t ptid);
782   void remote_interrupt_as ();
783   void remote_interrupt_ns ();
784
785   char *remote_get_noisy_reply ();
786   int remote_query_attached (int pid);
787   inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
788                                  int try_open_exec);
789
790   ptid_t remote_current_thread (ptid_t oldpid);
791   ptid_t get_current_thread (char *wait_status);
792
793   void set_thread (ptid_t ptid, int gen);
794   void set_general_thread (ptid_t ptid);
795   void set_continue_thread (ptid_t ptid);
796   void set_general_process ();
797
798   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
799
800   int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
801                                           gdb_ext_thread_info *info);
802   int remote_get_threadinfo (threadref *threadid, int fieldset,
803                              gdb_ext_thread_info *info);
804
805   int parse_threadlist_response (char *pkt, int result_limit,
806                                  threadref *original_echo,
807                                  threadref *resultlist,
808                                  int *doneflag);
809   int remote_get_threadlist (int startflag, threadref *nextthread,
810                              int result_limit, int *done, int *result_count,
811                              threadref *threadlist);
812
813   int remote_threadlist_iterator (rmt_thread_action stepfunction,
814                                   void *context, int looplimit);
815
816   int remote_get_threads_with_ql (threads_listing_context *context);
817   int remote_get_threads_with_qxfer (threads_listing_context *context);
818   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
819
820   void extended_remote_restart ();
821
822   void get_offsets ();
823
824   void remote_check_symbols ();
825
826   void remote_supported_packet (const struct protocol_feature *feature,
827                                 enum packet_support support,
828                                 const char *argument);
829
830   void remote_query_supported ();
831
832   void remote_packet_size (const protocol_feature *feature,
833                            packet_support support, const char *value);
834
835   void remote_serial_quit_handler ();
836
837   void remote_detach_pid (int pid);
838
839   void remote_vcont_probe ();
840
841   void remote_resume_with_hc (ptid_t ptid, int step,
842                               gdb_signal siggnal);
843
844   void send_interrupt_sequence ();
845   void interrupt_query ();
846
847   void remote_notif_get_pending_events (notif_client *nc);
848
849   int fetch_register_using_p (struct regcache *regcache,
850                               packet_reg *reg);
851   int send_g_packet ();
852   void process_g_packet (struct regcache *regcache);
853   void fetch_registers_using_g (struct regcache *regcache);
854   int store_register_using_P (const struct regcache *regcache,
855                               packet_reg *reg);
856   void store_registers_using_G (const struct regcache *regcache);
857
858   void set_remote_traceframe ();
859
860   void check_binary_download (CORE_ADDR addr);
861
862   target_xfer_status remote_write_bytes_aux (const char *header,
863                                              CORE_ADDR memaddr,
864                                              const gdb_byte *myaddr,
865                                              ULONGEST len_units,
866                                              int unit_size,
867                                              ULONGEST *xfered_len_units,
868                                              char packet_format,
869                                              int use_length);
870
871   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
872                                          const gdb_byte *myaddr, ULONGEST len,
873                                          int unit_size, ULONGEST *xfered_len);
874
875   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
876                                           ULONGEST len_units,
877                                           int unit_size, ULONGEST *xfered_len_units);
878
879   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
880                                                         ULONGEST memaddr,
881                                                         ULONGEST len,
882                                                         int unit_size,
883                                                         ULONGEST *xfered_len);
884
885   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
886                                         gdb_byte *myaddr, ULONGEST len,
887                                         int unit_size,
888                                         ULONGEST *xfered_len);
889
890   packet_result remote_send_printf (const char *format, ...)
891     ATTRIBUTE_PRINTF (2, 3);
892
893   target_xfer_status remote_flash_write (ULONGEST address,
894                                          ULONGEST length, ULONGEST *xfered_len,
895                                          const gdb_byte *data);
896
897   int readchar (int timeout);
898
899   void remote_serial_write (const char *str, int len);
900
901   int putpkt (const char *buf);
902   int putpkt_binary (const char *buf, int cnt);
903
904   void skip_frame ();
905   long read_frame (char **buf_p, long *sizeof_buf);
906   void getpkt (char **buf, long *sizeof_buf, int forever);
907   int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
908                               int expecting_notif, int *is_notif);
909   int getpkt_sane (char **buf, long *sizeof_buf, int forever);
910   int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
911                             int *is_notif);
912   int remote_vkill (int pid);
913   void remote_kill_k ();
914
915   void extended_remote_disable_randomization (int val);
916   int extended_remote_run (const std::string &args);
917
918   void send_environment_packet (const char *action,
919                                 const char *packet,
920                                 const char *value);
921
922   void extended_remote_environment_support ();
923   void extended_remote_set_inferior_cwd ();
924
925   target_xfer_status remote_write_qxfer (const char *object_name,
926                                          const char *annex,
927                                          const gdb_byte *writebuf,
928                                          ULONGEST offset, LONGEST len,
929                                          ULONGEST *xfered_len,
930                                          struct packet_config *packet);
931
932   target_xfer_status remote_read_qxfer (const char *object_name,
933                                         const char *annex,
934                                         gdb_byte *readbuf, ULONGEST offset,
935                                         LONGEST len,
936                                         ULONGEST *xfered_len,
937                                         struct packet_config *packet);
938
939   void push_stop_reply (struct stop_reply *new_event);
940
941   bool vcont_r_supported ();
942
943   void packet_command (const char *args, int from_tty);
944
945 private: /* data fields */
946
947   /* The remote state.  Don't reference this directly.  Use the
948      get_remote_state method instead.  */
949   remote_state m_remote_state;
950 };
951
952 static const target_info extended_remote_target_info = {
953   "extended-remote",
954   N_("Extended remote serial target in gdb-specific protocol"),
955   remote_doc
956 };
957
958 /* Set up the extended remote target by extending the standard remote
959    target and adding to it.  */
960
961 class extended_remote_target final : public remote_target
962 {
963 public:
964   const target_info &info () const override
965   { return extended_remote_target_info; }
966
967   /* Open an extended-remote connection.  */
968   static void open (const char *, int);
969
970   bool can_create_inferior () override { return true; }
971   void create_inferior (const char *, const std::string &,
972                         char **, int) override;
973
974   void detach (inferior *, int) override;
975
976   bool can_attach () override { return true; }
977   void attach (const char *, int) override;
978
979   void post_attach (int) override;
980   bool supports_disable_randomization () override;
981 };
982
983 /* Per-program-space data key.  */
984 static const struct program_space_data *remote_pspace_data;
985
986 /* The variable registered as the control variable used by the
987    remote exec-file commands.  While the remote exec-file setting is
988    per-program-space, the set/show machinery uses this as the 
989    location of the remote exec-file value.  */
990 static char *remote_exec_file_var;
991
992 /* The size to align memory write packets, when practical.  The protocol
993    does not guarantee any alignment, and gdb will generate short
994    writes and unaligned writes, but even as a best-effort attempt this
995    can improve bulk transfers.  For instance, if a write is misaligned
996    relative to the target's data bus, the stub may need to make an extra
997    round trip fetching data from the target.  This doesn't make a
998    huge difference, but it's easy to do, so we try to be helpful.
999
1000    The alignment chosen is arbitrary; usually data bus width is
1001    important here, not the possibly larger cache line size.  */
1002 enum { REMOTE_ALIGN_WRITES = 16 };
1003
1004 /* Prototypes for local functions.  */
1005
1006 static int hexnumlen (ULONGEST num);
1007
1008 static int stubhex (int ch);
1009
1010 static int hexnumstr (char *, ULONGEST);
1011
1012 static int hexnumnstr (char *, ULONGEST, int);
1013
1014 static CORE_ADDR remote_address_masked (CORE_ADDR);
1015
1016 static void print_packet (const char *);
1017
1018 static int stub_unpack_int (char *buff, int fieldlength);
1019
1020 struct packet_config;
1021
1022 static void show_packet_config_cmd (struct packet_config *config);
1023
1024 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1025                                              int from_tty,
1026                                              struct cmd_list_element *c,
1027                                              const char *value);
1028
1029 static ptid_t read_ptid (const char *buf, const char **obuf);
1030
1031 static void remote_async_inferior_event_handler (gdb_client_data);
1032
1033 static int remote_read_description_p (struct target_ops *target);
1034
1035 static void remote_console_output (char *msg);
1036
1037 static void remote_btrace_reset (remote_state *rs);
1038
1039 static void remote_unpush_and_throw (void);
1040
1041 /* For "remote".  */
1042
1043 static struct cmd_list_element *remote_cmdlist;
1044
1045 /* For "set remote" and "show remote".  */
1046
1047 static struct cmd_list_element *remote_set_cmdlist;
1048 static struct cmd_list_element *remote_show_cmdlist;
1049
1050 /* Controls whether GDB is willing to use range stepping.  */
1051
1052 static int use_range_stepping = 1;
1053
1054 /* The max number of chars in debug output.  The rest of chars are
1055    omitted.  */
1056
1057 #define REMOTE_DEBUG_MAX_CHAR 512
1058
1059 /* Private data that we'll store in (struct thread_info)->priv.  */
1060 struct remote_thread_info : public private_thread_info
1061 {
1062   std::string extra;
1063   std::string name;
1064   int core = -1;
1065
1066   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1067      sequence of bytes.  */
1068   gdb::byte_vector thread_handle;
1069
1070   /* Whether the target stopped for a breakpoint/watchpoint.  */
1071   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1072
1073   /* This is set to the data address of the access causing the target
1074      to stop for a watchpoint.  */
1075   CORE_ADDR watch_data_address = 0;
1076
1077   /* Fields used by the vCont action coalescing implemented in
1078      remote_resume / remote_commit_resume.  remote_resume stores each
1079      thread's last resume request in these fields, so that a later
1080      remote_commit_resume knows which is the proper action for this
1081      thread to include in the vCont packet.  */
1082
1083   /* True if the last target_resume call for this thread was a step
1084      request, false if a continue request.  */
1085   int last_resume_step = 0;
1086
1087   /* The signal specified in the last target_resume call for this
1088      thread.  */
1089   gdb_signal last_resume_sig = GDB_SIGNAL_0;
1090
1091   /* Whether this thread was already vCont-resumed on the remote
1092      side.  */
1093   int vcont_resumed = 0;
1094 };
1095
1096 remote_state::remote_state ()
1097 {
1098   /* The default buffer size is unimportant; it will be expanded
1099      whenever a larger buffer is needed. */
1100   this->buf_size = 400;
1101   this->buf = (char *) xmalloc (this->buf_size);
1102 }
1103
1104 remote_state::~remote_state ()
1105 {
1106   xfree (this->last_pass_packet);
1107   xfree (this->last_program_signals_packet);
1108   xfree (this->buf);
1109   xfree (this->finished_object);
1110   xfree (this->finished_annex);
1111 }
1112
1113 /* Utility: generate error from an incoming stub packet.  */
1114 static void
1115 trace_error (char *buf)
1116 {
1117   if (*buf++ != 'E')
1118     return;                     /* not an error msg */
1119   switch (*buf)
1120     {
1121     case '1':                   /* malformed packet error */
1122       if (*++buf == '0')        /*   general case: */
1123         error (_("remote.c: error in outgoing packet."));
1124       else
1125         error (_("remote.c: error in outgoing packet at field #%ld."),
1126                strtol (buf, NULL, 16));
1127     default:
1128       error (_("Target returns error code '%s'."), buf);
1129     }
1130 }
1131
1132 /* Utility: wait for reply from stub, while accepting "O" packets.  */
1133
1134 char *
1135 remote_target::remote_get_noisy_reply ()
1136 {
1137   struct remote_state *rs = get_remote_state ();
1138
1139   do                            /* Loop on reply from remote stub.  */
1140     {
1141       char *buf;
1142
1143       QUIT;                     /* Allow user to bail out with ^C.  */
1144       getpkt (&rs->buf, &rs->buf_size, 0);
1145       buf = rs->buf;
1146       if (buf[0] == 'E')
1147         trace_error (buf);
1148       else if (startswith (buf, "qRelocInsn:"))
1149         {
1150           ULONGEST ul;
1151           CORE_ADDR from, to, org_to;
1152           const char *p, *pp;
1153           int adjusted_size = 0;
1154           int relocated = 0;
1155
1156           p = buf + strlen ("qRelocInsn:");
1157           pp = unpack_varlen_hex (p, &ul);
1158           if (*pp != ';')
1159             error (_("invalid qRelocInsn packet: %s"), buf);
1160           from = ul;
1161
1162           p = pp + 1;
1163           unpack_varlen_hex (p, &ul);
1164           to = ul;
1165
1166           org_to = to;
1167
1168           TRY
1169             {
1170               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1171               relocated = 1;
1172             }
1173           CATCH (ex, RETURN_MASK_ALL)
1174             {
1175               if (ex.error == MEMORY_ERROR)
1176                 {
1177                   /* Propagate memory errors silently back to the
1178                      target.  The stub may have limited the range of
1179                      addresses we can write to, for example.  */
1180                 }
1181               else
1182                 {
1183                   /* Something unexpectedly bad happened.  Be verbose
1184                      so we can tell what, and propagate the error back
1185                      to the stub, so it doesn't get stuck waiting for
1186                      a response.  */
1187                   exception_fprintf (gdb_stderr, ex,
1188                                      _("warning: relocating instruction: "));
1189                 }
1190               putpkt ("E01");
1191             }
1192           END_CATCH
1193
1194           if (relocated)
1195             {
1196               adjusted_size = to - org_to;
1197
1198               xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
1199               putpkt (buf);
1200             }
1201         }
1202       else if (buf[0] == 'O' && buf[1] != 'K')
1203         remote_console_output (buf + 1);        /* 'O' message from stub */
1204       else
1205         return buf;             /* Here's the actual reply.  */
1206     }
1207   while (1);
1208 }
1209
1210 struct remote_arch_state *
1211 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1212 {
1213   remote_arch_state *rsa;
1214
1215   auto it = this->m_arch_states.find (gdbarch);
1216   if (it == this->m_arch_states.end ())
1217     {
1218       auto p = this->m_arch_states.emplace (std::piecewise_construct,
1219                                             std::forward_as_tuple (gdbarch),
1220                                             std::forward_as_tuple (gdbarch));
1221       rsa = &p.first->second;
1222
1223       /* Make sure that the packet buffer is plenty big enough for
1224          this architecture.  */
1225       if (this->buf_size < rsa->remote_packet_size)
1226         {
1227           this->buf_size = 2 * rsa->remote_packet_size;
1228           this->buf = (char *) xrealloc (this->buf, this->buf_size);
1229         }
1230     }
1231   else
1232     rsa = &it->second;
1233
1234   return rsa;
1235 }
1236
1237 /* Fetch the global remote target state.  */
1238
1239 remote_state *
1240 remote_target::get_remote_state ()
1241 {
1242   /* Make sure that the remote architecture state has been
1243      initialized, because doing so might reallocate rs->buf.  Any
1244      function which calls getpkt also needs to be mindful of changes
1245      to rs->buf, but this call limits the number of places which run
1246      into trouble.  */
1247   m_remote_state.get_remote_arch_state (target_gdbarch ());
1248
1249   return &m_remote_state;
1250 }
1251
1252 /* Cleanup routine for the remote module's pspace data.  */
1253
1254 static void
1255 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1256 {
1257   char *remote_exec_file = (char *) arg;
1258
1259   xfree (remote_exec_file);
1260 }
1261
1262 /* Fetch the remote exec-file from the current program space.  */
1263
1264 static const char *
1265 get_remote_exec_file (void)
1266 {
1267   char *remote_exec_file;
1268
1269   remote_exec_file
1270     = (char *) program_space_data (current_program_space,
1271                                    remote_pspace_data);
1272   if (remote_exec_file == NULL)
1273     return "";
1274
1275   return remote_exec_file;
1276 }
1277
1278 /* Set the remote exec file for PSPACE.  */
1279
1280 static void
1281 set_pspace_remote_exec_file (struct program_space *pspace,
1282                         char *remote_exec_file)
1283 {
1284   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1285
1286   xfree (old_file);
1287   set_program_space_data (pspace, remote_pspace_data,
1288                           xstrdup (remote_exec_file));
1289 }
1290
1291 /* The "set/show remote exec-file" set command hook.  */
1292
1293 static void
1294 set_remote_exec_file (const char *ignored, int from_tty,
1295                       struct cmd_list_element *c)
1296 {
1297   gdb_assert (remote_exec_file_var != NULL);
1298   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1299 }
1300
1301 /* The "set/show remote exec-file" show command hook.  */
1302
1303 static void
1304 show_remote_exec_file (struct ui_file *file, int from_tty,
1305                        struct cmd_list_element *cmd, const char *value)
1306 {
1307   fprintf_filtered (file, "%s\n", remote_exec_file_var);
1308 }
1309
1310 static int
1311 compare_pnums (const void *lhs_, const void *rhs_)
1312 {
1313   const struct packet_reg * const *lhs
1314     = (const struct packet_reg * const *) lhs_;
1315   const struct packet_reg * const *rhs
1316     = (const struct packet_reg * const *) rhs_;
1317
1318   if ((*lhs)->pnum < (*rhs)->pnum)
1319     return -1;
1320   else if ((*lhs)->pnum == (*rhs)->pnum)
1321     return 0;
1322   else
1323     return 1;
1324 }
1325
1326 static int
1327 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1328 {
1329   int regnum, num_remote_regs, offset;
1330   struct packet_reg **remote_regs;
1331
1332   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1333     {
1334       struct packet_reg *r = &regs[regnum];
1335
1336       if (register_size (gdbarch, regnum) == 0)
1337         /* Do not try to fetch zero-sized (placeholder) registers.  */
1338         r->pnum = -1;
1339       else
1340         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1341
1342       r->regnum = regnum;
1343     }
1344
1345   /* Define the g/G packet format as the contents of each register
1346      with a remote protocol number, in order of ascending protocol
1347      number.  */
1348
1349   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1350   for (num_remote_regs = 0, regnum = 0;
1351        regnum < gdbarch_num_regs (gdbarch);
1352        regnum++)
1353     if (regs[regnum].pnum != -1)
1354       remote_regs[num_remote_regs++] = &regs[regnum];
1355
1356   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1357          compare_pnums);
1358
1359   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1360     {
1361       remote_regs[regnum]->in_g_packet = 1;
1362       remote_regs[regnum]->offset = offset;
1363       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1364     }
1365
1366   return offset;
1367 }
1368
1369 /* Given the architecture described by GDBARCH, return the remote
1370    protocol register's number and the register's offset in the g/G
1371    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1372    If the target does not have a mapping for REGNUM, return false,
1373    otherwise, return true.  */
1374
1375 int
1376 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1377                                    int *pnum, int *poffset)
1378 {
1379   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1380
1381   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1382
1383   map_regcache_remote_table (gdbarch, regs.data ());
1384
1385   *pnum = regs[regnum].pnum;
1386   *poffset = regs[regnum].offset;
1387
1388   return *pnum != -1;
1389 }
1390
1391 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1392 {
1393   /* Use the architecture to build a regnum<->pnum table, which will be
1394      1:1 unless a feature set specifies otherwise.  */
1395   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1396
1397   /* Record the maximum possible size of the g packet - it may turn out
1398      to be smaller.  */
1399   this->sizeof_g_packet
1400     = map_regcache_remote_table (gdbarch, this->regs.get ());
1401
1402   /* Default maximum number of characters in a packet body.  Many
1403      remote stubs have a hardwired buffer size of 400 bytes
1404      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
1405      as the maximum packet-size to ensure that the packet and an extra
1406      NUL character can always fit in the buffer.  This stops GDB
1407      trashing stubs that try to squeeze an extra NUL into what is
1408      already a full buffer (As of 1999-12-04 that was most stubs).  */
1409   this->remote_packet_size = 400 - 1;
1410
1411   /* This one is filled in when a ``g'' packet is received.  */
1412   this->actual_register_packet_size = 0;
1413
1414   /* Should rsa->sizeof_g_packet needs more space than the
1415      default, adjust the size accordingly.  Remember that each byte is
1416      encoded as two characters.  32 is the overhead for the packet
1417      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
1418      (``$NN:G...#NN'') is a better guess, the below has been padded a
1419      little.  */
1420   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1421     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1422 }
1423
1424 /* Get a pointer to the current remote target.  If not connected to a
1425    remote target, return NULL.  */
1426
1427 static remote_target *
1428 get_current_remote_target ()
1429 {
1430   target_ops *proc_target = find_target_at (process_stratum);
1431   return dynamic_cast<remote_target *> (proc_target);
1432 }
1433
1434 /* Return the current allowed size of a remote packet.  This is
1435    inferred from the current architecture, and should be used to
1436    limit the length of outgoing packets.  */
1437 long
1438 remote_target::get_remote_packet_size ()
1439 {
1440   struct remote_state *rs = get_remote_state ();
1441   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1442
1443   if (rs->explicit_packet_size)
1444     return rs->explicit_packet_size;
1445
1446   return rsa->remote_packet_size;
1447 }
1448
1449 static struct packet_reg *
1450 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1451                         long regnum)
1452 {
1453   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1454     return NULL;
1455   else
1456     {
1457       struct packet_reg *r = &rsa->regs[regnum];
1458
1459       gdb_assert (r->regnum == regnum);
1460       return r;
1461     }
1462 }
1463
1464 static struct packet_reg *
1465 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1466                       LONGEST pnum)
1467 {
1468   int i;
1469
1470   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1471     {
1472       struct packet_reg *r = &rsa->regs[i];
1473
1474       if (r->pnum == pnum)
1475         return r;
1476     }
1477   return NULL;
1478 }
1479
1480 /* Allow the user to specify what sequence to send to the remote
1481    when he requests a program interruption: Although ^C is usually
1482    what remote systems expect (this is the default, here), it is
1483    sometimes preferable to send a break.  On other systems such
1484    as the Linux kernel, a break followed by g, which is Magic SysRq g
1485    is required in order to interrupt the execution.  */
1486 const char interrupt_sequence_control_c[] = "Ctrl-C";
1487 const char interrupt_sequence_break[] = "BREAK";
1488 const char interrupt_sequence_break_g[] = "BREAK-g";
1489 static const char *const interrupt_sequence_modes[] =
1490   {
1491     interrupt_sequence_control_c,
1492     interrupt_sequence_break,
1493     interrupt_sequence_break_g,
1494     NULL
1495   };
1496 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1497
1498 static void
1499 show_interrupt_sequence (struct ui_file *file, int from_tty,
1500                          struct cmd_list_element *c,
1501                          const char *value)
1502 {
1503   if (interrupt_sequence_mode == interrupt_sequence_control_c)
1504     fprintf_filtered (file,
1505                       _("Send the ASCII ETX character (Ctrl-c) "
1506                         "to the remote target to interrupt the "
1507                         "execution of the program.\n"));
1508   else if (interrupt_sequence_mode == interrupt_sequence_break)
1509     fprintf_filtered (file,
1510                       _("send a break signal to the remote target "
1511                         "to interrupt the execution of the program.\n"));
1512   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1513     fprintf_filtered (file,
1514                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1515                         "the remote target to interrupt the execution "
1516                         "of Linux kernel.\n"));
1517   else
1518     internal_error (__FILE__, __LINE__,
1519                     _("Invalid value for interrupt_sequence_mode: %s."),
1520                     interrupt_sequence_mode);
1521 }
1522
1523 /* This boolean variable specifies whether interrupt_sequence is sent
1524    to the remote target when gdb connects to it.
1525    This is mostly needed when you debug the Linux kernel: The Linux kernel
1526    expects BREAK g which is Magic SysRq g for connecting gdb.  */
1527 static int interrupt_on_connect = 0;
1528
1529 /* This variable is used to implement the "set/show remotebreak" commands.
1530    Since these commands are now deprecated in favor of "set/show remote
1531    interrupt-sequence", it no longer has any effect on the code.  */
1532 static int remote_break;
1533
1534 static void
1535 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1536 {
1537   if (remote_break)
1538     interrupt_sequence_mode = interrupt_sequence_break;
1539   else
1540     interrupt_sequence_mode = interrupt_sequence_control_c;
1541 }
1542
1543 static void
1544 show_remotebreak (struct ui_file *file, int from_tty,
1545                   struct cmd_list_element *c,
1546                   const char *value)
1547 {
1548 }
1549
1550 /* This variable sets the number of bits in an address that are to be
1551    sent in a memory ("M" or "m") packet.  Normally, after stripping
1552    leading zeros, the entire address would be sent.  This variable
1553    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
1554    initial implementation of remote.c restricted the address sent in
1555    memory packets to ``host::sizeof long'' bytes - (typically 32
1556    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1557    address was never sent.  Since fixing this bug may cause a break in
1558    some remote targets this variable is principly provided to
1559    facilitate backward compatibility.  */
1560
1561 static unsigned int remote_address_size;
1562
1563 \f
1564 /* User configurable variables for the number of characters in a
1565    memory read/write packet.  MIN (rsa->remote_packet_size,
1566    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1567    values (fifo overruns, et.al.) and some users need larger values
1568    (speed up transfers).  The variables ``preferred_*'' (the user
1569    request), ``current_*'' (what was actually set) and ``forced_*''
1570    (Positive - a soft limit, negative - a hard limit).  */
1571
1572 struct memory_packet_config
1573 {
1574   const char *name;
1575   long size;
1576   int fixed_p;
1577 };
1578
1579 /* The default max memory-write-packet-size, when the setting is
1580    "fixed".  The 16k is historical.  (It came from older GDB's using
1581    alloca for buffers and the knowledge (folklore?) that some hosts
1582    don't cope very well with large alloca calls.)  */
1583 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1584
1585 /* The minimum remote packet size for memory transfers.  Ensures we
1586    can write at least one byte.  */
1587 #define MIN_MEMORY_PACKET_SIZE 20
1588
1589 /* Get the memory packet size, assuming it is fixed.  */
1590
1591 static long
1592 get_fixed_memory_packet_size (struct memory_packet_config *config)
1593 {
1594   gdb_assert (config->fixed_p);
1595
1596   if (config->size <= 0)
1597     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1598   else
1599     return config->size;
1600 }
1601
1602 /* Compute the current size of a read/write packet.  Since this makes
1603    use of ``actual_register_packet_size'' the computation is dynamic.  */
1604
1605 long
1606 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1607 {
1608   struct remote_state *rs = get_remote_state ();
1609   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1610
1611   long what_they_get;
1612   if (config->fixed_p)
1613     what_they_get = get_fixed_memory_packet_size (config);
1614   else
1615     {
1616       what_they_get = get_remote_packet_size ();
1617       /* Limit the packet to the size specified by the user.  */
1618       if (config->size > 0
1619           && what_they_get > config->size)
1620         what_they_get = config->size;
1621
1622       /* Limit it to the size of the targets ``g'' response unless we have
1623          permission from the stub to use a larger packet size.  */
1624       if (rs->explicit_packet_size == 0
1625           && rsa->actual_register_packet_size > 0
1626           && what_they_get > rsa->actual_register_packet_size)
1627         what_they_get = rsa->actual_register_packet_size;
1628     }
1629   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1630     what_they_get = MIN_MEMORY_PACKET_SIZE;
1631
1632   /* Make sure there is room in the global buffer for this packet
1633      (including its trailing NUL byte).  */
1634   if (rs->buf_size < what_they_get + 1)
1635     {
1636       rs->buf_size = 2 * what_they_get;
1637       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1638     }
1639
1640   return what_they_get;
1641 }
1642
1643 /* Update the size of a read/write packet.  If they user wants
1644    something really big then do a sanity check.  */
1645
1646 static void
1647 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1648 {
1649   int fixed_p = config->fixed_p;
1650   long size = config->size;
1651
1652   if (args == NULL)
1653     error (_("Argument required (integer, `fixed' or `limited')."));
1654   else if (strcmp (args, "hard") == 0
1655       || strcmp (args, "fixed") == 0)
1656     fixed_p = 1;
1657   else if (strcmp (args, "soft") == 0
1658            || strcmp (args, "limit") == 0)
1659     fixed_p = 0;
1660   else
1661     {
1662       char *end;
1663
1664       size = strtoul (args, &end, 0);
1665       if (args == end)
1666         error (_("Invalid %s (bad syntax)."), config->name);
1667
1668       /* Instead of explicitly capping the size of a packet to or
1669          disallowing it, the user is allowed to set the size to
1670          something arbitrarily large.  */
1671     }
1672
1673   /* Extra checks?  */
1674   if (fixed_p && !config->fixed_p)
1675     {
1676       /* So that the query shows the correct value.  */
1677       long query_size = (size <= 0
1678                          ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1679                          : size);
1680
1681       if (! query (_("The target may not be able to correctly handle a %s\n"
1682                    "of %ld bytes. Change the packet size? "),
1683                    config->name, query_size))
1684         error (_("Packet size not changed."));
1685     }
1686   /* Update the config.  */
1687   config->fixed_p = fixed_p;
1688   config->size = size;
1689 }
1690
1691 static void
1692 show_memory_packet_size (struct memory_packet_config *config)
1693 {
1694   if (config->size == 0)
1695     printf_filtered (_("The %s is 0 (default). "), config->name);
1696   else
1697     printf_filtered (_("The %s is %ld. "), config->name, config->size);
1698   if (config->fixed_p)
1699     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1700                      get_fixed_memory_packet_size (config));
1701   else
1702     {
1703       remote_target *remote = get_current_remote_target ();
1704
1705       if (remote != NULL)
1706         printf_filtered (_("Packets are limited to %ld bytes.\n"),
1707                          remote->get_memory_packet_size (config));
1708       else
1709         puts_filtered ("The actual limit will be further reduced "
1710                        "dependent on the target.\n");
1711     }
1712 }
1713
1714 static struct memory_packet_config memory_write_packet_config =
1715 {
1716   "memory-write-packet-size",
1717 };
1718
1719 static void
1720 set_memory_write_packet_size (const char *args, int from_tty)
1721 {
1722   set_memory_packet_size (args, &memory_write_packet_config);
1723 }
1724
1725 static void
1726 show_memory_write_packet_size (const char *args, int from_tty)
1727 {
1728   show_memory_packet_size (&memory_write_packet_config);
1729 }
1730
1731 long
1732 remote_target::get_memory_write_packet_size ()
1733 {
1734   return get_memory_packet_size (&memory_write_packet_config);
1735 }
1736
1737 static struct memory_packet_config memory_read_packet_config =
1738 {
1739   "memory-read-packet-size",
1740 };
1741
1742 static void
1743 set_memory_read_packet_size (const char *args, int from_tty)
1744 {
1745   set_memory_packet_size (args, &memory_read_packet_config);
1746 }
1747
1748 static void
1749 show_memory_read_packet_size (const char *args, int from_tty)
1750 {
1751   show_memory_packet_size (&memory_read_packet_config);
1752 }
1753
1754 long
1755 remote_target::get_memory_read_packet_size ()
1756 {
1757   long size = get_memory_packet_size (&memory_read_packet_config);
1758
1759   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1760      extra buffer size argument before the memory read size can be
1761      increased beyond this.  */
1762   if (size > get_remote_packet_size ())
1763     size = get_remote_packet_size ();
1764   return size;
1765 }
1766
1767 \f
1768
1769 struct packet_config
1770   {
1771     const char *name;
1772     const char *title;
1773
1774     /* If auto, GDB auto-detects support for this packet or feature,
1775        either through qSupported, or by trying the packet and looking
1776        at the response.  If true, GDB assumes the target supports this
1777        packet.  If false, the packet is disabled.  Configs that don't
1778        have an associated command always have this set to auto.  */
1779     enum auto_boolean detect;
1780
1781     /* Does the target support this packet?  */
1782     enum packet_support support;
1783   };
1784
1785 static enum packet_support packet_config_support (struct packet_config *config);
1786 static enum packet_support packet_support (int packet);
1787
1788 static void
1789 show_packet_config_cmd (struct packet_config *config)
1790 {
1791   const char *support = "internal-error";
1792
1793   switch (packet_config_support (config))
1794     {
1795     case PACKET_ENABLE:
1796       support = "enabled";
1797       break;
1798     case PACKET_DISABLE:
1799       support = "disabled";
1800       break;
1801     case PACKET_SUPPORT_UNKNOWN:
1802       support = "unknown";
1803       break;
1804     }
1805   switch (config->detect)
1806     {
1807     case AUTO_BOOLEAN_AUTO:
1808       printf_filtered (_("Support for the `%s' packet "
1809                          "is auto-detected, currently %s.\n"),
1810                        config->name, support);
1811       break;
1812     case AUTO_BOOLEAN_TRUE:
1813     case AUTO_BOOLEAN_FALSE:
1814       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1815                        config->name, support);
1816       break;
1817     }
1818 }
1819
1820 static void
1821 add_packet_config_cmd (struct packet_config *config, const char *name,
1822                        const char *title, int legacy)
1823 {
1824   char *set_doc;
1825   char *show_doc;
1826   char *cmd_name;
1827
1828   config->name = name;
1829   config->title = title;
1830   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1831                         name, title);
1832   show_doc = xstrprintf ("Show current use of remote "
1833                          "protocol `%s' (%s) packet",
1834                          name, title);
1835   /* set/show TITLE-packet {auto,on,off} */
1836   cmd_name = xstrprintf ("%s-packet", title);
1837   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1838                                 &config->detect, set_doc,
1839                                 show_doc, NULL, /* help_doc */
1840                                 NULL,
1841                                 show_remote_protocol_packet_cmd,
1842                                 &remote_set_cmdlist, &remote_show_cmdlist);
1843   /* The command code copies the documentation strings.  */
1844   xfree (set_doc);
1845   xfree (show_doc);
1846   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1847   if (legacy)
1848     {
1849       char *legacy_name;
1850
1851       legacy_name = xstrprintf ("%s-packet", name);
1852       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1853                      &remote_set_cmdlist);
1854       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1855                      &remote_show_cmdlist);
1856     }
1857 }
1858
1859 static enum packet_result
1860 packet_check_result (const char *buf)
1861 {
1862   if (buf[0] != '\0')
1863     {
1864       /* The stub recognized the packet request.  Check that the
1865          operation succeeded.  */
1866       if (buf[0] == 'E'
1867           && isxdigit (buf[1]) && isxdigit (buf[2])
1868           && buf[3] == '\0')
1869         /* "Enn"  - definitly an error.  */
1870         return PACKET_ERROR;
1871
1872       /* Always treat "E." as an error.  This will be used for
1873          more verbose error messages, such as E.memtypes.  */
1874       if (buf[0] == 'E' && buf[1] == '.')
1875         return PACKET_ERROR;
1876
1877       /* The packet may or may not be OK.  Just assume it is.  */
1878       return PACKET_OK;
1879     }
1880   else
1881     /* The stub does not support the packet.  */
1882     return PACKET_UNKNOWN;
1883 }
1884
1885 static enum packet_result
1886 packet_ok (const char *buf, struct packet_config *config)
1887 {
1888   enum packet_result result;
1889
1890   if (config->detect != AUTO_BOOLEAN_TRUE
1891       && config->support == PACKET_DISABLE)
1892     internal_error (__FILE__, __LINE__,
1893                     _("packet_ok: attempt to use a disabled packet"));
1894
1895   result = packet_check_result (buf);
1896   switch (result)
1897     {
1898     case PACKET_OK:
1899     case PACKET_ERROR:
1900       /* The stub recognized the packet request.  */
1901       if (config->support == PACKET_SUPPORT_UNKNOWN)
1902         {
1903           if (remote_debug)
1904             fprintf_unfiltered (gdb_stdlog,
1905                                 "Packet %s (%s) is supported\n",
1906                                 config->name, config->title);
1907           config->support = PACKET_ENABLE;
1908         }
1909       break;
1910     case PACKET_UNKNOWN:
1911       /* The stub does not support the packet.  */
1912       if (config->detect == AUTO_BOOLEAN_AUTO
1913           && config->support == PACKET_ENABLE)
1914         {
1915           /* If the stub previously indicated that the packet was
1916              supported then there is a protocol error.  */
1917           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1918                  config->name, config->title);
1919         }
1920       else if (config->detect == AUTO_BOOLEAN_TRUE)
1921         {
1922           /* The user set it wrong.  */
1923           error (_("Enabled packet %s (%s) not recognized by stub"),
1924                  config->name, config->title);
1925         }
1926
1927       if (remote_debug)
1928         fprintf_unfiltered (gdb_stdlog,
1929                             "Packet %s (%s) is NOT supported\n",
1930                             config->name, config->title);
1931       config->support = PACKET_DISABLE;
1932       break;
1933     }
1934
1935   return result;
1936 }
1937
1938 enum {
1939   PACKET_vCont = 0,
1940   PACKET_X,
1941   PACKET_qSymbol,
1942   PACKET_P,
1943   PACKET_p,
1944   PACKET_Z0,
1945   PACKET_Z1,
1946   PACKET_Z2,
1947   PACKET_Z3,
1948   PACKET_Z4,
1949   PACKET_vFile_setfs,
1950   PACKET_vFile_open,
1951   PACKET_vFile_pread,
1952   PACKET_vFile_pwrite,
1953   PACKET_vFile_close,
1954   PACKET_vFile_unlink,
1955   PACKET_vFile_readlink,
1956   PACKET_vFile_fstat,
1957   PACKET_qXfer_auxv,
1958   PACKET_qXfer_features,
1959   PACKET_qXfer_exec_file,
1960   PACKET_qXfer_libraries,
1961   PACKET_qXfer_libraries_svr4,
1962   PACKET_qXfer_memory_map,
1963   PACKET_qXfer_spu_read,
1964   PACKET_qXfer_spu_write,
1965   PACKET_qXfer_osdata,
1966   PACKET_qXfer_threads,
1967   PACKET_qXfer_statictrace_read,
1968   PACKET_qXfer_traceframe_info,
1969   PACKET_qXfer_uib,
1970   PACKET_qGetTIBAddr,
1971   PACKET_qGetTLSAddr,
1972   PACKET_qSupported,
1973   PACKET_qTStatus,
1974   PACKET_QPassSignals,
1975   PACKET_QCatchSyscalls,
1976   PACKET_QProgramSignals,
1977   PACKET_QSetWorkingDir,
1978   PACKET_QStartupWithShell,
1979   PACKET_QEnvironmentHexEncoded,
1980   PACKET_QEnvironmentReset,
1981   PACKET_QEnvironmentUnset,
1982   PACKET_qCRC,
1983   PACKET_qSearch_memory,
1984   PACKET_vAttach,
1985   PACKET_vRun,
1986   PACKET_QStartNoAckMode,
1987   PACKET_vKill,
1988   PACKET_qXfer_siginfo_read,
1989   PACKET_qXfer_siginfo_write,
1990   PACKET_qAttached,
1991
1992   /* Support for conditional tracepoints.  */
1993   PACKET_ConditionalTracepoints,
1994
1995   /* Support for target-side breakpoint conditions.  */
1996   PACKET_ConditionalBreakpoints,
1997
1998   /* Support for target-side breakpoint commands.  */
1999   PACKET_BreakpointCommands,
2000
2001   /* Support for fast tracepoints.  */
2002   PACKET_FastTracepoints,
2003
2004   /* Support for static tracepoints.  */
2005   PACKET_StaticTracepoints,
2006
2007   /* Support for installing tracepoints while a trace experiment is
2008      running.  */
2009   PACKET_InstallInTrace,
2010
2011   PACKET_bc,
2012   PACKET_bs,
2013   PACKET_TracepointSource,
2014   PACKET_QAllow,
2015   PACKET_qXfer_fdpic,
2016   PACKET_QDisableRandomization,
2017   PACKET_QAgent,
2018   PACKET_QTBuffer_size,
2019   PACKET_Qbtrace_off,
2020   PACKET_Qbtrace_bts,
2021   PACKET_Qbtrace_pt,
2022   PACKET_qXfer_btrace,
2023
2024   /* Support for the QNonStop packet.  */
2025   PACKET_QNonStop,
2026
2027   /* Support for the QThreadEvents packet.  */
2028   PACKET_QThreadEvents,
2029
2030   /* Support for multi-process extensions.  */
2031   PACKET_multiprocess_feature,
2032
2033   /* Support for enabling and disabling tracepoints while a trace
2034      experiment is running.  */
2035   PACKET_EnableDisableTracepoints_feature,
2036
2037   /* Support for collecting strings using the tracenz bytecode.  */
2038   PACKET_tracenz_feature,
2039
2040   /* Support for continuing to run a trace experiment while GDB is
2041      disconnected.  */
2042   PACKET_DisconnectedTracing_feature,
2043
2044   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
2045   PACKET_augmented_libraries_svr4_read_feature,
2046
2047   /* Support for the qXfer:btrace-conf:read packet.  */
2048   PACKET_qXfer_btrace_conf,
2049
2050   /* Support for the Qbtrace-conf:bts:size packet.  */
2051   PACKET_Qbtrace_conf_bts_size,
2052
2053   /* Support for swbreak+ feature.  */
2054   PACKET_swbreak_feature,
2055
2056   /* Support for hwbreak+ feature.  */
2057   PACKET_hwbreak_feature,
2058
2059   /* Support for fork events.  */
2060   PACKET_fork_event_feature,
2061
2062   /* Support for vfork events.  */
2063   PACKET_vfork_event_feature,
2064
2065   /* Support for the Qbtrace-conf:pt:size packet.  */
2066   PACKET_Qbtrace_conf_pt_size,
2067
2068   /* Support for exec events.  */
2069   PACKET_exec_event_feature,
2070
2071   /* Support for query supported vCont actions.  */
2072   PACKET_vContSupported,
2073
2074   /* Support remote CTRL-C.  */
2075   PACKET_vCtrlC,
2076
2077   /* Support TARGET_WAITKIND_NO_RESUMED.  */
2078   PACKET_no_resumed,
2079
2080   PACKET_MAX
2081 };
2082
2083 static struct packet_config remote_protocol_packets[PACKET_MAX];
2084
2085 /* Returns the packet's corresponding "set remote foo-packet" command
2086    state.  See struct packet_config for more details.  */
2087
2088 static enum auto_boolean
2089 packet_set_cmd_state (int packet)
2090 {
2091   return remote_protocol_packets[packet].detect;
2092 }
2093
2094 /* Returns whether a given packet or feature is supported.  This takes
2095    into account the state of the corresponding "set remote foo-packet"
2096    command, which may be used to bypass auto-detection.  */
2097
2098 static enum packet_support
2099 packet_config_support (struct packet_config *config)
2100 {
2101   switch (config->detect)
2102     {
2103     case AUTO_BOOLEAN_TRUE:
2104       return PACKET_ENABLE;
2105     case AUTO_BOOLEAN_FALSE:
2106       return PACKET_DISABLE;
2107     case AUTO_BOOLEAN_AUTO:
2108       return config->support;
2109     default:
2110       gdb_assert_not_reached (_("bad switch"));
2111     }
2112 }
2113
2114 /* Same as packet_config_support, but takes the packet's enum value as
2115    argument.  */
2116
2117 static enum packet_support
2118 packet_support (int packet)
2119 {
2120   struct packet_config *config = &remote_protocol_packets[packet];
2121
2122   return packet_config_support (config);
2123 }
2124
2125 static void
2126 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2127                                  struct cmd_list_element *c,
2128                                  const char *value)
2129 {
2130   struct packet_config *packet;
2131
2132   for (packet = remote_protocol_packets;
2133        packet < &remote_protocol_packets[PACKET_MAX];
2134        packet++)
2135     {
2136       if (&packet->detect == c->var)
2137         {
2138           show_packet_config_cmd (packet);
2139           return;
2140         }
2141     }
2142   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2143                   c->name);
2144 }
2145
2146 /* Should we try one of the 'Z' requests?  */
2147
2148 enum Z_packet_type
2149 {
2150   Z_PACKET_SOFTWARE_BP,
2151   Z_PACKET_HARDWARE_BP,
2152   Z_PACKET_WRITE_WP,
2153   Z_PACKET_READ_WP,
2154   Z_PACKET_ACCESS_WP,
2155   NR_Z_PACKET_TYPES
2156 };
2157
2158 /* For compatibility with older distributions.  Provide a ``set remote
2159    Z-packet ...'' command that updates all the Z packet types.  */
2160
2161 static enum auto_boolean remote_Z_packet_detect;
2162
2163 static void
2164 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2165                                   struct cmd_list_element *c)
2166 {
2167   int i;
2168
2169   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2170     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2171 }
2172
2173 static void
2174 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2175                                    struct cmd_list_element *c,
2176                                    const char *value)
2177 {
2178   int i;
2179
2180   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2181     {
2182       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2183     }
2184 }
2185
2186 /* Returns true if the multi-process extensions are in effect.  */
2187
2188 static int
2189 remote_multi_process_p (struct remote_state *rs)
2190 {
2191   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2192 }
2193
2194 /* Returns true if fork events are supported.  */
2195
2196 static int
2197 remote_fork_event_p (struct remote_state *rs)
2198 {
2199   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2200 }
2201
2202 /* Returns true if vfork events are supported.  */
2203
2204 static int
2205 remote_vfork_event_p (struct remote_state *rs)
2206 {
2207   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2208 }
2209
2210 /* Returns true if exec events are supported.  */
2211
2212 static int
2213 remote_exec_event_p (struct remote_state *rs)
2214 {
2215   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2216 }
2217
2218 /* Insert fork catchpoint target routine.  If fork events are enabled
2219    then return success, nothing more to do.  */
2220
2221 int
2222 remote_target::insert_fork_catchpoint (int pid)
2223 {
2224   struct remote_state *rs = get_remote_state ();
2225
2226   return !remote_fork_event_p (rs);
2227 }
2228
2229 /* Remove fork catchpoint target routine.  Nothing to do, just
2230    return success.  */
2231
2232 int
2233 remote_target::remove_fork_catchpoint (int pid)
2234 {
2235   return 0;
2236 }
2237
2238 /* Insert vfork catchpoint target routine.  If vfork events are enabled
2239    then return success, nothing more to do.  */
2240
2241 int
2242 remote_target::insert_vfork_catchpoint (int pid)
2243 {
2244   struct remote_state *rs = get_remote_state ();
2245
2246   return !remote_vfork_event_p (rs);
2247 }
2248
2249 /* Remove vfork catchpoint target routine.  Nothing to do, just
2250    return success.  */
2251
2252 int
2253 remote_target::remove_vfork_catchpoint (int pid)
2254 {
2255   return 0;
2256 }
2257
2258 /* Insert exec catchpoint target routine.  If exec events are
2259    enabled, just return success.  */
2260
2261 int
2262 remote_target::insert_exec_catchpoint (int pid)
2263 {
2264   struct remote_state *rs = get_remote_state ();
2265
2266   return !remote_exec_event_p (rs);
2267 }
2268
2269 /* Remove exec catchpoint target routine.  Nothing to do, just
2270    return success.  */
2271
2272 int
2273 remote_target::remove_exec_catchpoint (int pid)
2274 {
2275   return 0;
2276 }
2277
2278 \f
2279
2280 static ptid_t magic_null_ptid;
2281 static ptid_t not_sent_ptid;
2282 static ptid_t any_thread_ptid;
2283
2284 /* Find out if the stub attached to PID (and hence GDB should offer to
2285    detach instead of killing it when bailing out).  */
2286
2287 int
2288 remote_target::remote_query_attached (int pid)
2289 {
2290   struct remote_state *rs = get_remote_state ();
2291   size_t size = get_remote_packet_size ();
2292
2293   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2294     return 0;
2295
2296   if (remote_multi_process_p (rs))
2297     xsnprintf (rs->buf, size, "qAttached:%x", pid);
2298   else
2299     xsnprintf (rs->buf, size, "qAttached");
2300
2301   putpkt (rs->buf);
2302   getpkt (&rs->buf, &rs->buf_size, 0);
2303
2304   switch (packet_ok (rs->buf,
2305                      &remote_protocol_packets[PACKET_qAttached]))
2306     {
2307     case PACKET_OK:
2308       if (strcmp (rs->buf, "1") == 0)
2309         return 1;
2310       break;
2311     case PACKET_ERROR:
2312       warning (_("Remote failure reply: %s"), rs->buf);
2313       break;
2314     case PACKET_UNKNOWN:
2315       break;
2316     }
2317
2318   return 0;
2319 }
2320
2321 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2322    has been invented by GDB, instead of reported by the target.  Since
2323    we can be connected to a remote system before before knowing about
2324    any inferior, mark the target with execution when we find the first
2325    inferior.  If ATTACHED is 1, then we had just attached to this
2326    inferior.  If it is 0, then we just created this inferior.  If it
2327    is -1, then try querying the remote stub to find out if it had
2328    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2329    attempt to open this inferior's executable as the main executable
2330    if no main executable is open already.  */
2331
2332 inferior *
2333 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2334                                     int try_open_exec)
2335 {
2336   struct inferior *inf;
2337
2338   /* Check whether this process we're learning about is to be
2339      considered attached, or if is to be considered to have been
2340      spawned by the stub.  */
2341   if (attached == -1)
2342     attached = remote_query_attached (pid);
2343
2344   if (gdbarch_has_global_solist (target_gdbarch ()))
2345     {
2346       /* If the target shares code across all inferiors, then every
2347          attach adds a new inferior.  */
2348       inf = add_inferior (pid);
2349
2350       /* ... and every inferior is bound to the same program space.
2351          However, each inferior may still have its own address
2352          space.  */
2353       inf->aspace = maybe_new_address_space ();
2354       inf->pspace = current_program_space;
2355     }
2356   else
2357     {
2358       /* In the traditional debugging scenario, there's a 1-1 match
2359          between program/address spaces.  We simply bind the inferior
2360          to the program space's address space.  */
2361       inf = current_inferior ();
2362       inferior_appeared (inf, pid);
2363     }
2364
2365   inf->attach_flag = attached;
2366   inf->fake_pid_p = fake_pid_p;
2367
2368   /* If no main executable is currently open then attempt to
2369      open the file that was executed to create this inferior.  */
2370   if (try_open_exec && get_exec_file (0) == NULL)
2371     exec_file_locate_attach (pid, 0, 1);
2372
2373   return inf;
2374 }
2375
2376 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2377 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
2378
2379 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2380    according to RUNNING.  */
2381
2382 thread_info *
2383 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2384 {
2385   struct remote_state *rs = get_remote_state ();
2386   struct thread_info *thread;
2387
2388   /* GDB historically didn't pull threads in the initial connection
2389      setup.  If the remote target doesn't even have a concept of
2390      threads (e.g., a bare-metal target), even if internally we
2391      consider that a single-threaded target, mentioning a new thread
2392      might be confusing to the user.  Be silent then, preserving the
2393      age old behavior.  */
2394   if (rs->starting_up)
2395     thread = add_thread_silent (ptid);
2396   else
2397     thread = add_thread (ptid);
2398
2399   get_remote_thread_info (thread)->vcont_resumed = executing;
2400   set_executing (ptid, executing);
2401   set_running (ptid, running);
2402
2403   return thread;
2404 }
2405
2406 /* Come here when we learn about a thread id from the remote target.
2407    It may be the first time we hear about such thread, so take the
2408    opportunity to add it to GDB's thread list.  In case this is the
2409    first time we're noticing its corresponding inferior, add it to
2410    GDB's inferior list as well.  EXECUTING indicates whether the
2411    thread is (internally) executing or stopped.  */
2412
2413 void
2414 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2415 {
2416   /* In non-stop mode, we assume new found threads are (externally)
2417      running until proven otherwise with a stop reply.  In all-stop,
2418      we can only get here if all threads are stopped.  */
2419   int running = target_is_non_stop_p () ? 1 : 0;
2420
2421   /* If this is a new thread, add it to GDB's thread list.
2422      If we leave it up to WFI to do this, bad things will happen.  */
2423
2424   thread_info *tp = find_thread_ptid (currthread);
2425   if (tp != NULL && tp->state == THREAD_EXITED)
2426     {
2427       /* We're seeing an event on a thread id we knew had exited.
2428          This has to be a new thread reusing the old id.  Add it.  */
2429       remote_add_thread (currthread, running, executing);
2430       return;
2431     }
2432
2433   if (!in_thread_list (currthread))
2434     {
2435       struct inferior *inf = NULL;
2436       int pid = currthread.pid ();
2437
2438       if (inferior_ptid.is_pid ()
2439           && pid == inferior_ptid.pid ())
2440         {
2441           /* inferior_ptid has no thread member yet.  This can happen
2442              with the vAttach -> remote_wait,"TAAthread:" path if the
2443              stub doesn't support qC.  This is the first stop reported
2444              after an attach, so this is the main thread.  Update the
2445              ptid in the thread list.  */
2446           if (in_thread_list (ptid_t (pid)))
2447             thread_change_ptid (inferior_ptid, currthread);
2448           else
2449             {
2450               remote_add_thread (currthread, running, executing);
2451               inferior_ptid = currthread;
2452             }
2453           return;
2454         }
2455
2456       if (magic_null_ptid == inferior_ptid)
2457         {
2458           /* inferior_ptid is not set yet.  This can happen with the
2459              vRun -> remote_wait,"TAAthread:" path if the stub
2460              doesn't support qC.  This is the first stop reported
2461              after an attach, so this is the main thread.  Update the
2462              ptid in the thread list.  */
2463           thread_change_ptid (inferior_ptid, currthread);
2464           return;
2465         }
2466
2467       /* When connecting to a target remote, or to a target
2468          extended-remote which already was debugging an inferior, we
2469          may not know about it yet.  Add it before adding its child
2470          thread, so notifications are emitted in a sensible order.  */
2471       if (find_inferior_pid (currthread.pid ()) == NULL)
2472         {
2473           struct remote_state *rs = get_remote_state ();
2474           int fake_pid_p = !remote_multi_process_p (rs);
2475
2476           inf = remote_add_inferior (fake_pid_p,
2477                                      currthread.pid (), -1, 1);
2478         }
2479
2480       /* This is really a new thread.  Add it.  */
2481       thread_info *new_thr
2482         = remote_add_thread (currthread, running, executing);
2483
2484       /* If we found a new inferior, let the common code do whatever
2485          it needs to with it (e.g., read shared libraries, insert
2486          breakpoints), unless we're just setting up an all-stop
2487          connection.  */
2488       if (inf != NULL)
2489         {
2490           struct remote_state *rs = get_remote_state ();
2491
2492           if (!rs->starting_up)
2493             notice_new_inferior (new_thr, executing, 0);
2494         }
2495     }
2496 }
2497
2498 /* Return THREAD's private thread data, creating it if necessary.  */
2499
2500 static remote_thread_info *
2501 get_remote_thread_info (thread_info *thread)
2502 {
2503   gdb_assert (thread != NULL);
2504
2505   if (thread->priv == NULL)
2506     thread->priv.reset (new remote_thread_info);
2507
2508   return static_cast<remote_thread_info *> (thread->priv.get ());
2509 }
2510
2511 static remote_thread_info *
2512 get_remote_thread_info (ptid_t ptid)
2513 {
2514   thread_info *thr = find_thread_ptid (ptid);
2515   return get_remote_thread_info (thr);
2516 }
2517
2518 /* Call this function as a result of
2519    1) A halt indication (T packet) containing a thread id
2520    2) A direct query of currthread
2521    3) Successful execution of set thread */
2522
2523 static void
2524 record_currthread (struct remote_state *rs, ptid_t currthread)
2525 {
2526   rs->general_thread = currthread;
2527 }
2528
2529 /* If 'QPassSignals' is supported, tell the remote stub what signals
2530    it can simply pass through to the inferior without reporting.  */
2531
2532 void
2533 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2534 {
2535   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2536     {
2537       char *pass_packet, *p;
2538       int count = 0, i;
2539       struct remote_state *rs = get_remote_state ();
2540
2541       gdb_assert (numsigs < 256);
2542       for (i = 0; i < numsigs; i++)
2543         {
2544           if (pass_signals[i])
2545             count++;
2546         }
2547       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2548       strcpy (pass_packet, "QPassSignals:");
2549       p = pass_packet + strlen (pass_packet);
2550       for (i = 0; i < numsigs; i++)
2551         {
2552           if (pass_signals[i])
2553             {
2554               if (i >= 16)
2555                 *p++ = tohex (i >> 4);
2556               *p++ = tohex (i & 15);
2557               if (count)
2558                 *p++ = ';';
2559               else
2560                 break;
2561               count--;
2562             }
2563         }
2564       *p = 0;
2565       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2566         {
2567           putpkt (pass_packet);
2568           getpkt (&rs->buf, &rs->buf_size, 0);
2569           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2570           if (rs->last_pass_packet)
2571             xfree (rs->last_pass_packet);
2572           rs->last_pass_packet = pass_packet;
2573         }
2574       else
2575         xfree (pass_packet);
2576     }
2577 }
2578
2579 /* If 'QCatchSyscalls' is supported, tell the remote stub
2580    to report syscalls to GDB.  */
2581
2582 int
2583 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2584                                        gdb::array_view<const int> syscall_counts)
2585 {
2586   const char *catch_packet;
2587   enum packet_result result;
2588   int n_sysno = 0;
2589
2590   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2591     {
2592       /* Not supported.  */
2593       return 1;
2594     }
2595
2596   if (needed && any_count == 0)
2597     {
2598       /* Count how many syscalls are to be caught.  */
2599       for (size_t i = 0; i < syscall_counts.size (); i++)
2600         {
2601           if (syscall_counts[i] != 0)
2602             n_sysno++;
2603         }
2604     }
2605
2606   if (remote_debug)
2607     {
2608       fprintf_unfiltered (gdb_stdlog,
2609                           "remote_set_syscall_catchpoint "
2610                           "pid %d needed %d any_count %d n_sysno %d\n",
2611                           pid, needed, any_count, n_sysno);
2612     }
2613
2614   std::string built_packet;
2615   if (needed)
2616     {
2617       /* Prepare a packet with the sysno list, assuming max 8+1
2618          characters for a sysno.  If the resulting packet size is too
2619          big, fallback on the non-selective packet.  */
2620       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2621       built_packet.reserve (maxpktsz);
2622       built_packet = "QCatchSyscalls:1";
2623       if (any_count == 0)
2624         {
2625           /* Add in each syscall to be caught.  */
2626           for (size_t i = 0; i < syscall_counts.size (); i++)
2627             {
2628               if (syscall_counts[i] != 0)
2629                 string_appendf (built_packet, ";%zx", i);
2630             }
2631         }
2632       if (built_packet.size () > get_remote_packet_size ())
2633         {
2634           /* catch_packet too big.  Fallback to less efficient
2635              non selective mode, with GDB doing the filtering.  */
2636           catch_packet = "QCatchSyscalls:1";
2637         }
2638       else
2639         catch_packet = built_packet.c_str ();
2640     }
2641   else
2642     catch_packet = "QCatchSyscalls:0";
2643
2644   struct remote_state *rs = get_remote_state ();
2645
2646   putpkt (catch_packet);
2647   getpkt (&rs->buf, &rs->buf_size, 0);
2648   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2649   if (result == PACKET_OK)
2650     return 0;
2651   else
2652     return -1;
2653 }
2654
2655 /* If 'QProgramSignals' is supported, tell the remote stub what
2656    signals it should pass through to the inferior when detaching.  */
2657
2658 void
2659 remote_target::program_signals (int numsigs, unsigned char *signals)
2660 {
2661   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2662     {
2663       char *packet, *p;
2664       int count = 0, i;
2665       struct remote_state *rs = get_remote_state ();
2666
2667       gdb_assert (numsigs < 256);
2668       for (i = 0; i < numsigs; i++)
2669         {
2670           if (signals[i])
2671             count++;
2672         }
2673       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2674       strcpy (packet, "QProgramSignals:");
2675       p = packet + strlen (packet);
2676       for (i = 0; i < numsigs; i++)
2677         {
2678           if (signal_pass_state (i))
2679             {
2680               if (i >= 16)
2681                 *p++ = tohex (i >> 4);
2682               *p++ = tohex (i & 15);
2683               if (count)
2684                 *p++ = ';';
2685               else
2686                 break;
2687               count--;
2688             }
2689         }
2690       *p = 0;
2691       if (!rs->last_program_signals_packet
2692           || strcmp (rs->last_program_signals_packet, packet) != 0)
2693         {
2694           putpkt (packet);
2695           getpkt (&rs->buf, &rs->buf_size, 0);
2696           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2697           xfree (rs->last_program_signals_packet);
2698           rs->last_program_signals_packet = packet;
2699         }
2700       else
2701         xfree (packet);
2702     }
2703 }
2704
2705 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2706    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2707    thread.  If GEN is set, set the general thread, if not, then set
2708    the step/continue thread.  */
2709 void
2710 remote_target::set_thread (ptid_t ptid, int gen)
2711 {
2712   struct remote_state *rs = get_remote_state ();
2713   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2714   char *buf = rs->buf;
2715   char *endbuf = rs->buf + get_remote_packet_size ();
2716
2717   if (state == ptid)
2718     return;
2719
2720   *buf++ = 'H';
2721   *buf++ = gen ? 'g' : 'c';
2722   if (ptid == magic_null_ptid)
2723     xsnprintf (buf, endbuf - buf, "0");
2724   else if (ptid == any_thread_ptid)
2725     xsnprintf (buf, endbuf - buf, "0");
2726   else if (ptid == minus_one_ptid)
2727     xsnprintf (buf, endbuf - buf, "-1");
2728   else
2729     write_ptid (buf, endbuf, ptid);
2730   putpkt (rs->buf);
2731   getpkt (&rs->buf, &rs->buf_size, 0);
2732   if (gen)
2733     rs->general_thread = ptid;
2734   else
2735     rs->continue_thread = ptid;
2736 }
2737
2738 void
2739 remote_target::set_general_thread (ptid_t ptid)
2740 {
2741   set_thread (ptid, 1);
2742 }
2743
2744 void
2745 remote_target::set_continue_thread (ptid_t ptid)
2746 {
2747   set_thread (ptid, 0);
2748 }
2749
2750 /* Change the remote current process.  Which thread within the process
2751    ends up selected isn't important, as long as it is the same process
2752    as what INFERIOR_PTID points to.
2753
2754    This comes from that fact that there is no explicit notion of
2755    "selected process" in the protocol.  The selected process for
2756    general operations is the process the selected general thread
2757    belongs to.  */
2758
2759 void
2760 remote_target::set_general_process ()
2761 {
2762   struct remote_state *rs = get_remote_state ();
2763
2764   /* If the remote can't handle multiple processes, don't bother.  */
2765   if (!remote_multi_process_p (rs))
2766     return;
2767
2768   /* We only need to change the remote current thread if it's pointing
2769      at some other process.  */
2770   if (rs->general_thread.pid () != inferior_ptid.pid ())
2771     set_general_thread (inferior_ptid);
2772 }
2773
2774 \f
2775 /* Return nonzero if this is the main thread that we made up ourselves
2776    to model non-threaded targets as single-threaded.  */
2777
2778 static int
2779 remote_thread_always_alive (ptid_t ptid)
2780 {
2781   if (ptid == magic_null_ptid)
2782     /* The main thread is always alive.  */
2783     return 1;
2784
2785   if (ptid.pid () != 0 && ptid.lwp () == 0)
2786     /* The main thread is always alive.  This can happen after a
2787        vAttach, if the remote side doesn't support
2788        multi-threading.  */
2789     return 1;
2790
2791   return 0;
2792 }
2793
2794 /* Return nonzero if the thread PTID is still alive on the remote
2795    system.  */
2796
2797 bool
2798 remote_target::thread_alive (ptid_t ptid)
2799 {
2800   struct remote_state *rs = get_remote_state ();
2801   char *p, *endp;
2802
2803   /* Check if this is a thread that we made up ourselves to model
2804      non-threaded targets as single-threaded.  */
2805   if (remote_thread_always_alive (ptid))
2806     return 1;
2807
2808   p = rs->buf;
2809   endp = rs->buf + get_remote_packet_size ();
2810
2811   *p++ = 'T';
2812   write_ptid (p, endp, ptid);
2813
2814   putpkt (rs->buf);
2815   getpkt (&rs->buf, &rs->buf_size, 0);
2816   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2817 }
2818
2819 /* Return a pointer to a thread name if we know it and NULL otherwise.
2820    The thread_info object owns the memory for the name.  */
2821
2822 const char *
2823 remote_target::thread_name (struct thread_info *info)
2824 {
2825   if (info->priv != NULL)
2826     {
2827       const std::string &name = get_remote_thread_info (info)->name;
2828       return !name.empty () ? name.c_str () : NULL;
2829     }
2830
2831   return NULL;
2832 }
2833
2834 /* About these extended threadlist and threadinfo packets.  They are
2835    variable length packets but, the fields within them are often fixed
2836    length.  They are redundent enough to send over UDP as is the
2837    remote protocol in general.  There is a matching unit test module
2838    in libstub.  */
2839
2840 /* WARNING: This threadref data structure comes from the remote O.S.,
2841    libstub protocol encoding, and remote.c.  It is not particularly
2842    changable.  */
2843
2844 /* Right now, the internal structure is int. We want it to be bigger.
2845    Plan to fix this.  */
2846
2847 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2848
2849 /* gdb_ext_thread_info is an internal GDB data structure which is
2850    equivalent to the reply of the remote threadinfo packet.  */
2851
2852 struct gdb_ext_thread_info
2853   {
2854     threadref threadid;         /* External form of thread reference.  */
2855     int active;                 /* Has state interesting to GDB?
2856                                    regs, stack.  */
2857     char display[256];          /* Brief state display, name,
2858                                    blocked/suspended.  */
2859     char shortname[32];         /* To be used to name threads.  */
2860     char more_display[256];     /* Long info, statistics, queue depth,
2861                                    whatever.  */
2862   };
2863
2864 /* The volume of remote transfers can be limited by submitting
2865    a mask containing bits specifying the desired information.
2866    Use a union of these values as the 'selection' parameter to
2867    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2868
2869 #define TAG_THREADID 1
2870 #define TAG_EXISTS 2
2871 #define TAG_DISPLAY 4
2872 #define TAG_THREADNAME 8
2873 #define TAG_MOREDISPLAY 16
2874
2875 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2876
2877 static char *unpack_nibble (char *buf, int *val);
2878
2879 static char *unpack_byte (char *buf, int *value);
2880
2881 static char *pack_int (char *buf, int value);
2882
2883 static char *unpack_int (char *buf, int *value);
2884
2885 static char *unpack_string (char *src, char *dest, int length);
2886
2887 static char *pack_threadid (char *pkt, threadref *id);
2888
2889 static char *unpack_threadid (char *inbuf, threadref *id);
2890
2891 void int_to_threadref (threadref *id, int value);
2892
2893 static int threadref_to_int (threadref *ref);
2894
2895 static void copy_threadref (threadref *dest, threadref *src);
2896
2897 static int threadmatch (threadref *dest, threadref *src);
2898
2899 static char *pack_threadinfo_request (char *pkt, int mode,
2900                                       threadref *id);
2901
2902 static char *pack_threadlist_request (char *pkt, int startflag,
2903                                       int threadcount,
2904                                       threadref *nextthread);
2905
2906 static int remote_newthread_step (threadref *ref, void *context);
2907
2908
2909 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2910    buffer we're allowed to write to.  Returns
2911    BUF+CHARACTERS_WRITTEN.  */
2912
2913 char *
2914 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2915 {
2916   int pid, tid;
2917   struct remote_state *rs = get_remote_state ();
2918
2919   if (remote_multi_process_p (rs))
2920     {
2921       pid = ptid.pid ();
2922       if (pid < 0)
2923         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2924       else
2925         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2926     }
2927   tid = ptid.lwp ();
2928   if (tid < 0)
2929     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2930   else
2931     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2932
2933   return buf;
2934 }
2935
2936 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2937    last parsed char.  Returns null_ptid if no thread id is found, and
2938    throws an error if the thread id has an invalid format.  */
2939
2940 static ptid_t
2941 read_ptid (const char *buf, const char **obuf)
2942 {
2943   const char *p = buf;
2944   const char *pp;
2945   ULONGEST pid = 0, tid = 0;
2946
2947   if (*p == 'p')
2948     {
2949       /* Multi-process ptid.  */
2950       pp = unpack_varlen_hex (p + 1, &pid);
2951       if (*pp != '.')
2952         error (_("invalid remote ptid: %s"), p);
2953
2954       p = pp;
2955       pp = unpack_varlen_hex (p + 1, &tid);
2956       if (obuf)
2957         *obuf = pp;
2958       return ptid_t (pid, tid, 0);
2959     }
2960
2961   /* No multi-process.  Just a tid.  */
2962   pp = unpack_varlen_hex (p, &tid);
2963
2964   /* Return null_ptid when no thread id is found.  */
2965   if (p == pp)
2966     {
2967       if (obuf)
2968         *obuf = pp;
2969       return null_ptid;
2970     }
2971
2972   /* Since the stub is not sending a process id, then default to
2973      what's in inferior_ptid, unless it's null at this point.  If so,
2974      then since there's no way to know the pid of the reported
2975      threads, use the magic number.  */
2976   if (inferior_ptid == null_ptid)
2977     pid = magic_null_ptid.pid ();
2978   else
2979     pid = inferior_ptid.pid ();
2980
2981   if (obuf)
2982     *obuf = pp;
2983   return ptid_t (pid, tid, 0);
2984 }
2985
2986 static int
2987 stubhex (int ch)
2988 {
2989   if (ch >= 'a' && ch <= 'f')
2990     return ch - 'a' + 10;
2991   if (ch >= '0' && ch <= '9')
2992     return ch - '0';
2993   if (ch >= 'A' && ch <= 'F')
2994     return ch - 'A' + 10;
2995   return -1;
2996 }
2997
2998 static int
2999 stub_unpack_int (char *buff, int fieldlength)
3000 {
3001   int nibble;
3002   int retval = 0;
3003
3004   while (fieldlength)
3005     {
3006       nibble = stubhex (*buff++);
3007       retval |= nibble;
3008       fieldlength--;
3009       if (fieldlength)
3010         retval = retval << 4;
3011     }
3012   return retval;
3013 }
3014
3015 static char *
3016 unpack_nibble (char *buf, int *val)
3017 {
3018   *val = fromhex (*buf++);
3019   return buf;
3020 }
3021
3022 static char *
3023 unpack_byte (char *buf, int *value)
3024 {
3025   *value = stub_unpack_int (buf, 2);
3026   return buf + 2;
3027 }
3028
3029 static char *
3030 pack_int (char *buf, int value)
3031 {
3032   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3033   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3034   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3035   buf = pack_hex_byte (buf, (value & 0xff));
3036   return buf;
3037 }
3038
3039 static char *
3040 unpack_int (char *buf, int *value)
3041 {
3042   *value = stub_unpack_int (buf, 8);
3043   return buf + 8;
3044 }
3045
3046 #if 0                   /* Currently unused, uncomment when needed.  */
3047 static char *pack_string (char *pkt, char *string);
3048
3049 static char *
3050 pack_string (char *pkt, char *string)
3051 {
3052   char ch;
3053   int len;
3054
3055   len = strlen (string);
3056   if (len > 200)
3057     len = 200;          /* Bigger than most GDB packets, junk???  */
3058   pkt = pack_hex_byte (pkt, len);
3059   while (len-- > 0)
3060     {
3061       ch = *string++;
3062       if ((ch == '\0') || (ch == '#'))
3063         ch = '*';               /* Protect encapsulation.  */
3064       *pkt++ = ch;
3065     }
3066   return pkt;
3067 }
3068 #endif /* 0 (unused) */
3069
3070 static char *
3071 unpack_string (char *src, char *dest, int length)
3072 {
3073   while (length--)
3074     *dest++ = *src++;
3075   *dest = '\0';
3076   return src;
3077 }
3078
3079 static char *
3080 pack_threadid (char *pkt, threadref *id)
3081 {
3082   char *limit;
3083   unsigned char *altid;
3084
3085   altid = (unsigned char *) id;
3086   limit = pkt + BUF_THREAD_ID_SIZE;
3087   while (pkt < limit)
3088     pkt = pack_hex_byte (pkt, *altid++);
3089   return pkt;
3090 }
3091
3092
3093 static char *
3094 unpack_threadid (char *inbuf, threadref *id)
3095 {
3096   char *altref;
3097   char *limit = inbuf + BUF_THREAD_ID_SIZE;
3098   int x, y;
3099
3100   altref = (char *) id;
3101
3102   while (inbuf < limit)
3103     {
3104       x = stubhex (*inbuf++);
3105       y = stubhex (*inbuf++);
3106       *altref++ = (x << 4) | y;
3107     }
3108   return inbuf;
3109 }
3110
3111 /* Externally, threadrefs are 64 bits but internally, they are still
3112    ints.  This is due to a mismatch of specifications.  We would like
3113    to use 64bit thread references internally.  This is an adapter
3114    function.  */
3115
3116 void
3117 int_to_threadref (threadref *id, int value)
3118 {
3119   unsigned char *scan;
3120
3121   scan = (unsigned char *) id;
3122   {
3123     int i = 4;
3124     while (i--)
3125       *scan++ = 0;
3126   }
3127   *scan++ = (value >> 24) & 0xff;
3128   *scan++ = (value >> 16) & 0xff;
3129   *scan++ = (value >> 8) & 0xff;
3130   *scan++ = (value & 0xff);
3131 }
3132
3133 static int
3134 threadref_to_int (threadref *ref)
3135 {
3136   int i, value = 0;
3137   unsigned char *scan;
3138
3139   scan = *ref;
3140   scan += 4;
3141   i = 4;
3142   while (i-- > 0)
3143     value = (value << 8) | ((*scan++) & 0xff);
3144   return value;
3145 }
3146
3147 static void
3148 copy_threadref (threadref *dest, threadref *src)
3149 {
3150   int i;
3151   unsigned char *csrc, *cdest;
3152
3153   csrc = (unsigned char *) src;
3154   cdest = (unsigned char *) dest;
3155   i = 8;
3156   while (i--)
3157     *cdest++ = *csrc++;
3158 }
3159
3160 static int
3161 threadmatch (threadref *dest, threadref *src)
3162 {
3163   /* Things are broken right now, so just assume we got a match.  */
3164 #if 0
3165   unsigned char *srcp, *destp;
3166   int i, result;
3167   srcp = (char *) src;
3168   destp = (char *) dest;
3169
3170   result = 1;
3171   while (i-- > 0)
3172     result &= (*srcp++ == *destp++) ? 1 : 0;
3173   return result;
3174 #endif
3175   return 1;
3176 }
3177
3178 /*
3179    threadid:1,        # always request threadid
3180    context_exists:2,
3181    display:4,
3182    unique_name:8,
3183    more_display:16
3184  */
3185
3186 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
3187
3188 static char *
3189 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3190 {
3191   *pkt++ = 'q';                         /* Info Query */
3192   *pkt++ = 'P';                         /* process or thread info */
3193   pkt = pack_int (pkt, mode);           /* mode */
3194   pkt = pack_threadid (pkt, id);        /* threadid */
3195   *pkt = '\0';                          /* terminate */
3196   return pkt;
3197 }
3198
3199 /* These values tag the fields in a thread info response packet.  */
3200 /* Tagging the fields allows us to request specific fields and to
3201    add more fields as time goes by.  */
3202
3203 #define TAG_THREADID 1          /* Echo the thread identifier.  */
3204 #define TAG_EXISTS 2            /* Is this process defined enough to
3205                                    fetch registers and its stack?  */
3206 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
3207 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
3208 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
3209                                    the process.  */
3210
3211 int
3212 remote_target::remote_unpack_thread_info_response (char *pkt,
3213                                                    threadref *expectedref,
3214                                                    gdb_ext_thread_info *info)
3215 {
3216   struct remote_state *rs = get_remote_state ();
3217   int mask, length;
3218   int tag;
3219   threadref ref;
3220   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
3221   int retval = 1;
3222
3223   /* info->threadid = 0; FIXME: implement zero_threadref.  */
3224   info->active = 0;
3225   info->display[0] = '\0';
3226   info->shortname[0] = '\0';
3227   info->more_display[0] = '\0';
3228
3229   /* Assume the characters indicating the packet type have been
3230      stripped.  */
3231   pkt = unpack_int (pkt, &mask);        /* arg mask */
3232   pkt = unpack_threadid (pkt, &ref);
3233
3234   if (mask == 0)
3235     warning (_("Incomplete response to threadinfo request."));
3236   if (!threadmatch (&ref, expectedref))
3237     {                   /* This is an answer to a different request.  */
3238       warning (_("ERROR RMT Thread info mismatch."));
3239       return 0;
3240     }
3241   copy_threadref (&info->threadid, &ref);
3242
3243   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
3244
3245   /* Packets are terminated with nulls.  */
3246   while ((pkt < limit) && mask && *pkt)
3247     {
3248       pkt = unpack_int (pkt, &tag);     /* tag */
3249       pkt = unpack_byte (pkt, &length); /* length */
3250       if (!(tag & mask))                /* Tags out of synch with mask.  */
3251         {
3252           warning (_("ERROR RMT: threadinfo tag mismatch."));
3253           retval = 0;
3254           break;
3255         }
3256       if (tag == TAG_THREADID)
3257         {
3258           if (length != 16)
3259             {
3260               warning (_("ERROR RMT: length of threadid is not 16."));
3261               retval = 0;
3262               break;
3263             }
3264           pkt = unpack_threadid (pkt, &ref);
3265           mask = mask & ~TAG_THREADID;
3266           continue;
3267         }
3268       if (tag == TAG_EXISTS)
3269         {
3270           info->active = stub_unpack_int (pkt, length);
3271           pkt += length;
3272           mask = mask & ~(TAG_EXISTS);
3273           if (length > 8)
3274             {
3275               warning (_("ERROR RMT: 'exists' length too long."));
3276               retval = 0;
3277               break;
3278             }
3279           continue;
3280         }
3281       if (tag == TAG_THREADNAME)
3282         {
3283           pkt = unpack_string (pkt, &info->shortname[0], length);
3284           mask = mask & ~TAG_THREADNAME;
3285           continue;
3286         }
3287       if (tag == TAG_DISPLAY)
3288         {
3289           pkt = unpack_string (pkt, &info->display[0], length);
3290           mask = mask & ~TAG_DISPLAY;
3291           continue;
3292         }
3293       if (tag == TAG_MOREDISPLAY)
3294         {
3295           pkt = unpack_string (pkt, &info->more_display[0], length);
3296           mask = mask & ~TAG_MOREDISPLAY;
3297           continue;
3298         }
3299       warning (_("ERROR RMT: unknown thread info tag."));
3300       break;                    /* Not a tag we know about.  */
3301     }
3302   return retval;
3303 }
3304
3305 int
3306 remote_target::remote_get_threadinfo (threadref *threadid,
3307                                       int fieldset,
3308                                       gdb_ext_thread_info *info)
3309 {
3310   struct remote_state *rs = get_remote_state ();
3311   int result;
3312
3313   pack_threadinfo_request (rs->buf, fieldset, threadid);
3314   putpkt (rs->buf);
3315   getpkt (&rs->buf, &rs->buf_size, 0);
3316
3317   if (rs->buf[0] == '\0')
3318     return 0;
3319
3320   result = remote_unpack_thread_info_response (rs->buf + 2,
3321                                                threadid, info);
3322   return result;
3323 }
3324
3325 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3326
3327 static char *
3328 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3329                          threadref *nextthread)
3330 {
3331   *pkt++ = 'q';                 /* info query packet */
3332   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3333   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3334   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3335   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3336   *pkt = '\0';
3337   return pkt;
3338 }
3339
3340 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3341
3342 int
3343 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3344                                           threadref *original_echo,
3345                                           threadref *resultlist,
3346                                           int *doneflag)
3347 {
3348   struct remote_state *rs = get_remote_state ();
3349   char *limit;
3350   int count, resultcount, done;
3351
3352   resultcount = 0;
3353   /* Assume the 'q' and 'M chars have been stripped.  */
3354   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3355   /* done parse past here */
3356   pkt = unpack_byte (pkt, &count);      /* count field */
3357   pkt = unpack_nibble (pkt, &done);
3358   /* The first threadid is the argument threadid.  */
3359   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3360   while ((count-- > 0) && (pkt < limit))
3361     {
3362       pkt = unpack_threadid (pkt, resultlist++);
3363       if (resultcount++ >= result_limit)
3364         break;
3365     }
3366   if (doneflag)
3367     *doneflag = done;
3368   return resultcount;
3369 }
3370
3371 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3372    qL packet is not supported, 0 on error and 1 on success.  */
3373
3374 int
3375 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3376                                       int result_limit, int *done, int *result_count,
3377                                       threadref *threadlist)
3378 {
3379   struct remote_state *rs = get_remote_state ();
3380   int result = 1;
3381
3382   /* Trancate result limit to be smaller than the packet size.  */
3383   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3384       >= get_remote_packet_size ())
3385     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3386
3387   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3388   putpkt (rs->buf);
3389   getpkt (&rs->buf, &rs->buf_size, 0);
3390   if (*rs->buf == '\0')
3391     {
3392       /* Packet not supported.  */
3393       return -1;
3394     }
3395
3396   *result_count =
3397     parse_threadlist_response (rs->buf + 2, result_limit,
3398                                &rs->echo_nextthread, threadlist, done);
3399
3400   if (!threadmatch (&rs->echo_nextthread, nextthread))
3401     {
3402       /* FIXME: This is a good reason to drop the packet.  */
3403       /* Possably, there is a duplicate response.  */
3404       /* Possabilities :
3405          retransmit immediatly - race conditions
3406          retransmit after timeout - yes
3407          exit
3408          wait for packet, then exit
3409        */
3410       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3411       return 0;                 /* I choose simply exiting.  */
3412     }
3413   if (*result_count <= 0)
3414     {
3415       if (*done != 1)
3416         {
3417           warning (_("RMT ERROR : failed to get remote thread list."));
3418           result = 0;
3419         }
3420       return result;            /* break; */
3421     }
3422   if (*result_count > result_limit)
3423     {
3424       *result_count = 0;
3425       warning (_("RMT ERROR: threadlist response longer than requested."));
3426       return 0;
3427     }
3428   return result;
3429 }
3430
3431 /* Fetch the list of remote threads, with the qL packet, and call
3432    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3433    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3434    STEPFUNCTION returns false.  If the packet is not supported,
3435    returns -1.  */
3436
3437 int
3438 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3439                                            void *context, int looplimit)
3440 {
3441   struct remote_state *rs = get_remote_state ();
3442   int done, i, result_count;
3443   int startflag = 1;
3444   int result = 1;
3445   int loopcount = 0;
3446
3447   done = 0;
3448   while (!done)
3449     {
3450       if (loopcount++ > looplimit)
3451         {
3452           result = 0;
3453           warning (_("Remote fetch threadlist -infinite loop-."));
3454           break;
3455         }
3456       result = remote_get_threadlist (startflag, &rs->nextthread,
3457                                       MAXTHREADLISTRESULTS,
3458                                       &done, &result_count,
3459                                       rs->resultthreadlist);
3460       if (result <= 0)
3461         break;
3462       /* Clear for later iterations.  */
3463       startflag = 0;
3464       /* Setup to resume next batch of thread references, set nextthread.  */
3465       if (result_count >= 1)
3466         copy_threadref (&rs->nextthread,
3467                         &rs->resultthreadlist[result_count - 1]);
3468       i = 0;
3469       while (result_count--)
3470         {
3471           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3472             {
3473               result = 0;
3474               break;
3475             }
3476         }
3477     }
3478   return result;
3479 }
3480
3481 /* A thread found on the remote target.  */
3482
3483 struct thread_item
3484 {
3485   explicit thread_item (ptid_t ptid_)
3486   : ptid (ptid_)
3487   {}
3488
3489   thread_item (thread_item &&other) = default;
3490   thread_item &operator= (thread_item &&other) = default;
3491
3492   DISABLE_COPY_AND_ASSIGN (thread_item);
3493
3494   /* The thread's PTID.  */
3495   ptid_t ptid;
3496
3497   /* The thread's extra info.  */
3498   std::string extra;
3499
3500   /* The thread's name.  */
3501   std::string name;
3502
3503   /* The core the thread was running on.  -1 if not known.  */
3504   int core = -1;
3505
3506   /* The thread handle associated with the thread.  */
3507   gdb::byte_vector thread_handle;
3508 };
3509
3510 /* Context passed around to the various methods listing remote
3511    threads.  As new threads are found, they're added to the ITEMS
3512    vector.  */
3513
3514 struct threads_listing_context
3515 {
3516   /* Return true if this object contains an entry for a thread with ptid
3517      PTID.  */
3518
3519   bool contains_thread (ptid_t ptid) const
3520   {
3521     auto match_ptid = [&] (const thread_item &item)
3522       {
3523         return item.ptid == ptid;
3524       };
3525
3526     auto it = std::find_if (this->items.begin (),
3527                             this->items.end (),
3528                             match_ptid);
3529
3530     return it != this->items.end ();
3531   }
3532
3533   /* Remove the thread with ptid PTID.  */
3534
3535   void remove_thread (ptid_t ptid)
3536   {
3537     auto match_ptid = [&] (const thread_item &item)
3538       {
3539         return item.ptid == ptid;
3540       };
3541
3542     auto it = std::remove_if (this->items.begin (),
3543                               this->items.end (),
3544                               match_ptid);
3545
3546     if (it != this->items.end ())
3547       this->items.erase (it);
3548   }
3549
3550   /* The threads found on the remote target.  */
3551   std::vector<thread_item> items;
3552 };
3553
3554 static int
3555 remote_newthread_step (threadref *ref, void *data)
3556 {
3557   struct threads_listing_context *context
3558     = (struct threads_listing_context *) data;
3559   int pid = inferior_ptid.pid ();
3560   int lwp = threadref_to_int (ref);
3561   ptid_t ptid (pid, lwp);
3562
3563   context->items.emplace_back (ptid);
3564
3565   return 1;                     /* continue iterator */
3566 }
3567
3568 #define CRAZY_MAX_THREADS 1000
3569
3570 ptid_t
3571 remote_target::remote_current_thread (ptid_t oldpid)
3572 {
3573   struct remote_state *rs = get_remote_state ();
3574
3575   putpkt ("qC");
3576   getpkt (&rs->buf, &rs->buf_size, 0);
3577   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3578     {
3579       const char *obuf;
3580       ptid_t result;
3581
3582       result = read_ptid (&rs->buf[2], &obuf);
3583       if (*obuf != '\0' && remote_debug)
3584         fprintf_unfiltered (gdb_stdlog,
3585                             "warning: garbage in qC reply\n");
3586
3587       return result;
3588     }
3589   else
3590     return oldpid;
3591 }
3592
3593 /* List remote threads using the deprecated qL packet.  */
3594
3595 int
3596 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3597 {
3598   if (remote_threadlist_iterator (remote_newthread_step, context,
3599                                   CRAZY_MAX_THREADS) >= 0)
3600     return 1;
3601
3602   return 0;
3603 }
3604
3605 #if defined(HAVE_LIBEXPAT)
3606
3607 static void
3608 start_thread (struct gdb_xml_parser *parser,
3609               const struct gdb_xml_element *element,
3610               void *user_data,
3611               std::vector<gdb_xml_value> &attributes)
3612 {
3613   struct threads_listing_context *data
3614     = (struct threads_listing_context *) user_data;
3615   struct gdb_xml_value *attr;
3616
3617   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3618   ptid_t ptid = read_ptid (id, NULL);
3619
3620   data->items.emplace_back (ptid);
3621   thread_item &item = data->items.back ();
3622
3623   attr = xml_find_attribute (attributes, "core");
3624   if (attr != NULL)
3625     item.core = *(ULONGEST *) attr->value.get ();
3626
3627   attr = xml_find_attribute (attributes, "name");
3628   if (attr != NULL)
3629     item.name = (const char *) attr->value.get ();
3630
3631   attr = xml_find_attribute (attributes, "handle");
3632   if (attr != NULL)
3633     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3634 }
3635
3636 static void
3637 end_thread (struct gdb_xml_parser *parser,
3638             const struct gdb_xml_element *element,
3639             void *user_data, const char *body_text)
3640 {
3641   struct threads_listing_context *data
3642     = (struct threads_listing_context *) user_data;
3643
3644   if (body_text != NULL && *body_text != '\0')
3645     data->items.back ().extra = body_text;
3646 }
3647
3648 const struct gdb_xml_attribute thread_attributes[] = {
3649   { "id", GDB_XML_AF_NONE, NULL, NULL },
3650   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3651   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3652   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3653   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3654 };
3655
3656 const struct gdb_xml_element thread_children[] = {
3657   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3658 };
3659
3660 const struct gdb_xml_element threads_children[] = {
3661   { "thread", thread_attributes, thread_children,
3662     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3663     start_thread, end_thread },
3664   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3665 };
3666
3667 const struct gdb_xml_element threads_elements[] = {
3668   { "threads", NULL, threads_children,
3669     GDB_XML_EF_NONE, NULL, NULL },
3670   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3671 };
3672
3673 #endif
3674
3675 /* List remote threads using qXfer:threads:read.  */
3676
3677 int
3678 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3679 {
3680 #if defined(HAVE_LIBEXPAT)
3681   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3682     {
3683       gdb::optional<gdb::char_vector> xml
3684         = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3685
3686       if (xml && (*xml)[0] != '\0')
3687         {
3688           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3689                                threads_elements, xml->data (), context);
3690         }
3691
3692       return 1;
3693     }
3694 #endif
3695
3696   return 0;
3697 }
3698
3699 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3700
3701 int
3702 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3703 {
3704   struct remote_state *rs = get_remote_state ();
3705
3706   if (rs->use_threadinfo_query)
3707     {
3708       const char *bufp;
3709
3710       putpkt ("qfThreadInfo");
3711       getpkt (&rs->buf, &rs->buf_size, 0);
3712       bufp = rs->buf;
3713       if (bufp[0] != '\0')              /* q packet recognized */
3714         {
3715           while (*bufp++ == 'm')        /* reply contains one or more TID */
3716             {
3717               do
3718                 {
3719                   ptid_t ptid = read_ptid (bufp, &bufp);
3720                   context->items.emplace_back (ptid);
3721                 }
3722               while (*bufp++ == ',');   /* comma-separated list */
3723               putpkt ("qsThreadInfo");
3724               getpkt (&rs->buf, &rs->buf_size, 0);
3725               bufp = rs->buf;
3726             }
3727           return 1;
3728         }
3729       else
3730         {
3731           /* Packet not recognized.  */
3732           rs->use_threadinfo_query = 0;
3733         }
3734     }
3735
3736   return 0;
3737 }
3738
3739 /* Implement the to_update_thread_list function for the remote
3740    targets.  */
3741
3742 void
3743 remote_target::update_thread_list ()
3744 {
3745   struct threads_listing_context context;
3746   int got_list = 0;
3747
3748   /* We have a few different mechanisms to fetch the thread list.  Try
3749      them all, starting with the most preferred one first, falling
3750      back to older methods.  */
3751   if (remote_get_threads_with_qxfer (&context)
3752       || remote_get_threads_with_qthreadinfo (&context)
3753       || remote_get_threads_with_ql (&context))
3754     {
3755       struct thread_info *tp, *tmp;
3756
3757       got_list = 1;
3758
3759       if (context.items.empty ()
3760           && remote_thread_always_alive (inferior_ptid))
3761         {
3762           /* Some targets don't really support threads, but still
3763              reply an (empty) thread list in response to the thread
3764              listing packets, instead of replying "packet not
3765              supported".  Exit early so we don't delete the main
3766              thread.  */
3767           return;
3768         }
3769
3770       /* CONTEXT now holds the current thread list on the remote
3771          target end.  Delete GDB-side threads no longer found on the
3772          target.  */
3773       ALL_THREADS_SAFE (tp, tmp)
3774         {
3775           if (!context.contains_thread (tp->ptid))
3776             {
3777               /* Not found.  */
3778               delete_thread (tp);
3779             }
3780         }
3781
3782       /* Remove any unreported fork child threads from CONTEXT so
3783          that we don't interfere with follow fork, which is where
3784          creation of such threads is handled.  */
3785       remove_new_fork_children (&context);
3786
3787       /* And now add threads we don't know about yet to our list.  */
3788       for (thread_item &item : context.items)
3789         {
3790           if (item.ptid != null_ptid)
3791             {
3792               /* In non-stop mode, we assume new found threads are
3793                  executing until proven otherwise with a stop reply.
3794                  In all-stop, we can only get here if all threads are
3795                  stopped.  */
3796               int executing = target_is_non_stop_p () ? 1 : 0;
3797
3798               remote_notice_new_inferior (item.ptid, executing);
3799
3800               thread_info *tp = find_thread_ptid (item.ptid);
3801               remote_thread_info *info = get_remote_thread_info (tp);
3802               info->core = item.core;
3803               info->extra = std::move (item.extra);
3804               info->name = std::move (item.name);
3805               info->thread_handle = std::move (item.thread_handle);
3806             }
3807         }
3808     }
3809
3810   if (!got_list)
3811     {
3812       /* If no thread listing method is supported, then query whether
3813          each known thread is alive, one by one, with the T packet.
3814          If the target doesn't support threads at all, then this is a
3815          no-op.  See remote_thread_alive.  */
3816       prune_threads ();
3817     }
3818 }
3819
3820 /*
3821  * Collect a descriptive string about the given thread.
3822  * The target may say anything it wants to about the thread
3823  * (typically info about its blocked / runnable state, name, etc.).
3824  * This string will appear in the info threads display.
3825  *
3826  * Optional: targets are not required to implement this function.
3827  */
3828
3829 const char *
3830 remote_target::extra_thread_info (thread_info *tp)
3831 {
3832   struct remote_state *rs = get_remote_state ();
3833   int set;
3834   threadref id;
3835   struct gdb_ext_thread_info threadinfo;
3836
3837   if (rs->remote_desc == 0)             /* paranoia */
3838     internal_error (__FILE__, __LINE__,
3839                     _("remote_threads_extra_info"));
3840
3841   if (tp->ptid == magic_null_ptid
3842       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
3843     /* This is the main thread which was added by GDB.  The remote
3844        server doesn't know about it.  */
3845     return NULL;
3846
3847   std::string &extra = get_remote_thread_info (tp)->extra;
3848
3849   /* If already have cached info, use it.  */
3850   if (!extra.empty ())
3851     return extra.c_str ();
3852
3853   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3854     {
3855       /* If we're using qXfer:threads:read, then the extra info is
3856          included in the XML.  So if we didn't have anything cached,
3857          it's because there's really no extra info.  */
3858       return NULL;
3859     }
3860
3861   if (rs->use_threadextra_query)
3862     {
3863       char *b = rs->buf;
3864       char *endb = rs->buf + get_remote_packet_size ();
3865
3866       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3867       b += strlen (b);
3868       write_ptid (b, endb, tp->ptid);
3869
3870       putpkt (rs->buf);
3871       getpkt (&rs->buf, &rs->buf_size, 0);
3872       if (rs->buf[0] != 0)
3873         {
3874           extra.resize (strlen (rs->buf) / 2);
3875           hex2bin (rs->buf, (gdb_byte *) &extra[0], extra.size ());
3876           return extra.c_str ();
3877         }
3878     }
3879
3880   /* If the above query fails, fall back to the old method.  */
3881   rs->use_threadextra_query = 0;
3882   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3883     | TAG_MOREDISPLAY | TAG_DISPLAY;
3884   int_to_threadref (&id, tp->ptid.lwp ());
3885   if (remote_get_threadinfo (&id, set, &threadinfo))
3886     if (threadinfo.active)
3887       {
3888         if (*threadinfo.shortname)
3889           string_appendf (extra, " Name: %s", threadinfo.shortname);
3890         if (*threadinfo.display)
3891           {
3892             if (!extra.empty ())
3893               extra += ',';
3894             string_appendf (extra, " State: %s", threadinfo.display);
3895           }
3896         if (*threadinfo.more_display)
3897           {
3898             if (!extra.empty ())
3899               extra += ',';
3900             string_appendf (extra, " Priority: %s", threadinfo.more_display);
3901           }
3902         return extra.c_str ();
3903       }
3904   return NULL;
3905 }
3906 \f
3907
3908 bool
3909 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3910                                             struct static_tracepoint_marker *marker)
3911 {
3912   struct remote_state *rs = get_remote_state ();
3913   char *p = rs->buf;
3914
3915   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3916   p += strlen (p);
3917   p += hexnumstr (p, addr);
3918   putpkt (rs->buf);
3919   getpkt (&rs->buf, &rs->buf_size, 0);
3920   p = rs->buf;
3921
3922   if (*p == 'E')
3923     error (_("Remote failure reply: %s"), p);
3924
3925   if (*p++ == 'm')
3926     {
3927       parse_static_tracepoint_marker_definition (p, NULL, marker);
3928       return true;
3929     }
3930
3931   return false;
3932 }
3933
3934 std::vector<static_tracepoint_marker>
3935 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3936 {
3937   struct remote_state *rs = get_remote_state ();
3938   std::vector<static_tracepoint_marker> markers;
3939   const char *p;
3940   static_tracepoint_marker marker;
3941
3942   /* Ask for a first packet of static tracepoint marker
3943      definition.  */
3944   putpkt ("qTfSTM");
3945   getpkt (&rs->buf, &rs->buf_size, 0);
3946   p = rs->buf;
3947   if (*p == 'E')
3948     error (_("Remote failure reply: %s"), p);
3949
3950   while (*p++ == 'm')
3951     {
3952       do
3953         {
3954           parse_static_tracepoint_marker_definition (p, &p, &marker);
3955
3956           if (strid == NULL || marker.str_id == strid)
3957             markers.push_back (std::move (marker));
3958         }
3959       while (*p++ == ',');      /* comma-separated list */
3960       /* Ask for another packet of static tracepoint definition.  */
3961       putpkt ("qTsSTM");
3962       getpkt (&rs->buf, &rs->buf_size, 0);
3963       p = rs->buf;
3964     }
3965
3966   return markers;
3967 }
3968
3969 \f
3970 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3971
3972 ptid_t
3973 remote_target::get_ada_task_ptid (long lwp, long thread)
3974 {
3975   return ptid_t (inferior_ptid.pid (), lwp, 0);
3976 }
3977 \f
3978
3979 /* Restart the remote side; this is an extended protocol operation.  */
3980
3981 void
3982 remote_target::extended_remote_restart ()
3983 {
3984   struct remote_state *rs = get_remote_state ();
3985
3986   /* Send the restart command; for reasons I don't understand the
3987      remote side really expects a number after the "R".  */
3988   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3989   putpkt (rs->buf);
3990
3991   remote_fileio_reset ();
3992 }
3993 \f
3994 /* Clean up connection to a remote debugger.  */
3995
3996 void
3997 remote_target::close ()
3998 {
3999   /* Make sure we leave stdin registered in the event loop.  */
4000   terminal_ours ();
4001
4002   /* We don't have a connection to the remote stub anymore.  Get rid
4003      of all the inferiors and their threads we were controlling.
4004      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4005      will be unable to find the thread corresponding to (pid, 0, 0).  */
4006   inferior_ptid = null_ptid;
4007   discard_all_inferiors ();
4008
4009   trace_reset_local_state ();
4010
4011   delete this;
4012 }
4013
4014 remote_target::~remote_target ()
4015 {
4016   struct remote_state *rs = get_remote_state ();
4017
4018   /* Check for NULL because we may get here with a partially
4019      constructed target/connection.  */
4020   if (rs->remote_desc == nullptr)
4021     return;
4022
4023   serial_close (rs->remote_desc);
4024
4025   /* We are destroying the remote target, so we should discard
4026      everything of this target.  */
4027   discard_pending_stop_replies_in_queue ();
4028
4029   if (rs->remote_async_inferior_event_token)
4030     delete_async_event_handler (&rs->remote_async_inferior_event_token);
4031
4032   remote_notif_state_xfree (rs->notif_state);
4033 }
4034
4035 /* Query the remote side for the text, data and bss offsets.  */
4036
4037 void
4038 remote_target::get_offsets ()
4039 {
4040   struct remote_state *rs = get_remote_state ();
4041   char *buf;
4042   char *ptr;
4043   int lose, num_segments = 0, do_sections, do_segments;
4044   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4045   struct section_offsets *offs;
4046   struct symfile_segment_data *data;
4047
4048   if (symfile_objfile == NULL)
4049     return;
4050
4051   putpkt ("qOffsets");
4052   getpkt (&rs->buf, &rs->buf_size, 0);
4053   buf = rs->buf;
4054
4055   if (buf[0] == '\000')
4056     return;                     /* Return silently.  Stub doesn't support
4057                                    this command.  */
4058   if (buf[0] == 'E')
4059     {
4060       warning (_("Remote failure reply: %s"), buf);
4061       return;
4062     }
4063
4064   /* Pick up each field in turn.  This used to be done with scanf, but
4065      scanf will make trouble if CORE_ADDR size doesn't match
4066      conversion directives correctly.  The following code will work
4067      with any size of CORE_ADDR.  */
4068   text_addr = data_addr = bss_addr = 0;
4069   ptr = buf;
4070   lose = 0;
4071
4072   if (startswith (ptr, "Text="))
4073     {
4074       ptr += 5;
4075       /* Don't use strtol, could lose on big values.  */
4076       while (*ptr && *ptr != ';')
4077         text_addr = (text_addr << 4) + fromhex (*ptr++);
4078
4079       if (startswith (ptr, ";Data="))
4080         {
4081           ptr += 6;
4082           while (*ptr && *ptr != ';')
4083             data_addr = (data_addr << 4) + fromhex (*ptr++);
4084         }
4085       else
4086         lose = 1;
4087
4088       if (!lose && startswith (ptr, ";Bss="))
4089         {
4090           ptr += 5;
4091           while (*ptr && *ptr != ';')
4092             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4093
4094           if (bss_addr != data_addr)
4095             warning (_("Target reported unsupported offsets: %s"), buf);
4096         }
4097       else
4098         lose = 1;
4099     }
4100   else if (startswith (ptr, "TextSeg="))
4101     {
4102       ptr += 8;
4103       /* Don't use strtol, could lose on big values.  */
4104       while (*ptr && *ptr != ';')
4105         text_addr = (text_addr << 4) + fromhex (*ptr++);
4106       num_segments = 1;
4107
4108       if (startswith (ptr, ";DataSeg="))
4109         {
4110           ptr += 9;
4111           while (*ptr && *ptr != ';')
4112             data_addr = (data_addr << 4) + fromhex (*ptr++);
4113           num_segments++;
4114         }
4115     }
4116   else
4117     lose = 1;
4118
4119   if (lose)
4120     error (_("Malformed response to offset query, %s"), buf);
4121   else if (*ptr != '\0')
4122     warning (_("Target reported unsupported offsets: %s"), buf);
4123
4124   offs = ((struct section_offsets *)
4125           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4126   memcpy (offs, symfile_objfile->section_offsets,
4127           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4128
4129   data = get_symfile_segment_data (symfile_objfile->obfd);
4130   do_segments = (data != NULL);
4131   do_sections = num_segments == 0;
4132
4133   if (num_segments > 0)
4134     {
4135       segments[0] = text_addr;
4136       segments[1] = data_addr;
4137     }
4138   /* If we have two segments, we can still try to relocate everything
4139      by assuming that the .text and .data offsets apply to the whole
4140      text and data segments.  Convert the offsets given in the packet
4141      to base addresses for symfile_map_offsets_to_segments.  */
4142   else if (data && data->num_segments == 2)
4143     {
4144       segments[0] = data->segment_bases[0] + text_addr;
4145       segments[1] = data->segment_bases[1] + data_addr;
4146       num_segments = 2;
4147     }
4148   /* If the object file has only one segment, assume that it is text
4149      rather than data; main programs with no writable data are rare,
4150      but programs with no code are useless.  Of course the code might
4151      have ended up in the data segment... to detect that we would need
4152      the permissions here.  */
4153   else if (data && data->num_segments == 1)
4154     {
4155       segments[0] = data->segment_bases[0] + text_addr;
4156       num_segments = 1;
4157     }
4158   /* There's no way to relocate by segment.  */
4159   else
4160     do_segments = 0;
4161
4162   if (do_segments)
4163     {
4164       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4165                                                  offs, num_segments, segments);
4166
4167       if (ret == 0 && !do_sections)
4168         error (_("Can not handle qOffsets TextSeg "
4169                  "response with this symbol file"));
4170
4171       if (ret > 0)
4172         do_sections = 0;
4173     }
4174
4175   if (data)
4176     free_symfile_segment_data (data);
4177
4178   if (do_sections)
4179     {
4180       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4181
4182       /* This is a temporary kludge to force data and bss to use the
4183          same offsets because that's what nlmconv does now.  The real
4184          solution requires changes to the stub and remote.c that I
4185          don't have time to do right now.  */
4186
4187       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4188       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4189     }
4190
4191   objfile_relocate (symfile_objfile, offs);
4192 }
4193
4194 /* Send interrupt_sequence to remote target.  */
4195
4196 void
4197 remote_target::send_interrupt_sequence ()
4198 {
4199   struct remote_state *rs = get_remote_state ();
4200
4201   if (interrupt_sequence_mode == interrupt_sequence_control_c)
4202     remote_serial_write ("\x03", 1);
4203   else if (interrupt_sequence_mode == interrupt_sequence_break)
4204     serial_send_break (rs->remote_desc);
4205   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4206     {
4207       serial_send_break (rs->remote_desc);
4208       remote_serial_write ("g", 1);
4209     }
4210   else
4211     internal_error (__FILE__, __LINE__,
4212                     _("Invalid value for interrupt_sequence_mode: %s."),
4213                     interrupt_sequence_mode);
4214 }
4215
4216
4217 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4218    and extract the PTID.  Returns NULL_PTID if not found.  */
4219
4220 static ptid_t
4221 stop_reply_extract_thread (char *stop_reply)
4222 {
4223   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4224     {
4225       const char *p;
4226
4227       /* Txx r:val ; r:val (...)  */
4228       p = &stop_reply[3];
4229
4230       /* Look for "register" named "thread".  */
4231       while (*p != '\0')
4232         {
4233           const char *p1;
4234
4235           p1 = strchr (p, ':');
4236           if (p1 == NULL)
4237             return null_ptid;
4238
4239           if (strncmp (p, "thread", p1 - p) == 0)
4240             return read_ptid (++p1, &p);
4241
4242           p1 = strchr (p, ';');
4243           if (p1 == NULL)
4244             return null_ptid;
4245           p1++;
4246
4247           p = p1;
4248         }
4249     }
4250
4251   return null_ptid;
4252 }
4253
4254 /* Determine the remote side's current thread.  If we have a stop
4255    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4256    "thread" register we can extract the current thread from.  If not,
4257    ask the remote which is the current thread with qC.  The former
4258    method avoids a roundtrip.  */
4259
4260 ptid_t
4261 remote_target::get_current_thread (char *wait_status)
4262 {
4263   ptid_t ptid = null_ptid;
4264
4265   /* Note we don't use remote_parse_stop_reply as that makes use of
4266      the target architecture, which we haven't yet fully determined at
4267      this point.  */
4268   if (wait_status != NULL)
4269     ptid = stop_reply_extract_thread (wait_status);
4270   if (ptid == null_ptid)
4271     ptid = remote_current_thread (inferior_ptid);
4272
4273   return ptid;
4274 }
4275
4276 /* Query the remote target for which is the current thread/process,
4277    add it to our tables, and update INFERIOR_PTID.  The caller is
4278    responsible for setting the state such that the remote end is ready
4279    to return the current thread.
4280
4281    This function is called after handling the '?' or 'vRun' packets,
4282    whose response is a stop reply from which we can also try
4283    extracting the thread.  If the target doesn't support the explicit
4284    qC query, we infer the current thread from that stop reply, passed
4285    in in WAIT_STATUS, which may be NULL.  */
4286
4287 void
4288 remote_target::add_current_inferior_and_thread (char *wait_status)
4289 {
4290   struct remote_state *rs = get_remote_state ();
4291   int fake_pid_p = 0;
4292
4293   inferior_ptid = null_ptid;
4294
4295   /* Now, if we have thread information, update inferior_ptid.  */
4296   ptid_t curr_ptid = get_current_thread (wait_status);
4297
4298   if (curr_ptid != null_ptid)
4299     {
4300       if (!remote_multi_process_p (rs))
4301         fake_pid_p = 1;
4302     }
4303   else
4304     {
4305       /* Without this, some commands which require an active target
4306          (such as kill) won't work.  This variable serves (at least)
4307          double duty as both the pid of the target process (if it has
4308          such), and as a flag indicating that a target is active.  */
4309       curr_ptid = magic_null_ptid;
4310       fake_pid_p = 1;
4311     }
4312
4313   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4314
4315   /* Add the main thread and switch to it.  Don't try reading
4316      registers yet, since we haven't fetched the target description
4317      yet.  */
4318   thread_info *tp = add_thread_silent (curr_ptid);
4319   switch_to_thread_no_regs (tp);
4320 }
4321
4322 /* Print info about a thread that was found already stopped on
4323    connection.  */
4324
4325 static void
4326 print_one_stopped_thread (struct thread_info *thread)
4327 {
4328   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4329
4330   switch_to_thread (thread);
4331   thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4332   set_current_sal_from_frame (get_current_frame ());
4333
4334   thread->suspend.waitstatus_pending_p = 0;
4335
4336   if (ws->kind == TARGET_WAITKIND_STOPPED)
4337     {
4338       enum gdb_signal sig = ws->value.sig;
4339
4340       if (signal_print_state (sig))
4341         gdb::observers::signal_received.notify (sig);
4342     }
4343   gdb::observers::normal_stop.notify (NULL, 1);
4344 }
4345
4346 /* Process all initial stop replies the remote side sent in response
4347    to the ? packet.  These indicate threads that were already stopped
4348    on initial connection.  We mark these threads as stopped and print
4349    their current frame before giving the user the prompt.  */
4350
4351 void
4352 remote_target::process_initial_stop_replies (int from_tty)
4353 {
4354   int pending_stop_replies = stop_reply_queue_length ();
4355   struct inferior *inf;
4356   struct thread_info *thread;
4357   struct thread_info *selected = NULL;
4358   struct thread_info *lowest_stopped = NULL;
4359   struct thread_info *first = NULL;
4360
4361   /* Consume the initial pending events.  */
4362   while (pending_stop_replies-- > 0)
4363     {
4364       ptid_t waiton_ptid = minus_one_ptid;
4365       ptid_t event_ptid;
4366       struct target_waitstatus ws;
4367       int ignore_event = 0;
4368       struct thread_info *thread;
4369
4370       memset (&ws, 0, sizeof (ws));
4371       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4372       if (remote_debug)
4373         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4374
4375       switch (ws.kind)
4376         {
4377         case TARGET_WAITKIND_IGNORE:
4378         case TARGET_WAITKIND_NO_RESUMED:
4379         case TARGET_WAITKIND_SIGNALLED:
4380         case TARGET_WAITKIND_EXITED:
4381           /* We shouldn't see these, but if we do, just ignore.  */
4382           if (remote_debug)
4383             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4384           ignore_event = 1;
4385           break;
4386
4387         case TARGET_WAITKIND_EXECD:
4388           xfree (ws.value.execd_pathname);
4389           break;
4390         default:
4391           break;
4392         }
4393
4394       if (ignore_event)
4395         continue;
4396
4397       thread = find_thread_ptid (event_ptid);
4398
4399       if (ws.kind == TARGET_WAITKIND_STOPPED)
4400         {
4401           enum gdb_signal sig = ws.value.sig;
4402
4403           /* Stubs traditionally report SIGTRAP as initial signal,
4404              instead of signal 0.  Suppress it.  */
4405           if (sig == GDB_SIGNAL_TRAP)
4406             sig = GDB_SIGNAL_0;
4407           thread->suspend.stop_signal = sig;
4408           ws.value.sig = sig;
4409         }
4410
4411       thread->suspend.waitstatus = ws;
4412
4413       if (ws.kind != TARGET_WAITKIND_STOPPED
4414           || ws.value.sig != GDB_SIGNAL_0)
4415         thread->suspend.waitstatus_pending_p = 1;
4416
4417       set_executing (event_ptid, 0);
4418       set_running (event_ptid, 0);
4419       get_remote_thread_info (thread)->vcont_resumed = 0;
4420     }
4421
4422   /* "Notice" the new inferiors before anything related to
4423      registers/memory.  */
4424   ALL_INFERIORS (inf)
4425     {
4426       if (inf->pid == 0)
4427         continue;
4428
4429       inf->needs_setup = 1;
4430
4431       if (non_stop)
4432         {
4433           thread = any_live_thread_of_inferior (inf);
4434           notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4435                                from_tty);
4436         }
4437     }
4438
4439   /* If all-stop on top of non-stop, pause all threads.  Note this
4440      records the threads' stop pc, so must be done after "noticing"
4441      the inferiors.  */
4442   if (!non_stop)
4443     {
4444       stop_all_threads ();
4445
4446       /* If all threads of an inferior were already stopped, we
4447          haven't setup the inferior yet.  */
4448       ALL_INFERIORS (inf)
4449         {
4450           if (inf->pid == 0)
4451             continue;
4452
4453           if (inf->needs_setup)
4454             {
4455               thread = any_live_thread_of_inferior (inf);
4456               switch_to_thread_no_regs (thread);
4457               setup_inferior (0);
4458             }
4459         }
4460     }
4461
4462   /* Now go over all threads that are stopped, and print their current
4463      frame.  If all-stop, then if there's a signalled thread, pick
4464      that as current.  */
4465   ALL_NON_EXITED_THREADS (thread)
4466     {
4467       if (first == NULL)
4468         first = thread;
4469
4470       if (!non_stop)
4471         thread->set_running (false);
4472       else if (thread->state != THREAD_STOPPED)
4473         continue;
4474
4475       if (selected == NULL
4476           && thread->suspend.waitstatus_pending_p)
4477         selected = thread;
4478
4479       if (lowest_stopped == NULL
4480           || thread->inf->num < lowest_stopped->inf->num
4481           || thread->per_inf_num < lowest_stopped->per_inf_num)
4482         lowest_stopped = thread;
4483
4484       if (non_stop)
4485         print_one_stopped_thread (thread);
4486     }
4487
4488   /* In all-stop, we only print the status of one thread, and leave
4489      others with their status pending.  */
4490   if (!non_stop)
4491     {
4492       thread = selected;
4493       if (thread == NULL)
4494         thread = lowest_stopped;
4495       if (thread == NULL)
4496         thread = first;
4497
4498       print_one_stopped_thread (thread);
4499     }
4500
4501   /* For "info program".  */
4502   thread = inferior_thread ();
4503   if (thread->state == THREAD_STOPPED)
4504     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4505 }
4506
4507 /* Start the remote connection and sync state.  */
4508
4509 void
4510 remote_target::start_remote (int from_tty, int extended_p)
4511 {
4512   struct remote_state *rs = get_remote_state ();
4513   struct packet_config *noack_config;
4514   char *wait_status = NULL;
4515
4516   /* Signal other parts that we're going through the initial setup,
4517      and so things may not be stable yet.  E.g., we don't try to
4518      install tracepoints until we've relocated symbols.  Also, a
4519      Ctrl-C before we're connected and synced up can't interrupt the
4520      target.  Instead, it offers to drop the (potentially wedged)
4521      connection.  */
4522   rs->starting_up = 1;
4523
4524   QUIT;
4525
4526   if (interrupt_on_connect)
4527     send_interrupt_sequence ();
4528
4529   /* Ack any packet which the remote side has already sent.  */
4530   remote_serial_write ("+", 1);
4531
4532   /* The first packet we send to the target is the optional "supported
4533      packets" request.  If the target can answer this, it will tell us
4534      which later probes to skip.  */
4535   remote_query_supported ();
4536
4537   /* If the stub wants to get a QAllow, compose one and send it.  */
4538   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4539     set_permissions ();
4540
4541   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4542      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4543      as a reply to known packet.  For packet "vFile:setfs:" it is an
4544      invalid reply and GDB would return error in
4545      remote_hostio_set_filesystem, making remote files access impossible.
4546      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4547      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4548   {
4549     const char v_mustreplyempty[] = "vMustReplyEmpty";
4550
4551     putpkt (v_mustreplyempty);
4552     getpkt (&rs->buf, &rs->buf_size, 0);
4553     if (strcmp (rs->buf, "OK") == 0)
4554       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4555     else if (strcmp (rs->buf, "") != 0)
4556       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4557              rs->buf);
4558   }
4559
4560   /* Next, we possibly activate noack mode.
4561
4562      If the QStartNoAckMode packet configuration is set to AUTO,
4563      enable noack mode if the stub reported a wish for it with
4564      qSupported.
4565
4566      If set to TRUE, then enable noack mode even if the stub didn't
4567      report it in qSupported.  If the stub doesn't reply OK, the
4568      session ends with an error.
4569
4570      If FALSE, then don't activate noack mode, regardless of what the
4571      stub claimed should be the default with qSupported.  */
4572
4573   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4574   if (packet_config_support (noack_config) != PACKET_DISABLE)
4575     {
4576       putpkt ("QStartNoAckMode");
4577       getpkt (&rs->buf, &rs->buf_size, 0);
4578       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4579         rs->noack_mode = 1;
4580     }
4581
4582   if (extended_p)
4583     {
4584       /* Tell the remote that we are using the extended protocol.  */
4585       putpkt ("!");
4586       getpkt (&rs->buf, &rs->buf_size, 0);
4587     }
4588
4589   /* Let the target know which signals it is allowed to pass down to
4590      the program.  */
4591   update_signals_program_target ();
4592
4593   /* Next, if the target can specify a description, read it.  We do
4594      this before anything involving memory or registers.  */
4595   target_find_description ();
4596
4597   /* Next, now that we know something about the target, update the
4598      address spaces in the program spaces.  */
4599   update_address_spaces ();
4600
4601   /* On OSs where the list of libraries is global to all
4602      processes, we fetch them early.  */
4603   if (gdbarch_has_global_solist (target_gdbarch ()))
4604     solib_add (NULL, from_tty, auto_solib_add);
4605
4606   if (target_is_non_stop_p ())
4607     {
4608       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4609         error (_("Non-stop mode requested, but remote "
4610                  "does not support non-stop"));
4611
4612       putpkt ("QNonStop:1");
4613       getpkt (&rs->buf, &rs->buf_size, 0);
4614
4615       if (strcmp (rs->buf, "OK") != 0)
4616         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4617
4618       /* Find about threads and processes the stub is already
4619          controlling.  We default to adding them in the running state.
4620          The '?' query below will then tell us about which threads are
4621          stopped.  */
4622       this->update_thread_list ();
4623     }
4624   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4625     {
4626       /* Don't assume that the stub can operate in all-stop mode.
4627          Request it explicitly.  */
4628       putpkt ("QNonStop:0");
4629       getpkt (&rs->buf, &rs->buf_size, 0);
4630
4631       if (strcmp (rs->buf, "OK") != 0)
4632         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4633     }
4634
4635   /* Upload TSVs regardless of whether the target is running or not.  The
4636      remote stub, such as GDBserver, may have some predefined or builtin
4637      TSVs, even if the target is not running.  */
4638   if (get_trace_status (current_trace_status ()) != -1)
4639     {
4640       struct uploaded_tsv *uploaded_tsvs = NULL;
4641
4642       upload_trace_state_variables (&uploaded_tsvs);
4643       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4644     }
4645
4646   /* Check whether the target is running now.  */
4647   putpkt ("?");
4648   getpkt (&rs->buf, &rs->buf_size, 0);
4649
4650   if (!target_is_non_stop_p ())
4651     {
4652       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4653         {
4654           if (!extended_p)
4655             error (_("The target is not running (try extended-remote?)"));
4656
4657           /* We're connected, but not running.  Drop out before we
4658              call start_remote.  */
4659           rs->starting_up = 0;
4660           return;
4661         }
4662       else
4663         {
4664           /* Save the reply for later.  */
4665           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4666           strcpy (wait_status, rs->buf);
4667         }
4668
4669       /* Fetch thread list.  */
4670       target_update_thread_list ();
4671
4672       /* Let the stub know that we want it to return the thread.  */
4673       set_continue_thread (minus_one_ptid);
4674
4675       if (thread_count () == 0)
4676         {
4677           /* Target has no concept of threads at all.  GDB treats
4678              non-threaded target as single-threaded; add a main
4679              thread.  */
4680           add_current_inferior_and_thread (wait_status);
4681         }
4682       else
4683         {
4684           /* We have thread information; select the thread the target
4685              says should be current.  If we're reconnecting to a
4686              multi-threaded program, this will ideally be the thread
4687              that last reported an event before GDB disconnected.  */
4688           inferior_ptid = get_current_thread (wait_status);
4689           if (inferior_ptid == null_ptid)
4690             {
4691               /* Odd... The target was able to list threads, but not
4692                  tell us which thread was current (no "thread"
4693                  register in T stop reply?).  Just pick the first
4694                  thread in the thread list then.  */
4695               
4696               if (remote_debug)
4697                 fprintf_unfiltered (gdb_stdlog,
4698                                     "warning: couldn't determine remote "
4699                                     "current thread; picking first in list.\n");
4700
4701               inferior_ptid = thread_list->ptid;
4702             }
4703         }
4704
4705       /* init_wait_for_inferior should be called before get_offsets in order
4706          to manage `inserted' flag in bp loc in a correct state.
4707          breakpoint_init_inferior, called from init_wait_for_inferior, set
4708          `inserted' flag to 0, while before breakpoint_re_set, called from
4709          start_remote, set `inserted' flag to 1.  In the initialization of
4710          inferior, breakpoint_init_inferior should be called first, and then
4711          breakpoint_re_set can be called.  If this order is broken, state of
4712          `inserted' flag is wrong, and cause some problems on breakpoint
4713          manipulation.  */
4714       init_wait_for_inferior ();
4715
4716       get_offsets ();           /* Get text, data & bss offsets.  */
4717
4718       /* If we could not find a description using qXfer, and we know
4719          how to do it some other way, try again.  This is not
4720          supported for non-stop; it could be, but it is tricky if
4721          there are no stopped threads when we connect.  */
4722       if (remote_read_description_p (this)
4723           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4724         {
4725           target_clear_description ();
4726           target_find_description ();
4727         }
4728
4729       /* Use the previously fetched status.  */
4730       gdb_assert (wait_status != NULL);
4731       strcpy (rs->buf, wait_status);
4732       rs->cached_wait_status = 1;
4733
4734       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4735     }
4736   else
4737     {
4738       /* Clear WFI global state.  Do this before finding about new
4739          threads and inferiors, and setting the current inferior.
4740          Otherwise we would clear the proceed status of the current
4741          inferior when we want its stop_soon state to be preserved
4742          (see notice_new_inferior).  */
4743       init_wait_for_inferior ();
4744
4745       /* In non-stop, we will either get an "OK", meaning that there
4746          are no stopped threads at this time; or, a regular stop
4747          reply.  In the latter case, there may be more than one thread
4748          stopped --- we pull them all out using the vStopped
4749          mechanism.  */
4750       if (strcmp (rs->buf, "OK") != 0)
4751         {
4752           struct notif_client *notif = &notif_client_stop;
4753
4754           /* remote_notif_get_pending_replies acks this one, and gets
4755              the rest out.  */
4756           rs->notif_state->pending_event[notif_client_stop.id]
4757             = remote_notif_parse (this, notif, rs->buf);
4758           remote_notif_get_pending_events (notif);
4759         }
4760
4761       if (thread_count () == 0)
4762         {
4763           if (!extended_p)
4764             error (_("The target is not running (try extended-remote?)"));
4765
4766           /* We're connected, but not running.  Drop out before we
4767              call start_remote.  */
4768           rs->starting_up = 0;
4769           return;
4770         }
4771
4772       /* In non-stop mode, any cached wait status will be stored in
4773          the stop reply queue.  */
4774       gdb_assert (wait_status == NULL);
4775
4776       /* Report all signals during attach/startup.  */
4777       pass_signals (0, NULL);
4778
4779       /* If there are already stopped threads, mark them stopped and
4780          report their stops before giving the prompt to the user.  */
4781       process_initial_stop_replies (from_tty);
4782
4783       if (target_can_async_p ())
4784         target_async (1);
4785     }
4786
4787   /* If we connected to a live target, do some additional setup.  */
4788   if (target_has_execution)
4789     {
4790       if (symfile_objfile)      /* No use without a symbol-file.  */
4791         remote_check_symbols ();
4792     }
4793
4794   /* Possibly the target has been engaged in a trace run started
4795      previously; find out where things are at.  */
4796   if (get_trace_status (current_trace_status ()) != -1)
4797     {
4798       struct uploaded_tp *uploaded_tps = NULL;
4799
4800       if (current_trace_status ()->running)
4801         printf_filtered (_("Trace is already running on the target.\n"));
4802
4803       upload_tracepoints (&uploaded_tps);
4804
4805       merge_uploaded_tracepoints (&uploaded_tps);
4806     }
4807
4808   /* Possibly the target has been engaged in a btrace record started
4809      previously; find out where things are at.  */
4810   remote_btrace_maybe_reopen ();
4811
4812   /* The thread and inferior lists are now synchronized with the
4813      target, our symbols have been relocated, and we're merged the
4814      target's tracepoints with ours.  We're done with basic start
4815      up.  */
4816   rs->starting_up = 0;
4817
4818   /* Maybe breakpoints are global and need to be inserted now.  */
4819   if (breakpoints_should_be_inserted_now ())
4820     insert_breakpoints ();
4821 }
4822
4823 /* Open a connection to a remote debugger.
4824    NAME is the filename used for communication.  */
4825
4826 void
4827 remote_target::open (const char *name, int from_tty)
4828 {
4829   open_1 (name, from_tty, 0);
4830 }
4831
4832 /* Open a connection to a remote debugger using the extended
4833    remote gdb protocol.  NAME is the filename used for communication.  */
4834
4835 void
4836 extended_remote_target::open (const char *name, int from_tty)
4837 {
4838   open_1 (name, from_tty, 1 /*extended_p */);
4839 }
4840
4841 /* Reset all packets back to "unknown support".  Called when opening a
4842    new connection to a remote target.  */
4843
4844 static void
4845 reset_all_packet_configs_support (void)
4846 {
4847   int i;
4848
4849   for (i = 0; i < PACKET_MAX; i++)
4850     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4851 }
4852
4853 /* Initialize all packet configs.  */
4854
4855 static void
4856 init_all_packet_configs (void)
4857 {
4858   int i;
4859
4860   for (i = 0; i < PACKET_MAX; i++)
4861     {
4862       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4863       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4864     }
4865 }
4866
4867 /* Symbol look-up.  */
4868
4869 void
4870 remote_target::remote_check_symbols ()
4871 {
4872   char *msg, *reply, *tmp;
4873   int end;
4874   long reply_size;
4875   struct cleanup *old_chain;
4876
4877   /* The remote side has no concept of inferiors that aren't running
4878      yet, it only knows about running processes.  If we're connected
4879      but our current inferior is not running, we should not invite the
4880      remote target to request symbol lookups related to its
4881      (unrelated) current process.  */
4882   if (!target_has_execution)
4883     return;
4884
4885   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4886     return;
4887
4888   /* Make sure the remote is pointing at the right process.  Note
4889      there's no way to select "no process".  */
4890   set_general_process ();
4891
4892   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4893      because we need both at the same time.  */
4894   msg = (char *) xmalloc (get_remote_packet_size ());
4895   old_chain = make_cleanup (xfree, msg);
4896   reply = (char *) xmalloc (get_remote_packet_size ());
4897   make_cleanup (free_current_contents, &reply);
4898   reply_size = get_remote_packet_size ();
4899
4900   /* Invite target to request symbol lookups.  */
4901
4902   putpkt ("qSymbol::");
4903   getpkt (&reply, &reply_size, 0);
4904   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4905
4906   while (startswith (reply, "qSymbol:"))
4907     {
4908       struct bound_minimal_symbol sym;
4909
4910       tmp = &reply[8];
4911       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4912       msg[end] = '\0';
4913       sym = lookup_minimal_symbol (msg, NULL, NULL);
4914       if (sym.minsym == NULL)
4915         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4916       else
4917         {
4918           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4919           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4920
4921           /* If this is a function address, return the start of code
4922              instead of any data function descriptor.  */
4923           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4924                                                          sym_addr,
4925                                                          current_top_target ());
4926
4927           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4928                      phex_nz (sym_addr, addr_size), &reply[8]);
4929         }
4930   
4931       putpkt (msg);
4932       getpkt (&reply, &reply_size, 0);
4933     }
4934
4935   do_cleanups (old_chain);
4936 }
4937
4938 static struct serial *
4939 remote_serial_open (const char *name)
4940 {
4941   static int udp_warning = 0;
4942
4943   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4944      of in ser-tcp.c, because it is the remote protocol assuming that the
4945      serial connection is reliable and not the serial connection promising
4946      to be.  */
4947   if (!udp_warning && startswith (name, "udp:"))
4948     {
4949       warning (_("The remote protocol may be unreliable over UDP.\n"
4950                  "Some events may be lost, rendering further debugging "
4951                  "impossible."));
4952       udp_warning = 1;
4953     }
4954
4955   return serial_open (name);
4956 }
4957
4958 /* Inform the target of our permission settings.  The permission flags
4959    work without this, but if the target knows the settings, it can do
4960    a couple things.  First, it can add its own check, to catch cases
4961    that somehow manage to get by the permissions checks in target
4962    methods.  Second, if the target is wired to disallow particular
4963    settings (for instance, a system in the field that is not set up to
4964    be able to stop at a breakpoint), it can object to any unavailable
4965    permissions.  */
4966
4967 void
4968 remote_target::set_permissions ()
4969 {
4970   struct remote_state *rs = get_remote_state ();
4971
4972   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4973              "WriteReg:%x;WriteMem:%x;"
4974              "InsertBreak:%x;InsertTrace:%x;"
4975              "InsertFastTrace:%x;Stop:%x",
4976              may_write_registers, may_write_memory,
4977              may_insert_breakpoints, may_insert_tracepoints,
4978              may_insert_fast_tracepoints, may_stop);
4979   putpkt (rs->buf);
4980   getpkt (&rs->buf, &rs->buf_size, 0);
4981
4982   /* If the target didn't like the packet, warn the user.  Do not try
4983      to undo the user's settings, that would just be maddening.  */
4984   if (strcmp (rs->buf, "OK") != 0)
4985     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4986 }
4987
4988 /* This type describes each known response to the qSupported
4989    packet.  */
4990 struct protocol_feature
4991 {
4992   /* The name of this protocol feature.  */
4993   const char *name;
4994
4995   /* The default for this protocol feature.  */
4996   enum packet_support default_support;
4997
4998   /* The function to call when this feature is reported, or after
4999      qSupported processing if the feature is not supported.
5000      The first argument points to this structure.  The second
5001      argument indicates whether the packet requested support be
5002      enabled, disabled, or probed (or the default, if this function
5003      is being called at the end of processing and this feature was
5004      not reported).  The third argument may be NULL; if not NULL, it
5005      is a NUL-terminated string taken from the packet following
5006      this feature's name and an equals sign.  */
5007   void (*func) (remote_target *remote, const struct protocol_feature *,
5008                 enum packet_support, const char *);
5009
5010   /* The corresponding packet for this feature.  Only used if
5011      FUNC is remote_supported_packet.  */
5012   int packet;
5013 };
5014
5015 static void
5016 remote_supported_packet (remote_target *remote,
5017                          const struct protocol_feature *feature,
5018                          enum packet_support support,
5019                          const char *argument)
5020 {
5021   if (argument)
5022     {
5023       warning (_("Remote qSupported response supplied an unexpected value for"
5024                  " \"%s\"."), feature->name);
5025       return;
5026     }
5027
5028   remote_protocol_packets[feature->packet].support = support;
5029 }
5030
5031 void
5032 remote_target::remote_packet_size (const protocol_feature *feature,
5033                                    enum packet_support support, const char *value)
5034 {
5035   struct remote_state *rs = get_remote_state ();
5036
5037   int packet_size;
5038   char *value_end;
5039
5040   if (support != PACKET_ENABLE)
5041     return;
5042
5043   if (value == NULL || *value == '\0')
5044     {
5045       warning (_("Remote target reported \"%s\" without a size."),
5046                feature->name);
5047       return;
5048     }
5049
5050   errno = 0;
5051   packet_size = strtol (value, &value_end, 16);
5052   if (errno != 0 || *value_end != '\0' || packet_size < 0)
5053     {
5054       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5055                feature->name, value);
5056       return;
5057     }
5058
5059   /* Record the new maximum packet size.  */
5060   rs->explicit_packet_size = packet_size;
5061 }
5062
5063 void
5064 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5065                     enum packet_support support, const char *value)
5066 {
5067   remote->remote_packet_size (feature, support, value);
5068 }
5069
5070 static const struct protocol_feature remote_protocol_features[] = {
5071   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5072   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5073     PACKET_qXfer_auxv },
5074   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5075     PACKET_qXfer_exec_file },
5076   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5077     PACKET_qXfer_features },
5078   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5079     PACKET_qXfer_libraries },
5080   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5081     PACKET_qXfer_libraries_svr4 },
5082   { "augmented-libraries-svr4-read", PACKET_DISABLE,
5083     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5084   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5085     PACKET_qXfer_memory_map },
5086   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5087     PACKET_qXfer_spu_read },
5088   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5089     PACKET_qXfer_spu_write },
5090   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5091     PACKET_qXfer_osdata },
5092   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5093     PACKET_qXfer_threads },
5094   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5095     PACKET_qXfer_traceframe_info },
5096   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5097     PACKET_QPassSignals },
5098   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5099     PACKET_QCatchSyscalls },
5100   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5101     PACKET_QProgramSignals },
5102   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5103     PACKET_QSetWorkingDir },
5104   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5105     PACKET_QStartupWithShell },
5106   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5107     PACKET_QEnvironmentHexEncoded },
5108   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5109     PACKET_QEnvironmentReset },
5110   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5111     PACKET_QEnvironmentUnset },
5112   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5113     PACKET_QStartNoAckMode },
5114   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5115     PACKET_multiprocess_feature },
5116   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5117   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5118     PACKET_qXfer_siginfo_read },
5119   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5120     PACKET_qXfer_siginfo_write },
5121   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5122     PACKET_ConditionalTracepoints },
5123   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5124     PACKET_ConditionalBreakpoints },
5125   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5126     PACKET_BreakpointCommands },
5127   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5128     PACKET_FastTracepoints },
5129   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5130     PACKET_StaticTracepoints },
5131   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5132    PACKET_InstallInTrace},
5133   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5134     PACKET_DisconnectedTracing_feature },
5135   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5136     PACKET_bc },
5137   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5138     PACKET_bs },
5139   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5140     PACKET_TracepointSource },
5141   { "QAllow", PACKET_DISABLE, remote_supported_packet,
5142     PACKET_QAllow },
5143   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5144     PACKET_EnableDisableTracepoints_feature },
5145   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5146     PACKET_qXfer_fdpic },
5147   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5148     PACKET_qXfer_uib },
5149   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5150     PACKET_QDisableRandomization },
5151   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5152   { "QTBuffer:size", PACKET_DISABLE,
5153     remote_supported_packet, PACKET_QTBuffer_size},
5154   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5155   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5156   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5157   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5158   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5159     PACKET_qXfer_btrace },
5160   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5161     PACKET_qXfer_btrace_conf },
5162   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5163     PACKET_Qbtrace_conf_bts_size },
5164   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5165   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5166   { "fork-events", PACKET_DISABLE, remote_supported_packet,
5167     PACKET_fork_event_feature },
5168   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5169     PACKET_vfork_event_feature },
5170   { "exec-events", PACKET_DISABLE, remote_supported_packet,
5171     PACKET_exec_event_feature },
5172   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5173     PACKET_Qbtrace_conf_pt_size },
5174   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5175   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5176   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5177 };
5178
5179 static char *remote_support_xml;
5180
5181 /* Register string appended to "xmlRegisters=" in qSupported query.  */
5182
5183 void
5184 register_remote_support_xml (const char *xml)
5185 {
5186 #if defined(HAVE_LIBEXPAT)
5187   if (remote_support_xml == NULL)
5188     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5189   else
5190     {
5191       char *copy = xstrdup (remote_support_xml + 13);
5192       char *p = strtok (copy, ",");
5193
5194       do
5195         {
5196           if (strcmp (p, xml) == 0)
5197             {
5198               /* already there */
5199               xfree (copy);
5200               return;
5201             }
5202         }
5203       while ((p = strtok (NULL, ",")) != NULL);
5204       xfree (copy);
5205
5206       remote_support_xml = reconcat (remote_support_xml,
5207                                      remote_support_xml, ",", xml,
5208                                      (char *) NULL);
5209     }
5210 #endif
5211 }
5212
5213 static void
5214 remote_query_supported_append (std::string *msg, const char *append)
5215 {
5216   if (!msg->empty ())
5217     msg->append (";");
5218   msg->append (append);
5219 }
5220
5221 void
5222 remote_target::remote_query_supported ()
5223 {
5224   struct remote_state *rs = get_remote_state ();
5225   char *next;
5226   int i;
5227   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5228
5229   /* The packet support flags are handled differently for this packet
5230      than for most others.  We treat an error, a disabled packet, and
5231      an empty response identically: any features which must be reported
5232      to be used will be automatically disabled.  An empty buffer
5233      accomplishes this, since that is also the representation for a list
5234      containing no features.  */
5235
5236   rs->buf[0] = 0;
5237   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5238     {
5239       std::string q;
5240
5241       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5242         remote_query_supported_append (&q, "multiprocess+");
5243
5244       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5245         remote_query_supported_append (&q, "swbreak+");
5246       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5247         remote_query_supported_append (&q, "hwbreak+");
5248
5249       remote_query_supported_append (&q, "qRelocInsn+");
5250
5251       if (packet_set_cmd_state (PACKET_fork_event_feature)
5252           != AUTO_BOOLEAN_FALSE)
5253         remote_query_supported_append (&q, "fork-events+");
5254       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5255           != AUTO_BOOLEAN_FALSE)
5256         remote_query_supported_append (&q, "vfork-events+");
5257       if (packet_set_cmd_state (PACKET_exec_event_feature)
5258           != AUTO_BOOLEAN_FALSE)
5259         remote_query_supported_append (&q, "exec-events+");
5260
5261       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5262         remote_query_supported_append (&q, "vContSupported+");
5263
5264       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5265         remote_query_supported_append (&q, "QThreadEvents+");
5266
5267       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5268         remote_query_supported_append (&q, "no-resumed+");
5269
5270       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5271          the qSupported:xmlRegisters=i386 handling.  */
5272       if (remote_support_xml != NULL
5273           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5274         remote_query_supported_append (&q, remote_support_xml);
5275
5276       q = "qSupported:" + q;
5277       putpkt (q.c_str ());
5278
5279       getpkt (&rs->buf, &rs->buf_size, 0);
5280
5281       /* If an error occured, warn, but do not return - just reset the
5282          buffer to empty and go on to disable features.  */
5283       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5284           == PACKET_ERROR)
5285         {
5286           warning (_("Remote failure reply: %s"), rs->buf);
5287           rs->buf[0] = 0;
5288         }
5289     }
5290
5291   memset (seen, 0, sizeof (seen));
5292
5293   next = rs->buf;
5294   while (*next)
5295     {
5296       enum packet_support is_supported;
5297       char *p, *end, *name_end, *value;
5298
5299       /* First separate out this item from the rest of the packet.  If
5300          there's another item after this, we overwrite the separator
5301          (terminated strings are much easier to work with).  */
5302       p = next;
5303       end = strchr (p, ';');
5304       if (end == NULL)
5305         {
5306           end = p + strlen (p);
5307           next = end;
5308         }
5309       else
5310         {
5311           *end = '\0';
5312           next = end + 1;
5313
5314           if (end == p)
5315             {
5316               warning (_("empty item in \"qSupported\" response"));
5317               continue;
5318             }
5319         }
5320
5321       name_end = strchr (p, '=');
5322       if (name_end)
5323         {
5324           /* This is a name=value entry.  */
5325           is_supported = PACKET_ENABLE;
5326           value = name_end + 1;
5327           *name_end = '\0';
5328         }
5329       else
5330         {
5331           value = NULL;
5332           switch (end[-1])
5333             {
5334             case '+':
5335               is_supported = PACKET_ENABLE;
5336               break;
5337
5338             case '-':
5339               is_supported = PACKET_DISABLE;
5340               break;
5341
5342             case '?':
5343               is_supported = PACKET_SUPPORT_UNKNOWN;
5344               break;
5345
5346             default:
5347               warning (_("unrecognized item \"%s\" "
5348                          "in \"qSupported\" response"), p);
5349               continue;
5350             }
5351           end[-1] = '\0';
5352         }
5353
5354       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5355         if (strcmp (remote_protocol_features[i].name, p) == 0)
5356           {
5357             const struct protocol_feature *feature;
5358
5359             seen[i] = 1;
5360             feature = &remote_protocol_features[i];
5361             feature->func (this, feature, is_supported, value);
5362             break;
5363           }
5364     }
5365
5366   /* If we increased the packet size, make sure to increase the global
5367      buffer size also.  We delay this until after parsing the entire
5368      qSupported packet, because this is the same buffer we were
5369      parsing.  */
5370   if (rs->buf_size < rs->explicit_packet_size)
5371     {
5372       rs->buf_size = rs->explicit_packet_size;
5373       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5374     }
5375
5376   /* Handle the defaults for unmentioned features.  */
5377   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5378     if (!seen[i])
5379       {
5380         const struct protocol_feature *feature;
5381
5382         feature = &remote_protocol_features[i];
5383         feature->func (this, feature, feature->default_support, NULL);
5384       }
5385 }
5386
5387 /* Serial QUIT handler for the remote serial descriptor.
5388
5389    Defers handling a Ctrl-C until we're done with the current
5390    command/response packet sequence, unless:
5391
5392    - We're setting up the connection.  Don't send a remote interrupt
5393      request, as we're not fully synced yet.  Quit immediately
5394      instead.
5395
5396    - The target has been resumed in the foreground
5397      (target_terminal::is_ours is false) with a synchronous resume
5398      packet, and we're blocked waiting for the stop reply, thus a
5399      Ctrl-C should be immediately sent to the target.
5400
5401    - We get a second Ctrl-C while still within the same serial read or
5402      write.  In that case the serial is seemingly wedged --- offer to
5403      quit/disconnect.
5404
5405    - We see a second Ctrl-C without target response, after having
5406      previously interrupted the target.  In that case the target/stub
5407      is probably wedged --- offer to quit/disconnect.
5408 */
5409
5410 void
5411 remote_target::remote_serial_quit_handler ()
5412 {
5413   struct remote_state *rs = get_remote_state ();
5414
5415   if (check_quit_flag ())
5416     {
5417       /* If we're starting up, we're not fully synced yet.  Quit
5418          immediately.  */
5419       if (rs->starting_up)
5420         quit ();
5421       else if (rs->got_ctrlc_during_io)
5422         {
5423           if (query (_("The target is not responding to GDB commands.\n"
5424                        "Stop debugging it? ")))
5425             remote_unpush_and_throw ();
5426         }
5427       /* If ^C has already been sent once, offer to disconnect.  */
5428       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5429         interrupt_query ();
5430       /* All-stop protocol, and blocked waiting for stop reply.  Send
5431          an interrupt request.  */
5432       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5433         target_interrupt ();
5434       else
5435         rs->got_ctrlc_during_io = 1;
5436     }
5437 }
5438
5439 /* The remote_target that is current while the quit handler is
5440    overridden with remote_serial_quit_handler.  */
5441 static remote_target *curr_quit_handler_target;
5442
5443 static void
5444 remote_serial_quit_handler ()
5445 {
5446   curr_quit_handler_target->remote_serial_quit_handler ();
5447 }
5448
5449 /* Remove any of the remote.c targets from target stack.  Upper targets depend
5450    on it so remove them first.  */
5451
5452 static void
5453 remote_unpush_target (void)
5454 {
5455   pop_all_targets_at_and_above (process_stratum);
5456 }
5457
5458 static void
5459 remote_unpush_and_throw (void)
5460 {
5461   remote_unpush_target ();
5462   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5463 }
5464
5465 void
5466 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5467 {
5468   remote_target *curr_remote = get_current_remote_target ();
5469
5470   if (name == 0)
5471     error (_("To open a remote debug connection, you need to specify what\n"
5472            "serial device is attached to the remote system\n"
5473            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5474
5475   /* If we're connected to a running target, target_preopen will kill it.
5476      Ask this question first, before target_preopen has a chance to kill
5477      anything.  */
5478   if (curr_remote != NULL && !have_inferiors ())
5479     {
5480       if (from_tty
5481           && !query (_("Already connected to a remote target.  Disconnect? ")))
5482         error (_("Still connected."));
5483     }
5484
5485   /* Here the possibly existing remote target gets unpushed.  */
5486   target_preopen (from_tty);
5487
5488   remote_fileio_reset ();
5489   reopen_exec_file ();
5490   reread_symbols ();
5491
5492   remote_target *remote
5493     = (extended_p ? new extended_remote_target () : new remote_target ());
5494   target_ops_up target_holder (remote);
5495
5496   remote_state *rs = remote->get_remote_state ();
5497
5498   /* See FIXME above.  */
5499   if (!target_async_permitted)
5500     rs->wait_forever_enabled_p = 1;
5501
5502   rs->remote_desc = remote_serial_open (name);
5503   if (!rs->remote_desc)
5504     perror_with_name (name);
5505
5506   if (baud_rate != -1)
5507     {
5508       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5509         {
5510           /* The requested speed could not be set.  Error out to
5511              top level after closing remote_desc.  Take care to
5512              set remote_desc to NULL to avoid closing remote_desc
5513              more than once.  */
5514           serial_close (rs->remote_desc);
5515           rs->remote_desc = NULL;
5516           perror_with_name (name);
5517         }
5518     }
5519
5520   serial_setparity (rs->remote_desc, serial_parity);
5521   serial_raw (rs->remote_desc);
5522
5523   /* If there is something sitting in the buffer we might take it as a
5524      response to a command, which would be bad.  */
5525   serial_flush_input (rs->remote_desc);
5526
5527   if (from_tty)
5528     {
5529       puts_filtered ("Remote debugging using ");
5530       puts_filtered (name);
5531       puts_filtered ("\n");
5532     }
5533
5534   /* Switch to using the remote target now.  */
5535   push_target (remote);
5536   /* The target stack owns the target now.  */
5537   target_holder.release ();
5538
5539   /* Register extra event sources in the event loop.  */
5540   rs->remote_async_inferior_event_token
5541     = create_async_event_handler (remote_async_inferior_event_handler,
5542                                   remote);
5543   rs->notif_state = remote_notif_state_allocate (remote);
5544
5545   /* Reset the target state; these things will be queried either by
5546      remote_query_supported or as they are needed.  */
5547   reset_all_packet_configs_support ();
5548   rs->cached_wait_status = 0;
5549   rs->explicit_packet_size = 0;
5550   rs->noack_mode = 0;
5551   rs->extended = extended_p;
5552   rs->waiting_for_stop_reply = 0;
5553   rs->ctrlc_pending_p = 0;
5554   rs->got_ctrlc_during_io = 0;
5555
5556   rs->general_thread = not_sent_ptid;
5557   rs->continue_thread = not_sent_ptid;
5558   rs->remote_traceframe_number = -1;
5559
5560   rs->last_resume_exec_dir = EXEC_FORWARD;
5561
5562   /* Probe for ability to use "ThreadInfo" query, as required.  */
5563   rs->use_threadinfo_query = 1;
5564   rs->use_threadextra_query = 1;
5565
5566   rs->readahead_cache.invalidate ();
5567
5568   if (target_async_permitted)
5569     {
5570       /* FIXME: cagney/1999-09-23: During the initial connection it is
5571          assumed that the target is already ready and able to respond to
5572          requests.  Unfortunately remote_start_remote() eventually calls
5573          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5574          around this.  Eventually a mechanism that allows
5575          wait_for_inferior() to expect/get timeouts will be
5576          implemented.  */
5577       rs->wait_forever_enabled_p = 0;
5578     }
5579
5580   /* First delete any symbols previously loaded from shared libraries.  */
5581   no_shared_libraries (NULL, 0);
5582
5583   /* Start afresh.  */
5584   init_thread_list ();
5585
5586   /* Start the remote connection.  If error() or QUIT, discard this
5587      target (we'd otherwise be in an inconsistent state) and then
5588      propogate the error on up the exception chain.  This ensures that
5589      the caller doesn't stumble along blindly assuming that the
5590      function succeeded.  The CLI doesn't have this problem but other
5591      UI's, such as MI do.
5592
5593      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5594      this function should return an error indication letting the
5595      caller restore the previous state.  Unfortunately the command
5596      ``target remote'' is directly wired to this function making that
5597      impossible.  On a positive note, the CLI side of this problem has
5598      been fixed - the function set_cmd_context() makes it possible for
5599      all the ``target ....'' commands to share a common callback
5600      function.  See cli-dump.c.  */
5601   {
5602
5603     TRY
5604       {
5605         remote->start_remote (from_tty, extended_p);
5606       }
5607     CATCH (ex, RETURN_MASK_ALL)
5608       {
5609         /* Pop the partially set up target - unless something else did
5610            already before throwing the exception.  */
5611         if (ex.error != TARGET_CLOSE_ERROR)
5612           remote_unpush_target ();
5613         throw_exception (ex);
5614       }
5615     END_CATCH
5616   }
5617
5618   remote_btrace_reset (rs);
5619
5620   if (target_async_permitted)
5621     rs->wait_forever_enabled_p = 1;
5622 }
5623
5624 /* Detach the specified process.  */
5625
5626 void
5627 remote_target::remote_detach_pid (int pid)
5628 {
5629   struct remote_state *rs = get_remote_state ();
5630
5631   /* This should not be necessary, but the handling for D;PID in
5632      GDBserver versions prior to 8.2 incorrectly assumes that the
5633      selected process points to the same process we're detaching,
5634      leading to misbehavior (and possibly GDBserver crashing) when it
5635      does not.  Since it's easy and cheap, work around it by forcing
5636      GDBserver to select GDB's current process.  */
5637   set_general_process ();
5638
5639   if (remote_multi_process_p (rs))
5640     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5641   else
5642     strcpy (rs->buf, "D");
5643
5644   putpkt (rs->buf);
5645   getpkt (&rs->buf, &rs->buf_size, 0);
5646
5647   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5648     ;
5649   else if (rs->buf[0] == '\0')
5650     error (_("Remote doesn't know how to detach"));
5651   else
5652     error (_("Can't detach process."));
5653 }
5654
5655 /* This detaches a program to which we previously attached, using
5656    inferior_ptid to identify the process.  After this is done, GDB
5657    can be used to debug some other program.  We better not have left
5658    any breakpoints in the target program or it'll die when it hits
5659    one.  */
5660
5661 void
5662 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5663 {
5664   int pid = inferior_ptid.pid ();
5665   struct remote_state *rs = get_remote_state ();
5666   int is_fork_parent;
5667
5668   if (!target_has_execution)
5669     error (_("No process to detach from."));
5670
5671   target_announce_detach (from_tty);
5672
5673   /* Tell the remote target to detach.  */
5674   remote_detach_pid (pid);
5675
5676   /* Exit only if this is the only active inferior.  */
5677   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5678     puts_filtered (_("Ending remote debugging.\n"));
5679
5680   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5681
5682   /* Check to see if we are detaching a fork parent.  Note that if we
5683      are detaching a fork child, tp == NULL.  */
5684   is_fork_parent = (tp != NULL
5685                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5686
5687   /* If doing detach-on-fork, we don't mourn, because that will delete
5688      breakpoints that should be available for the followed inferior.  */
5689   if (!is_fork_parent)
5690     {
5691       /* Save the pid as a string before mourning, since that will
5692          unpush the remote target, and we need the string after.  */
5693       std::string infpid = target_pid_to_str (ptid_t (pid));
5694
5695       target_mourn_inferior (inferior_ptid);
5696       if (print_inferior_events)
5697         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5698                            inf->num, infpid.c_str ());
5699     }
5700   else
5701     {
5702       inferior_ptid = null_ptid;
5703       detach_inferior (current_inferior ());
5704     }
5705 }
5706
5707 void
5708 remote_target::detach (inferior *inf, int from_tty)
5709 {
5710   remote_detach_1 (inf, from_tty);
5711 }
5712
5713 void
5714 extended_remote_target::detach (inferior *inf, int from_tty)
5715 {
5716   remote_detach_1 (inf, from_tty);
5717 }
5718
5719 /* Target follow-fork function for remote targets.  On entry, and
5720    at return, the current inferior is the fork parent.
5721
5722    Note that although this is currently only used for extended-remote,
5723    it is named remote_follow_fork in anticipation of using it for the
5724    remote target as well.  */
5725
5726 int
5727 remote_target::follow_fork (int follow_child, int detach_fork)
5728 {
5729   struct remote_state *rs = get_remote_state ();
5730   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5731
5732   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5733       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5734     {
5735       /* When following the parent and detaching the child, we detach
5736          the child here.  For the case of following the child and
5737          detaching the parent, the detach is done in the target-
5738          independent follow fork code in infrun.c.  We can't use
5739          target_detach when detaching an unfollowed child because
5740          the client side doesn't know anything about the child.  */
5741       if (detach_fork && !follow_child)
5742         {
5743           /* Detach the fork child.  */
5744           ptid_t child_ptid;
5745           pid_t child_pid;
5746
5747           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5748           child_pid = child_ptid.pid ();
5749
5750           remote_detach_pid (child_pid);
5751         }
5752     }
5753   return 0;
5754 }
5755
5756 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5757    in the program space of the new inferior.  On entry and at return the
5758    current inferior is the exec'ing inferior.  INF is the new exec'd
5759    inferior, which may be the same as the exec'ing inferior unless
5760    follow-exec-mode is "new".  */
5761
5762 void
5763 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5764 {
5765   /* We know that this is a target file name, so if it has the "target:"
5766      prefix we strip it off before saving it in the program space.  */
5767   if (is_target_filename (execd_pathname))
5768     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5769
5770   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5771 }
5772
5773 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5774
5775 void
5776 remote_target::disconnect (const char *args, int from_tty)
5777 {
5778   if (args)
5779     error (_("Argument given to \"disconnect\" when remotely debugging."));
5780
5781   /* Make sure we unpush even the extended remote targets.  Calling
5782      target_mourn_inferior won't unpush, and remote_mourn won't
5783      unpush if there is more than one inferior left.  */
5784   unpush_target (this);
5785   generic_mourn_inferior ();
5786
5787   if (from_tty)
5788     puts_filtered ("Ending remote debugging.\n");
5789 }
5790
5791 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5792    be chatty about it.  */
5793
5794 void
5795 extended_remote_target::attach (const char *args, int from_tty)
5796 {
5797   struct remote_state *rs = get_remote_state ();
5798   int pid;
5799   char *wait_status = NULL;
5800
5801   pid = parse_pid_to_attach (args);
5802
5803   /* Remote PID can be freely equal to getpid, do not check it here the same
5804      way as in other targets.  */
5805
5806   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5807     error (_("This target does not support attaching to a process"));
5808
5809   if (from_tty)
5810     {
5811       char *exec_file = get_exec_file (0);
5812
5813       if (exec_file)
5814         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5815                            target_pid_to_str (ptid_t (pid)));
5816       else
5817         printf_unfiltered (_("Attaching to %s\n"),
5818                            target_pid_to_str (ptid_t (pid)));
5819
5820       gdb_flush (gdb_stdout);
5821     }
5822
5823   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5824   putpkt (rs->buf);
5825   getpkt (&rs->buf, &rs->buf_size, 0);
5826
5827   switch (packet_ok (rs->buf,
5828                      &remote_protocol_packets[PACKET_vAttach]))
5829     {
5830     case PACKET_OK:
5831       if (!target_is_non_stop_p ())
5832         {
5833           /* Save the reply for later.  */
5834           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5835           strcpy (wait_status, rs->buf);
5836         }
5837       else if (strcmp (rs->buf, "OK") != 0)
5838         error (_("Attaching to %s failed with: %s"),
5839                target_pid_to_str (ptid_t (pid)),
5840                rs->buf);
5841       break;
5842     case PACKET_UNKNOWN:
5843       error (_("This target does not support attaching to a process"));
5844     default:
5845       error (_("Attaching to %s failed"),
5846              target_pid_to_str (ptid_t (pid)));
5847     }
5848
5849   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5850
5851   inferior_ptid = ptid_t (pid);
5852
5853   if (target_is_non_stop_p ())
5854     {
5855       struct thread_info *thread;
5856
5857       /* Get list of threads.  */
5858       update_thread_list ();
5859
5860       thread = first_thread_of_inferior (current_inferior ());
5861       if (thread)
5862         inferior_ptid = thread->ptid;
5863       else
5864         inferior_ptid = ptid_t (pid);
5865
5866       /* Invalidate our notion of the remote current thread.  */
5867       record_currthread (rs, minus_one_ptid);
5868     }
5869   else
5870     {
5871       /* Now, if we have thread information, update inferior_ptid.  */
5872       inferior_ptid = remote_current_thread (inferior_ptid);
5873
5874       /* Add the main thread to the thread list.  */
5875       thread_info *thr = add_thread_silent (inferior_ptid);
5876       /* Don't consider the thread stopped until we've processed the
5877          saved stop reply.  */
5878       set_executing (thr->ptid, true);
5879     }
5880
5881   /* Next, if the target can specify a description, read it.  We do
5882      this before anything involving memory or registers.  */
5883   target_find_description ();
5884
5885   if (!target_is_non_stop_p ())
5886     {
5887       /* Use the previously fetched status.  */
5888       gdb_assert (wait_status != NULL);
5889
5890       if (target_can_async_p ())
5891         {
5892           struct notif_event *reply
5893             =  remote_notif_parse (this, &notif_client_stop, wait_status);
5894
5895           push_stop_reply ((struct stop_reply *) reply);
5896
5897           target_async (1);
5898         }
5899       else
5900         {
5901           gdb_assert (wait_status != NULL);
5902           strcpy (rs->buf, wait_status);
5903           rs->cached_wait_status = 1;
5904         }
5905     }
5906   else
5907     gdb_assert (wait_status == NULL);
5908 }
5909
5910 /* Implementation of the to_post_attach method.  */
5911
5912 void
5913 extended_remote_target::post_attach (int pid)
5914 {
5915   /* Get text, data & bss offsets.  */
5916   get_offsets ();
5917
5918   /* In certain cases GDB might not have had the chance to start
5919      symbol lookup up until now.  This could happen if the debugged
5920      binary is not using shared libraries, the vsyscall page is not
5921      present (on Linux) and the binary itself hadn't changed since the
5922      debugging process was started.  */
5923   if (symfile_objfile != NULL)
5924     remote_check_symbols();
5925 }
5926
5927 \f
5928 /* Check for the availability of vCont.  This function should also check
5929    the response.  */
5930
5931 void
5932 remote_target::remote_vcont_probe ()
5933 {
5934   remote_state *rs = get_remote_state ();
5935   char *buf;
5936
5937   strcpy (rs->buf, "vCont?");
5938   putpkt (rs->buf);
5939   getpkt (&rs->buf, &rs->buf_size, 0);
5940   buf = rs->buf;
5941
5942   /* Make sure that the features we assume are supported.  */
5943   if (startswith (buf, "vCont"))
5944     {
5945       char *p = &buf[5];
5946       int support_c, support_C;
5947
5948       rs->supports_vCont.s = 0;
5949       rs->supports_vCont.S = 0;
5950       support_c = 0;
5951       support_C = 0;
5952       rs->supports_vCont.t = 0;
5953       rs->supports_vCont.r = 0;
5954       while (p && *p == ';')
5955         {
5956           p++;
5957           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5958             rs->supports_vCont.s = 1;
5959           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5960             rs->supports_vCont.S = 1;
5961           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5962             support_c = 1;
5963           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5964             support_C = 1;
5965           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5966             rs->supports_vCont.t = 1;
5967           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5968             rs->supports_vCont.r = 1;
5969
5970           p = strchr (p, ';');
5971         }
5972
5973       /* If c, and C are not all supported, we can't use vCont.  Clearing
5974          BUF will make packet_ok disable the packet.  */
5975       if (!support_c || !support_C)
5976         buf[0] = 0;
5977     }
5978
5979   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5980 }
5981
5982 /* Helper function for building "vCont" resumptions.  Write a
5983    resumption to P.  ENDP points to one-passed-the-end of the buffer
5984    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5985    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5986    resumed thread should be single-stepped and/or signalled.  If PTID
5987    equals minus_one_ptid, then all threads are resumed; if PTID
5988    represents a process, then all threads of the process are resumed;
5989    the thread to be stepped and/or signalled is given in the global
5990    INFERIOR_PTID.  */
5991
5992 char *
5993 remote_target::append_resumption (char *p, char *endp,
5994                                   ptid_t ptid, int step, gdb_signal siggnal)
5995 {
5996   struct remote_state *rs = get_remote_state ();
5997
5998   if (step && siggnal != GDB_SIGNAL_0)
5999     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6000   else if (step
6001            /* GDB is willing to range step.  */
6002            && use_range_stepping
6003            /* Target supports range stepping.  */
6004            && rs->supports_vCont.r
6005            /* We don't currently support range stepping multiple
6006               threads with a wildcard (though the protocol allows it,
6007               so stubs shouldn't make an active effort to forbid
6008               it).  */
6009            && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6010     {
6011       struct thread_info *tp;
6012
6013       if (ptid == minus_one_ptid)
6014         {
6015           /* If we don't know about the target thread's tid, then
6016              we're resuming magic_null_ptid (see caller).  */
6017           tp = find_thread_ptid (magic_null_ptid);
6018         }
6019       else
6020         tp = find_thread_ptid (ptid);
6021       gdb_assert (tp != NULL);
6022
6023       if (tp->control.may_range_step)
6024         {
6025           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6026
6027           p += xsnprintf (p, endp - p, ";r%s,%s",
6028                           phex_nz (tp->control.step_range_start,
6029                                    addr_size),
6030                           phex_nz (tp->control.step_range_end,
6031                                    addr_size));
6032         }
6033       else
6034         p += xsnprintf (p, endp - p, ";s");
6035     }
6036   else if (step)
6037     p += xsnprintf (p, endp - p, ";s");
6038   else if (siggnal != GDB_SIGNAL_0)
6039     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6040   else
6041     p += xsnprintf (p, endp - p, ";c");
6042
6043   if (remote_multi_process_p (rs) && ptid.is_pid ())
6044     {
6045       ptid_t nptid;
6046
6047       /* All (-1) threads of process.  */
6048       nptid = ptid_t (ptid.pid (), -1, 0);
6049
6050       p += xsnprintf (p, endp - p, ":");
6051       p = write_ptid (p, endp, nptid);
6052     }
6053   else if (ptid != minus_one_ptid)
6054     {
6055       p += xsnprintf (p, endp - p, ":");
6056       p = write_ptid (p, endp, ptid);
6057     }
6058
6059   return p;
6060 }
6061
6062 /* Clear the thread's private info on resume.  */
6063
6064 static void
6065 resume_clear_thread_private_info (struct thread_info *thread)
6066 {
6067   if (thread->priv != NULL)
6068     {
6069       remote_thread_info *priv = get_remote_thread_info (thread);
6070
6071       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6072       priv->watch_data_address = 0;
6073     }
6074 }
6075
6076 /* Append a vCont continue-with-signal action for threads that have a
6077    non-zero stop signal.  */
6078
6079 char *
6080 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6081                                                   ptid_t ptid)
6082 {
6083   struct thread_info *thread;
6084
6085   ALL_NON_EXITED_THREADS (thread)
6086     if (thread->ptid.matches (ptid)
6087         && inferior_ptid != thread->ptid
6088         && thread->suspend.stop_signal != GDB_SIGNAL_0)
6089       {
6090         p = append_resumption (p, endp, thread->ptid,
6091                                0, thread->suspend.stop_signal);
6092         thread->suspend.stop_signal = GDB_SIGNAL_0;
6093         resume_clear_thread_private_info (thread);
6094       }
6095
6096   return p;
6097 }
6098
6099 /* Set the target running, using the packets that use Hc
6100    (c/s/C/S).  */
6101
6102 void
6103 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6104                                       gdb_signal siggnal)
6105 {
6106   struct remote_state *rs = get_remote_state ();
6107   struct thread_info *thread;
6108   char *buf;
6109
6110   rs->last_sent_signal = siggnal;
6111   rs->last_sent_step = step;
6112
6113   /* The c/s/C/S resume packets use Hc, so set the continue
6114      thread.  */
6115   if (ptid == minus_one_ptid)
6116     set_continue_thread (any_thread_ptid);
6117   else
6118     set_continue_thread (ptid);
6119
6120   ALL_NON_EXITED_THREADS (thread)
6121     resume_clear_thread_private_info (thread);
6122
6123   buf = rs->buf;
6124   if (::execution_direction == EXEC_REVERSE)
6125     {
6126       /* We don't pass signals to the target in reverse exec mode.  */
6127       if (info_verbose && siggnal != GDB_SIGNAL_0)
6128         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6129                  siggnal);
6130
6131       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6132         error (_("Remote reverse-step not supported."));
6133       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6134         error (_("Remote reverse-continue not supported."));
6135
6136       strcpy (buf, step ? "bs" : "bc");
6137     }
6138   else if (siggnal != GDB_SIGNAL_0)
6139     {
6140       buf[0] = step ? 'S' : 'C';
6141       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6142       buf[2] = tohex (((int) siggnal) & 0xf);
6143       buf[3] = '\0';
6144     }
6145   else
6146     strcpy (buf, step ? "s" : "c");
6147
6148   putpkt (buf);
6149 }
6150
6151 /* Resume the remote inferior by using a "vCont" packet.  The thread
6152    to be resumed is PTID; STEP and SIGGNAL indicate whether the
6153    resumed thread should be single-stepped and/or signalled.  If PTID
6154    equals minus_one_ptid, then all threads are resumed; the thread to
6155    be stepped and/or signalled is given in the global INFERIOR_PTID.
6156    This function returns non-zero iff it resumes the inferior.
6157
6158    This function issues a strict subset of all possible vCont commands
6159    at the moment.  */
6160
6161 int
6162 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6163                                          enum gdb_signal siggnal)
6164 {
6165   struct remote_state *rs = get_remote_state ();
6166   char *p;
6167   char *endp;
6168
6169   /* No reverse execution actions defined for vCont.  */
6170   if (::execution_direction == EXEC_REVERSE)
6171     return 0;
6172
6173   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6174     remote_vcont_probe ();
6175
6176   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6177     return 0;
6178
6179   p = rs->buf;
6180   endp = rs->buf + get_remote_packet_size ();
6181
6182   /* If we could generate a wider range of packets, we'd have to worry
6183      about overflowing BUF.  Should there be a generic
6184      "multi-part-packet" packet?  */
6185
6186   p += xsnprintf (p, endp - p, "vCont");
6187
6188   if (ptid == magic_null_ptid)
6189     {
6190       /* MAGIC_NULL_PTID means that we don't have any active threads,
6191          so we don't have any TID numbers the inferior will
6192          understand.  Make sure to only send forms that do not specify
6193          a TID.  */
6194       append_resumption (p, endp, minus_one_ptid, step, siggnal);
6195     }
6196   else if (ptid == minus_one_ptid || ptid.is_pid ())
6197     {
6198       /* Resume all threads (of all processes, or of a single
6199          process), with preference for INFERIOR_PTID.  This assumes
6200          inferior_ptid belongs to the set of all threads we are about
6201          to resume.  */
6202       if (step || siggnal != GDB_SIGNAL_0)
6203         {
6204           /* Step inferior_ptid, with or without signal.  */
6205           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6206         }
6207
6208       /* Also pass down any pending signaled resumption for other
6209          threads not the current.  */
6210       p = append_pending_thread_resumptions (p, endp, ptid);
6211
6212       /* And continue others without a signal.  */
6213       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6214     }
6215   else
6216     {
6217       /* Scheduler locking; resume only PTID.  */
6218       append_resumption (p, endp, ptid, step, siggnal);
6219     }
6220
6221   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6222   putpkt (rs->buf);
6223
6224   if (target_is_non_stop_p ())
6225     {
6226       /* In non-stop, the stub replies to vCont with "OK".  The stop
6227          reply will be reported asynchronously by means of a `%Stop'
6228          notification.  */
6229       getpkt (&rs->buf, &rs->buf_size, 0);
6230       if (strcmp (rs->buf, "OK") != 0)
6231         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6232     }
6233
6234   return 1;
6235 }
6236
6237 /* Tell the remote machine to resume.  */
6238
6239 void
6240 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6241 {
6242   struct remote_state *rs = get_remote_state ();
6243
6244   /* When connected in non-stop mode, the core resumes threads
6245      individually.  Resuming remote threads directly in target_resume
6246      would thus result in sending one packet per thread.  Instead, to
6247      minimize roundtrip latency, here we just store the resume
6248      request; the actual remote resumption will be done in
6249      target_commit_resume / remote_commit_resume, where we'll be able
6250      to do vCont action coalescing.  */
6251   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6252     {
6253       remote_thread_info *remote_thr;
6254
6255       if (minus_one_ptid == ptid || ptid.is_pid ())
6256         remote_thr = get_remote_thread_info (inferior_ptid);
6257       else
6258         remote_thr = get_remote_thread_info (ptid);
6259
6260       remote_thr->last_resume_step = step;
6261       remote_thr->last_resume_sig = siggnal;
6262       return;
6263     }
6264
6265   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6266      (explained in remote-notif.c:handle_notification) so
6267      remote_notif_process is not called.  We need find a place where
6268      it is safe to start a 'vNotif' sequence.  It is good to do it
6269      before resuming inferior, because inferior was stopped and no RSP
6270      traffic at that moment.  */
6271   if (!target_is_non_stop_p ())
6272     remote_notif_process (rs->notif_state, &notif_client_stop);
6273
6274   rs->last_resume_exec_dir = ::execution_direction;
6275
6276   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6277   if (!remote_resume_with_vcont (ptid, step, siggnal))
6278     remote_resume_with_hc (ptid, step, siggnal);
6279
6280   /* We are about to start executing the inferior, let's register it
6281      with the event loop.  NOTE: this is the one place where all the
6282      execution commands end up.  We could alternatively do this in each
6283      of the execution commands in infcmd.c.  */
6284   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6285      into infcmd.c in order to allow inferior function calls to work
6286      NOT asynchronously.  */
6287   if (target_can_async_p ())
6288     target_async (1);
6289
6290   /* We've just told the target to resume.  The remote server will
6291      wait for the inferior to stop, and then send a stop reply.  In
6292      the mean time, we can't start another command/query ourselves
6293      because the stub wouldn't be ready to process it.  This applies
6294      only to the base all-stop protocol, however.  In non-stop (which
6295      only supports vCont), the stub replies with an "OK", and is
6296      immediate able to process further serial input.  */
6297   if (!target_is_non_stop_p ())
6298     rs->waiting_for_stop_reply = 1;
6299 }
6300
6301 static int is_pending_fork_parent_thread (struct thread_info *thread);
6302
6303 /* Private per-inferior info for target remote processes.  */
6304
6305 struct remote_inferior : public private_inferior
6306 {
6307   /* Whether we can send a wildcard vCont for this process.  */
6308   bool may_wildcard_vcont = true;
6309 };
6310
6311 /* Get the remote private inferior data associated to INF.  */
6312
6313 static remote_inferior *
6314 get_remote_inferior (inferior *inf)
6315 {
6316   if (inf->priv == NULL)
6317     inf->priv.reset (new remote_inferior);
6318
6319   return static_cast<remote_inferior *> (inf->priv.get ());
6320 }
6321
6322 /* Class used to track the construction of a vCont packet in the
6323    outgoing packet buffer.  This is used to send multiple vCont
6324    packets if we have more actions than would fit a single packet.  */
6325
6326 class vcont_builder
6327 {
6328 public:
6329   explicit vcont_builder (remote_target *remote)
6330     : m_remote (remote)
6331   {
6332     restart ();
6333   }
6334
6335   void flush ();
6336   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6337
6338 private:
6339   void restart ();
6340
6341   /* The remote target.  */
6342   remote_target *m_remote;
6343
6344   /* Pointer to the first action.  P points here if no action has been
6345      appended yet.  */
6346   char *m_first_action;
6347
6348   /* Where the next action will be appended.  */
6349   char *m_p;
6350
6351   /* The end of the buffer.  Must never write past this.  */
6352   char *m_endp;
6353 };
6354
6355 /* Prepare the outgoing buffer for a new vCont packet.  */
6356
6357 void
6358 vcont_builder::restart ()
6359 {
6360   struct remote_state *rs = m_remote->get_remote_state ();
6361
6362   m_p = rs->buf;
6363   m_endp = rs->buf + m_remote->get_remote_packet_size ();
6364   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6365   m_first_action = m_p;
6366 }
6367
6368 /* If the vCont packet being built has any action, send it to the
6369    remote end.  */
6370
6371 void
6372 vcont_builder::flush ()
6373 {
6374   struct remote_state *rs;
6375
6376   if (m_p == m_first_action)
6377     return;
6378
6379   rs = m_remote->get_remote_state ();
6380   m_remote->putpkt (rs->buf);
6381   m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6382   if (strcmp (rs->buf, "OK") != 0)
6383     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6384 }
6385
6386 /* The largest action is range-stepping, with its two addresses.  This
6387    is more than sufficient.  If a new, bigger action is created, it'll
6388    quickly trigger a failed assertion in append_resumption (and we'll
6389    just bump this).  */
6390 #define MAX_ACTION_SIZE 200
6391
6392 /* Append a new vCont action in the outgoing packet being built.  If
6393    the action doesn't fit the packet along with previous actions, push
6394    what we've got so far to the remote end and start over a new vCont
6395    packet (with the new action).  */
6396
6397 void
6398 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6399 {
6400   char buf[MAX_ACTION_SIZE + 1];
6401
6402   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6403                                             ptid, step, siggnal);
6404
6405   /* Check whether this new action would fit in the vCont packet along
6406      with previous actions.  If not, send what we've got so far and
6407      start a new vCont packet.  */
6408   size_t rsize = endp - buf;
6409   if (rsize > m_endp - m_p)
6410     {
6411       flush ();
6412       restart ();
6413
6414       /* Should now fit.  */
6415       gdb_assert (rsize <= m_endp - m_p);
6416     }
6417
6418   memcpy (m_p, buf, rsize);
6419   m_p += rsize;
6420   *m_p = '\0';
6421 }
6422
6423 /* to_commit_resume implementation.  */
6424
6425 void
6426 remote_target::commit_resume ()
6427 {
6428   struct inferior *inf;
6429   struct thread_info *tp;
6430   int any_process_wildcard;
6431   int may_global_wildcard_vcont;
6432
6433   /* If connected in all-stop mode, we'd send the remote resume
6434      request directly from remote_resume.  Likewise if
6435      reverse-debugging, as there are no defined vCont actions for
6436      reverse execution.  */
6437   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6438     return;
6439
6440   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6441      instead of resuming all threads of each process individually.
6442      However, if any thread of a process must remain halted, we can't
6443      send wildcard resumes and must send one action per thread.
6444
6445      Care must be taken to not resume threads/processes the server
6446      side already told us are stopped, but the core doesn't know about
6447      yet, because the events are still in the vStopped notification
6448      queue.  For example:
6449
6450        #1 => vCont s:p1.1;c
6451        #2 <= OK
6452        #3 <= %Stopped T05 p1.1
6453        #4 => vStopped
6454        #5 <= T05 p1.2
6455        #6 => vStopped
6456        #7 <= OK
6457        #8 (infrun handles the stop for p1.1 and continues stepping)
6458        #9 => vCont s:p1.1;c
6459
6460      The last vCont above would resume thread p1.2 by mistake, because
6461      the server has no idea that the event for p1.2 had not been
6462      handled yet.
6463
6464      The server side must similarly ignore resume actions for the
6465      thread that has a pending %Stopped notification (and any other
6466      threads with events pending), until GDB acks the notification
6467      with vStopped.  Otherwise, e.g., the following case is
6468      mishandled:
6469
6470        #1 => g  (or any other packet)
6471        #2 <= [registers]
6472        #3 <= %Stopped T05 p1.2
6473        #4 => vCont s:p1.1;c
6474        #5 <= OK
6475
6476      Above, the server must not resume thread p1.2.  GDB can't know
6477      that p1.2 stopped until it acks the %Stopped notification, and
6478      since from GDB's perspective all threads should be running, it
6479      sends a "c" action.
6480
6481      Finally, special care must also be given to handling fork/vfork
6482      events.  A (v)fork event actually tells us that two processes
6483      stopped -- the parent and the child.  Until we follow the fork,
6484      we must not resume the child.  Therefore, if we have a pending
6485      fork follow, we must not send a global wildcard resume action
6486      (vCont;c).  We can still send process-wide wildcards though.  */
6487
6488   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6489   may_global_wildcard_vcont = 1;
6490
6491   /* And assume every process is individually wildcard-able too.  */
6492   ALL_NON_EXITED_INFERIORS (inf)
6493     {
6494       remote_inferior *priv = get_remote_inferior (inf);
6495
6496       priv->may_wildcard_vcont = true;
6497     }
6498
6499   /* Check for any pending events (not reported or processed yet) and
6500      disable process and global wildcard resumes appropriately.  */
6501   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6502
6503   ALL_NON_EXITED_THREADS (tp)
6504     {
6505       /* If a thread of a process is not meant to be resumed, then we
6506          can't wildcard that process.  */
6507       if (!tp->executing)
6508         {
6509           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6510
6511           /* And if we can't wildcard a process, we can't wildcard
6512              everything either.  */
6513           may_global_wildcard_vcont = 0;
6514           continue;
6515         }
6516
6517       /* If a thread is the parent of an unfollowed fork, then we
6518          can't do a global wildcard, as that would resume the fork
6519          child.  */
6520       if (is_pending_fork_parent_thread (tp))
6521         may_global_wildcard_vcont = 0;
6522     }
6523
6524   /* Now let's build the vCont packet(s).  Actions must be appended
6525      from narrower to wider scopes (thread -> process -> global).  If
6526      we end up with too many actions for a single packet vcont_builder
6527      flushes the current vCont packet to the remote side and starts a
6528      new one.  */
6529   struct vcont_builder vcont_builder (this);
6530
6531   /* Threads first.  */
6532   ALL_NON_EXITED_THREADS (tp)
6533     {
6534       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6535
6536       if (!tp->executing || remote_thr->vcont_resumed)
6537         continue;
6538
6539       gdb_assert (!thread_is_in_step_over_chain (tp));
6540
6541       if (!remote_thr->last_resume_step
6542           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6543           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6544         {
6545           /* We'll send a wildcard resume instead.  */
6546           remote_thr->vcont_resumed = 1;
6547           continue;
6548         }
6549
6550       vcont_builder.push_action (tp->ptid,
6551                                  remote_thr->last_resume_step,
6552                                  remote_thr->last_resume_sig);
6553       remote_thr->vcont_resumed = 1;
6554     }
6555
6556   /* Now check whether we can send any process-wide wildcard.  This is
6557      to avoid sending a global wildcard in the case nothing is
6558      supposed to be resumed.  */
6559   any_process_wildcard = 0;
6560
6561   ALL_NON_EXITED_INFERIORS (inf)
6562     {
6563       if (get_remote_inferior (inf)->may_wildcard_vcont)
6564         {
6565           any_process_wildcard = 1;
6566           break;
6567         }
6568     }
6569
6570   if (any_process_wildcard)
6571     {
6572       /* If all processes are wildcard-able, then send a single "c"
6573          action, otherwise, send an "all (-1) threads of process"
6574          continue action for each running process, if any.  */
6575       if (may_global_wildcard_vcont)
6576         {
6577           vcont_builder.push_action (minus_one_ptid,
6578                                      false, GDB_SIGNAL_0);
6579         }
6580       else
6581         {
6582           ALL_NON_EXITED_INFERIORS (inf)
6583             {
6584               if (get_remote_inferior (inf)->may_wildcard_vcont)
6585                 {
6586                   vcont_builder.push_action (ptid_t (inf->pid),
6587                                              false, GDB_SIGNAL_0);
6588                 }
6589             }
6590         }
6591     }
6592
6593   vcont_builder.flush ();
6594 }
6595
6596 \f
6597
6598 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6599    thread, all threads of a remote process, or all threads of all
6600    processes.  */
6601
6602 void
6603 remote_target::remote_stop_ns (ptid_t ptid)
6604 {
6605   struct remote_state *rs = get_remote_state ();
6606   char *p = rs->buf;
6607   char *endp = rs->buf + get_remote_packet_size ();
6608
6609   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6610     remote_vcont_probe ();
6611
6612   if (!rs->supports_vCont.t)
6613     error (_("Remote server does not support stopping threads"));
6614
6615   if (ptid == minus_one_ptid
6616       || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6617     p += xsnprintf (p, endp - p, "vCont;t");
6618   else
6619     {
6620       ptid_t nptid;
6621
6622       p += xsnprintf (p, endp - p, "vCont;t:");
6623
6624       if (ptid.is_pid ())
6625           /* All (-1) threads of process.  */
6626         nptid = ptid_t (ptid.pid (), -1, 0);
6627       else
6628         {
6629           /* Small optimization: if we already have a stop reply for
6630              this thread, no use in telling the stub we want this
6631              stopped.  */
6632           if (peek_stop_reply (ptid))
6633             return;
6634
6635           nptid = ptid;
6636         }
6637
6638       write_ptid (p, endp, nptid);
6639     }
6640
6641   /* In non-stop, we get an immediate OK reply.  The stop reply will
6642      come in asynchronously by notification.  */
6643   putpkt (rs->buf);
6644   getpkt (&rs->buf, &rs->buf_size, 0);
6645   if (strcmp (rs->buf, "OK") != 0)
6646     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6647 }
6648
6649 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6650    interrupt the remote target.  It is undefined which thread of which
6651    process reports the interrupt.  */
6652
6653 void
6654 remote_target::remote_interrupt_as ()
6655 {
6656   struct remote_state *rs = get_remote_state ();
6657
6658   rs->ctrlc_pending_p = 1;
6659
6660   /* If the inferior is stopped already, but the core didn't know
6661      about it yet, just ignore the request.  The cached wait status
6662      will be collected in remote_wait.  */
6663   if (rs->cached_wait_status)
6664     return;
6665
6666   /* Send interrupt_sequence to remote target.  */
6667   send_interrupt_sequence ();
6668 }
6669
6670 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6671    the remote target.  It is undefined which thread of which process
6672    reports the interrupt.  Throws an error if the packet is not
6673    supported by the server.  */
6674
6675 void
6676 remote_target::remote_interrupt_ns ()
6677 {
6678   struct remote_state *rs = get_remote_state ();
6679   char *p = rs->buf;
6680   char *endp = rs->buf + get_remote_packet_size ();
6681
6682   xsnprintf (p, endp - p, "vCtrlC");
6683
6684   /* In non-stop, we get an immediate OK reply.  The stop reply will
6685      come in asynchronously by notification.  */
6686   putpkt (rs->buf);
6687   getpkt (&rs->buf, &rs->buf_size, 0);
6688
6689   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6690     {
6691     case PACKET_OK:
6692       break;
6693     case PACKET_UNKNOWN:
6694       error (_("No support for interrupting the remote target."));
6695     case PACKET_ERROR:
6696       error (_("Interrupting target failed: %s"), rs->buf);
6697     }
6698 }
6699
6700 /* Implement the to_stop function for the remote targets.  */
6701
6702 void
6703 remote_target::stop (ptid_t ptid)
6704 {
6705   if (remote_debug)
6706     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6707
6708   if (target_is_non_stop_p ())
6709     remote_stop_ns (ptid);
6710   else
6711     {
6712       /* We don't currently have a way to transparently pause the
6713          remote target in all-stop mode.  Interrupt it instead.  */
6714       remote_interrupt_as ();
6715     }
6716 }
6717
6718 /* Implement the to_interrupt function for the remote targets.  */
6719
6720 void
6721 remote_target::interrupt ()
6722 {
6723   if (remote_debug)
6724     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6725
6726   if (target_is_non_stop_p ())
6727     remote_interrupt_ns ();
6728   else
6729     remote_interrupt_as ();
6730 }
6731
6732 /* Implement the to_pass_ctrlc function for the remote targets.  */
6733
6734 void
6735 remote_target::pass_ctrlc ()
6736 {
6737   struct remote_state *rs = get_remote_state ();
6738
6739   if (remote_debug)
6740     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6741
6742   /* If we're starting up, we're not fully synced yet.  Quit
6743      immediately.  */
6744   if (rs->starting_up)
6745     quit ();
6746   /* If ^C has already been sent once, offer to disconnect.  */
6747   else if (rs->ctrlc_pending_p)
6748     interrupt_query ();
6749   else
6750     target_interrupt ();
6751 }
6752
6753 /* Ask the user what to do when an interrupt is received.  */
6754
6755 void
6756 remote_target::interrupt_query ()
6757 {
6758   struct remote_state *rs = get_remote_state ();
6759
6760   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6761     {
6762       if (query (_("The target is not responding to interrupt requests.\n"
6763                    "Stop debugging it? ")))
6764         {
6765           remote_unpush_target ();
6766           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6767         }
6768     }
6769   else
6770     {
6771       if (query (_("Interrupted while waiting for the program.\n"
6772                    "Give up waiting? ")))
6773         quit ();
6774     }
6775 }
6776
6777 /* Enable/disable target terminal ownership.  Most targets can use
6778    terminal groups to control terminal ownership.  Remote targets are
6779    different in that explicit transfer of ownership to/from GDB/target
6780    is required.  */
6781
6782 void
6783 remote_target::terminal_inferior ()
6784 {
6785   /* NOTE: At this point we could also register our selves as the
6786      recipient of all input.  Any characters typed could then be
6787      passed on down to the target.  */
6788 }
6789
6790 void
6791 remote_target::terminal_ours ()
6792 {
6793 }
6794
6795 static void
6796 remote_console_output (char *msg)
6797 {
6798   char *p;
6799
6800   for (p = msg; p[0] && p[1]; p += 2)
6801     {
6802       char tb[2];
6803       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6804
6805       tb[0] = c;
6806       tb[1] = 0;
6807       fputs_unfiltered (tb, gdb_stdtarg);
6808     }
6809   gdb_flush (gdb_stdtarg);
6810 }
6811
6812 DEF_VEC_O(cached_reg_t);
6813
6814 typedef struct stop_reply
6815 {
6816   struct notif_event base;
6817
6818   /* The identifier of the thread about this event  */
6819   ptid_t ptid;
6820
6821   /* The remote state this event is associated with.  When the remote
6822      connection, represented by a remote_state object, is closed,
6823      all the associated stop_reply events should be released.  */
6824   struct remote_state *rs;
6825
6826   struct target_waitstatus ws;
6827
6828   /* The architecture associated with the expedited registers.  */
6829   gdbarch *arch;
6830
6831   /* Expedited registers.  This makes remote debugging a bit more
6832      efficient for those targets that provide critical registers as
6833      part of their normal status mechanism (as another roundtrip to
6834      fetch them is avoided).  */
6835   VEC(cached_reg_t) *regcache;
6836
6837   enum target_stop_reason stop_reason;
6838
6839   CORE_ADDR watch_data_address;
6840
6841   int core;
6842 } *stop_reply_p;
6843
6844 static void
6845 stop_reply_xfree (struct stop_reply *r)
6846 {
6847   notif_event_xfree ((struct notif_event *) r);
6848 }
6849
6850 /* Return the length of the stop reply queue.  */
6851
6852 int
6853 remote_target::stop_reply_queue_length ()
6854 {
6855   remote_state *rs = get_remote_state ();
6856   return rs->stop_reply_queue.size ();
6857 }
6858
6859 void
6860 remote_notif_stop_parse (remote_target *remote,
6861                          struct notif_client *self, char *buf,
6862                          struct notif_event *event)
6863 {
6864   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6865 }
6866
6867 static void
6868 remote_notif_stop_ack (remote_target *remote,
6869                        struct notif_client *self, char *buf,
6870                        struct notif_event *event)
6871 {
6872   struct stop_reply *stop_reply = (struct stop_reply *) event;
6873
6874   /* acknowledge */
6875   putpkt (remote, self->ack_command);
6876
6877   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6878     {
6879       /* We got an unknown stop reply.  */
6880       error (_("Unknown stop reply"));
6881     }
6882
6883   remote->push_stop_reply (stop_reply);
6884 }
6885
6886 static int
6887 remote_notif_stop_can_get_pending_events (remote_target *remote,
6888                                           struct notif_client *self)
6889 {
6890   /* We can't get pending events in remote_notif_process for
6891      notification stop, and we have to do this in remote_wait_ns
6892      instead.  If we fetch all queued events from stub, remote stub
6893      may exit and we have no chance to process them back in
6894      remote_wait_ns.  */
6895   remote_state *rs = remote->get_remote_state ();
6896   mark_async_event_handler (rs->remote_async_inferior_event_token);
6897   return 0;
6898 }
6899
6900 static void
6901 stop_reply_dtr (struct notif_event *event)
6902 {
6903   struct stop_reply *r = (struct stop_reply *) event;
6904   cached_reg_t *reg;
6905   int ix;
6906
6907   for (ix = 0;
6908        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6909        ix++)
6910     xfree (reg->data);
6911
6912   VEC_free (cached_reg_t, r->regcache);
6913 }
6914
6915 static struct notif_event *
6916 remote_notif_stop_alloc_reply (void)
6917 {
6918   /* We cast to a pointer to the "base class".  */
6919   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6920
6921   r->dtr = stop_reply_dtr;
6922
6923   return r;
6924 }
6925
6926 /* A client of notification Stop.  */
6927
6928 struct notif_client notif_client_stop =
6929 {
6930   "Stop",
6931   "vStopped",
6932   remote_notif_stop_parse,
6933   remote_notif_stop_ack,
6934   remote_notif_stop_can_get_pending_events,
6935   remote_notif_stop_alloc_reply,
6936   REMOTE_NOTIF_STOP,
6937 };
6938
6939 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6940    the pid of the process that owns the threads we want to check, or
6941    -1 if we want to check all threads.  */
6942
6943 static int
6944 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6945                         ptid_t thread_ptid)
6946 {
6947   if (ws->kind == TARGET_WAITKIND_FORKED
6948       || ws->kind == TARGET_WAITKIND_VFORKED)
6949     {
6950       if (event_pid == -1 || event_pid == thread_ptid.pid ())
6951         return 1;
6952     }
6953
6954   return 0;
6955 }
6956
6957 /* Return the thread's pending status used to determine whether the
6958    thread is a fork parent stopped at a fork event.  */
6959
6960 static struct target_waitstatus *
6961 thread_pending_fork_status (struct thread_info *thread)
6962 {
6963   if (thread->suspend.waitstatus_pending_p)
6964     return &thread->suspend.waitstatus;
6965   else
6966     return &thread->pending_follow;
6967 }
6968
6969 /* Determine if THREAD is a pending fork parent thread.  */
6970
6971 static int
6972 is_pending_fork_parent_thread (struct thread_info *thread)
6973 {
6974   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6975   int pid = -1;
6976
6977   return is_pending_fork_parent (ws, pid, thread->ptid);
6978 }
6979
6980 /* If CONTEXT contains any fork child threads that have not been
6981    reported yet, remove them from the CONTEXT list.  If such a
6982    thread exists it is because we are stopped at a fork catchpoint
6983    and have not yet called follow_fork, which will set up the
6984    host-side data structures for the new process.  */
6985
6986 void
6987 remote_target::remove_new_fork_children (threads_listing_context *context)
6988 {
6989   struct thread_info * thread;
6990   int pid = -1;
6991   struct notif_client *notif = &notif_client_stop;
6992
6993   /* For any threads stopped at a fork event, remove the corresponding
6994      fork child threads from the CONTEXT list.  */
6995   ALL_NON_EXITED_THREADS (thread)
6996     {
6997       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6998
6999       if (is_pending_fork_parent (ws, pid, thread->ptid))
7000         context->remove_thread (ws->value.related_pid);
7001     }
7002
7003   /* Check for any pending fork events (not reported or processed yet)
7004      in process PID and remove those fork child threads from the
7005      CONTEXT list as well.  */
7006   remote_notif_get_pending_events (notif);
7007   for (auto &event : get_remote_state ()->stop_reply_queue)
7008     if (event->ws.kind == TARGET_WAITKIND_FORKED
7009         || event->ws.kind == TARGET_WAITKIND_VFORKED
7010         || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7011       context->remove_thread (event->ws.value.related_pid);
7012 }
7013
7014 /* Check whether any event pending in the vStopped queue would prevent
7015    a global or process wildcard vCont action.  Clear
7016    *may_global_wildcard if we can't do a global wildcard (vCont;c),
7017    and clear the event inferior's may_wildcard_vcont flag if we can't
7018    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
7019
7020 void
7021 remote_target::check_pending_events_prevent_wildcard_vcont
7022   (int *may_global_wildcard)
7023 {
7024   struct notif_client *notif = &notif_client_stop;
7025
7026   remote_notif_get_pending_events (notif);
7027   for (auto &event : get_remote_state ()->stop_reply_queue)
7028     {
7029       if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7030           || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7031         continue;
7032
7033       if (event->ws.kind == TARGET_WAITKIND_FORKED
7034           || event->ws.kind == TARGET_WAITKIND_VFORKED)
7035         *may_global_wildcard = 0;
7036
7037       struct inferior *inf = find_inferior_ptid (event->ptid);
7038
7039       /* This may be the first time we heard about this process.
7040          Regardless, we must not do a global wildcard resume, otherwise
7041          we'd resume this process too.  */
7042       *may_global_wildcard = 0;
7043       if (inf != NULL)
7044         get_remote_inferior (inf)->may_wildcard_vcont = false;
7045     }
7046 }
7047
7048 /* Discard all pending stop replies of inferior INF.  */
7049
7050 void
7051 remote_target::discard_pending_stop_replies (struct inferior *inf)
7052 {
7053   struct stop_reply *reply;
7054   struct remote_state *rs = get_remote_state ();
7055   struct remote_notif_state *rns = rs->notif_state;
7056
7057   /* This function can be notified when an inferior exists.  When the
7058      target is not remote, the notification state is NULL.  */
7059   if (rs->remote_desc == NULL)
7060     return;
7061
7062   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7063
7064   /* Discard the in-flight notification.  */
7065   if (reply != NULL && reply->ptid.pid () == inf->pid)
7066     {
7067       stop_reply_xfree (reply);
7068       rns->pending_event[notif_client_stop.id] = NULL;
7069     }
7070
7071   /* Discard the stop replies we have already pulled with
7072      vStopped.  */
7073   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7074                               rs->stop_reply_queue.end (),
7075                               [=] (const stop_reply_up &event)
7076                               {
7077                                 return event->ptid.pid () == inf->pid;
7078                               });
7079   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7080 }
7081
7082 /* Discard the stop replies for RS in stop_reply_queue.  */
7083
7084 void
7085 remote_target::discard_pending_stop_replies_in_queue ()
7086 {
7087   remote_state *rs = get_remote_state ();
7088
7089   /* Discard the stop replies we have already pulled with
7090      vStopped.  */
7091   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7092                               rs->stop_reply_queue.end (),
7093                               [=] (const stop_reply_up &event)
7094                               {
7095                                 return event->rs == rs;
7096                               });
7097   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7098 }
7099
7100 /* Remove the first reply in 'stop_reply_queue' which matches
7101    PTID.  */
7102
7103 struct stop_reply *
7104 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7105 {
7106   remote_state *rs = get_remote_state ();
7107
7108   auto iter = std::find_if (rs->stop_reply_queue.begin (),
7109                             rs->stop_reply_queue.end (),
7110                             [=] (const stop_reply_up &event)
7111                             {
7112                               return event->ptid.matches (ptid);
7113                             });
7114   struct stop_reply *result;
7115   if (iter == rs->stop_reply_queue.end ())
7116     result = nullptr;
7117   else
7118     {
7119       result = iter->release ();
7120       rs->stop_reply_queue.erase (iter);
7121     }
7122
7123   if (notif_debug)
7124     fprintf_unfiltered (gdb_stdlog,
7125                         "notif: discard queued event: 'Stop' in %s\n",
7126                         target_pid_to_str (ptid));
7127
7128   return result;
7129 }
7130
7131 /* Look for a queued stop reply belonging to PTID.  If one is found,
7132    remove it from the queue, and return it.  Returns NULL if none is
7133    found.  If there are still queued events left to process, tell the
7134    event loop to get back to target_wait soon.  */
7135
7136 struct stop_reply *
7137 remote_target::queued_stop_reply (ptid_t ptid)
7138 {
7139   remote_state *rs = get_remote_state ();
7140   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7141
7142   if (!rs->stop_reply_queue.empty ())
7143     {
7144       /* There's still at least an event left.  */
7145       mark_async_event_handler (rs->remote_async_inferior_event_token);
7146     }
7147
7148   return r;
7149 }
7150
7151 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7152    know that we now have at least one queued event left to pass to the
7153    core side, tell the event loop to get back to target_wait soon.  */
7154
7155 void
7156 remote_target::push_stop_reply (struct stop_reply *new_event)
7157 {
7158   remote_state *rs = get_remote_state ();
7159   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7160
7161   if (notif_debug)
7162     fprintf_unfiltered (gdb_stdlog,
7163                         "notif: push 'Stop' %s to queue %d\n",
7164                         target_pid_to_str (new_event->ptid),
7165                         int (rs->stop_reply_queue.size ()));
7166
7167   mark_async_event_handler (rs->remote_async_inferior_event_token);
7168 }
7169
7170 /* Returns true if we have a stop reply for PTID.  */
7171
7172 int
7173 remote_target::peek_stop_reply (ptid_t ptid)
7174 {
7175   remote_state *rs = get_remote_state ();
7176   for (auto &event : rs->stop_reply_queue)
7177     if (ptid == event->ptid
7178         && event->ws.kind == TARGET_WAITKIND_STOPPED)
7179       return 1;
7180   return 0;
7181 }
7182
7183 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7184    starting with P and ending with PEND matches PREFIX.  */
7185
7186 static int
7187 strprefix (const char *p, const char *pend, const char *prefix)
7188 {
7189   for ( ; p < pend; p++, prefix++)
7190     if (*p != *prefix)
7191       return 0;
7192   return *prefix == '\0';
7193 }
7194
7195 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7196    result is stored in EVENT, or throws an error.  */
7197
7198 void
7199 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7200 {
7201   remote_arch_state *rsa = NULL;
7202   ULONGEST addr;
7203   const char *p;
7204   int skipregs = 0;
7205
7206   event->ptid = null_ptid;
7207   event->rs = get_remote_state ();
7208   event->ws.kind = TARGET_WAITKIND_IGNORE;
7209   event->ws.value.integer = 0;
7210   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7211   event->regcache = NULL;
7212   event->core = -1;
7213
7214   switch (buf[0])
7215     {
7216     case 'T':           /* Status with PC, SP, FP, ...  */
7217       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7218       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7219             ss = signal number
7220             n... = register number
7221             r... = register contents
7222       */
7223
7224       p = &buf[3];      /* after Txx */
7225       while (*p)
7226         {
7227           const char *p1;
7228           int fieldsize;
7229
7230           p1 = strchr (p, ':');
7231           if (p1 == NULL)
7232             error (_("Malformed packet(a) (missing colon): %s\n\
7233 Packet: '%s'\n"),
7234                    p, buf);
7235           if (p == p1)
7236             error (_("Malformed packet(a) (missing register number): %s\n\
7237 Packet: '%s'\n"),
7238                    p, buf);
7239
7240           /* Some "registers" are actually extended stop information.
7241              Note if you're adding a new entry here: GDB 7.9 and
7242              earlier assume that all register "numbers" that start
7243              with an hex digit are real register numbers.  Make sure
7244              the server only sends such a packet if it knows the
7245              client understands it.  */
7246
7247           if (strprefix (p, p1, "thread"))
7248             event->ptid = read_ptid (++p1, &p);
7249           else if (strprefix (p, p1, "syscall_entry"))
7250             {
7251               ULONGEST sysno;
7252
7253               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7254               p = unpack_varlen_hex (++p1, &sysno);
7255               event->ws.value.syscall_number = (int) sysno;
7256             }
7257           else if (strprefix (p, p1, "syscall_return"))
7258             {
7259               ULONGEST sysno;
7260
7261               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7262               p = unpack_varlen_hex (++p1, &sysno);
7263               event->ws.value.syscall_number = (int) sysno;
7264             }
7265           else if (strprefix (p, p1, "watch")
7266                    || strprefix (p, p1, "rwatch")
7267                    || strprefix (p, p1, "awatch"))
7268             {
7269               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7270               p = unpack_varlen_hex (++p1, &addr);
7271               event->watch_data_address = (CORE_ADDR) addr;
7272             }
7273           else if (strprefix (p, p1, "swbreak"))
7274             {
7275               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7276
7277               /* Make sure the stub doesn't forget to indicate support
7278                  with qSupported.  */
7279               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7280                 error (_("Unexpected swbreak stop reason"));
7281
7282               /* The value part is documented as "must be empty",
7283                  though we ignore it, in case we ever decide to make
7284                  use of it in a backward compatible way.  */
7285               p = strchrnul (p1 + 1, ';');
7286             }
7287           else if (strprefix (p, p1, "hwbreak"))
7288             {
7289               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7290
7291               /* Make sure the stub doesn't forget to indicate support
7292                  with qSupported.  */
7293               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7294                 error (_("Unexpected hwbreak stop reason"));
7295
7296               /* See above.  */
7297               p = strchrnul (p1 + 1, ';');
7298             }
7299           else if (strprefix (p, p1, "library"))
7300             {
7301               event->ws.kind = TARGET_WAITKIND_LOADED;
7302               p = strchrnul (p1 + 1, ';');
7303             }
7304           else if (strprefix (p, p1, "replaylog"))
7305             {
7306               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7307               /* p1 will indicate "begin" or "end", but it makes
7308                  no difference for now, so ignore it.  */
7309               p = strchrnul (p1 + 1, ';');
7310             }
7311           else if (strprefix (p, p1, "core"))
7312             {
7313               ULONGEST c;
7314
7315               p = unpack_varlen_hex (++p1, &c);
7316               event->core = c;
7317             }
7318           else if (strprefix (p, p1, "fork"))
7319             {
7320               event->ws.value.related_pid = read_ptid (++p1, &p);
7321               event->ws.kind = TARGET_WAITKIND_FORKED;
7322             }
7323           else if (strprefix (p, p1, "vfork"))
7324             {
7325               event->ws.value.related_pid = read_ptid (++p1, &p);
7326               event->ws.kind = TARGET_WAITKIND_VFORKED;
7327             }
7328           else if (strprefix (p, p1, "vforkdone"))
7329             {
7330               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7331               p = strchrnul (p1 + 1, ';');
7332             }
7333           else if (strprefix (p, p1, "exec"))
7334             {
7335               ULONGEST ignored;
7336               char pathname[PATH_MAX];
7337               int pathlen;
7338
7339               /* Determine the length of the execd pathname.  */
7340               p = unpack_varlen_hex (++p1, &ignored);
7341               pathlen = (p - p1) / 2;
7342
7343               /* Save the pathname for event reporting and for
7344                  the next run command.  */
7345               hex2bin (p1, (gdb_byte *) pathname, pathlen);
7346               pathname[pathlen] = '\0';
7347
7348               /* This is freed during event handling.  */
7349               event->ws.value.execd_pathname = xstrdup (pathname);
7350               event->ws.kind = TARGET_WAITKIND_EXECD;
7351
7352               /* Skip the registers included in this packet, since
7353                  they may be for an architecture different from the
7354                  one used by the original program.  */
7355               skipregs = 1;
7356             }
7357           else if (strprefix (p, p1, "create"))
7358             {
7359               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7360               p = strchrnul (p1 + 1, ';');
7361             }
7362           else
7363             {
7364               ULONGEST pnum;
7365               const char *p_temp;
7366
7367               if (skipregs)
7368                 {
7369                   p = strchrnul (p1 + 1, ';');
7370                   p++;
7371                   continue;
7372                 }
7373
7374               /* Maybe a real ``P'' register number.  */
7375               p_temp = unpack_varlen_hex (p, &pnum);
7376               /* If the first invalid character is the colon, we got a
7377                  register number.  Otherwise, it's an unknown stop
7378                  reason.  */
7379               if (p_temp == p1)
7380                 {
7381                   /* If we haven't parsed the event's thread yet, find
7382                      it now, in order to find the architecture of the
7383                      reported expedited registers.  */
7384                   if (event->ptid == null_ptid)
7385                     {
7386                       const char *thr = strstr (p1 + 1, ";thread:");
7387                       if (thr != NULL)
7388                         event->ptid = read_ptid (thr + strlen (";thread:"),
7389                                                  NULL);
7390                       else
7391                         {
7392                           /* Either the current thread hasn't changed,
7393                              or the inferior is not multi-threaded.
7394                              The event must be for the thread we last
7395                              set as (or learned as being) current.  */
7396                           event->ptid = event->rs->general_thread;
7397                         }
7398                     }
7399
7400                   if (rsa == NULL)
7401                     {
7402                       inferior *inf = (event->ptid == null_ptid
7403                                        ? NULL
7404                                        : find_inferior_ptid (event->ptid));
7405                       /* If this is the first time we learn anything
7406                          about this process, skip the registers
7407                          included in this packet, since we don't yet
7408                          know which architecture to use to parse them.
7409                          We'll determine the architecture later when
7410                          we process the stop reply and retrieve the
7411                          target description, via
7412                          remote_notice_new_inferior ->
7413                          post_create_inferior.  */
7414                       if (inf == NULL)
7415                         {
7416                           p = strchrnul (p1 + 1, ';');
7417                           p++;
7418                           continue;
7419                         }
7420
7421                       event->arch = inf->gdbarch;
7422                       rsa = event->rs->get_remote_arch_state (event->arch);
7423                     }
7424
7425                   packet_reg *reg
7426                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7427                   cached_reg_t cached_reg;
7428
7429                   if (reg == NULL)
7430                     error (_("Remote sent bad register number %s: %s\n\
7431 Packet: '%s'\n"),
7432                            hex_string (pnum), p, buf);
7433
7434                   cached_reg.num = reg->regnum;
7435                   cached_reg.data = (gdb_byte *)
7436                     xmalloc (register_size (event->arch, reg->regnum));
7437
7438                   p = p1 + 1;
7439                   fieldsize = hex2bin (p, cached_reg.data,
7440                                        register_size (event->arch, reg->regnum));
7441                   p += 2 * fieldsize;
7442                   if (fieldsize < register_size (event->arch, reg->regnum))
7443                     warning (_("Remote reply is too short: %s"), buf);
7444
7445                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7446                 }
7447               else
7448                 {
7449                   /* Not a number.  Silently skip unknown optional
7450                      info.  */
7451                   p = strchrnul (p1 + 1, ';');
7452                 }
7453             }
7454
7455           if (*p != ';')
7456             error (_("Remote register badly formatted: %s\nhere: %s"),
7457                    buf, p);
7458           ++p;
7459         }
7460
7461       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7462         break;
7463
7464       /* fall through */
7465     case 'S':           /* Old style status, just signal only.  */
7466       {
7467         int sig;
7468
7469         event->ws.kind = TARGET_WAITKIND_STOPPED;
7470         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7471         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7472           event->ws.value.sig = (enum gdb_signal) sig;
7473         else
7474           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7475       }
7476       break;
7477     case 'w':           /* Thread exited.  */
7478       {
7479         const char *p;
7480         ULONGEST value;
7481
7482         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7483         p = unpack_varlen_hex (&buf[1], &value);
7484         event->ws.value.integer = value;
7485         if (*p != ';')
7486           error (_("stop reply packet badly formatted: %s"), buf);
7487         event->ptid = read_ptid (++p, NULL);
7488         break;
7489       }
7490     case 'W':           /* Target exited.  */
7491     case 'X':
7492       {
7493         const char *p;
7494         int pid;
7495         ULONGEST value;
7496
7497         /* GDB used to accept only 2 hex chars here.  Stubs should
7498            only send more if they detect GDB supports multi-process
7499            support.  */
7500         p = unpack_varlen_hex (&buf[1], &value);
7501
7502         if (buf[0] == 'W')
7503           {
7504             /* The remote process exited.  */
7505             event->ws.kind = TARGET_WAITKIND_EXITED;
7506             event->ws.value.integer = value;
7507           }
7508         else
7509           {
7510             /* The remote process exited with a signal.  */
7511             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7512             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7513               event->ws.value.sig = (enum gdb_signal) value;
7514             else
7515               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7516           }
7517
7518         /* If no process is specified, assume inferior_ptid.  */
7519         pid = inferior_ptid.pid ();
7520         if (*p == '\0')
7521           ;
7522         else if (*p == ';')
7523           {
7524             p++;
7525
7526             if (*p == '\0')
7527               ;
7528             else if (startswith (p, "process:"))
7529               {
7530                 ULONGEST upid;
7531
7532                 p += sizeof ("process:") - 1;
7533                 unpack_varlen_hex (p, &upid);
7534                 pid = upid;
7535               }
7536             else
7537               error (_("unknown stop reply packet: %s"), buf);
7538           }
7539         else
7540           error (_("unknown stop reply packet: %s"), buf);
7541         event->ptid = ptid_t (pid);
7542       }
7543       break;
7544     case 'N':
7545       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7546       event->ptid = minus_one_ptid;
7547       break;
7548     }
7549
7550   if (target_is_non_stop_p () && event->ptid == null_ptid)
7551     error (_("No process or thread specified in stop reply: %s"), buf);
7552 }
7553
7554 /* When the stub wants to tell GDB about a new notification reply, it
7555    sends a notification (%Stop, for example).  Those can come it at
7556    any time, hence, we have to make sure that any pending
7557    putpkt/getpkt sequence we're making is finished, before querying
7558    the stub for more events with the corresponding ack command
7559    (vStopped, for example).  E.g., if we started a vStopped sequence
7560    immediately upon receiving the notification, something like this
7561    could happen:
7562
7563     1.1) --> Hg 1
7564     1.2) <-- OK
7565     1.3) --> g
7566     1.4) <-- %Stop
7567     1.5) --> vStopped
7568     1.6) <-- (registers reply to step #1.3)
7569
7570    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7571    query.
7572
7573    To solve this, whenever we parse a %Stop notification successfully,
7574    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7575    doing whatever we were doing:
7576
7577     2.1) --> Hg 1
7578     2.2) <-- OK
7579     2.3) --> g
7580     2.4) <-- %Stop
7581       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7582     2.5) <-- (registers reply to step #2.3)
7583
7584    Eventualy after step #2.5, we return to the event loop, which
7585    notices there's an event on the
7586    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7587    associated callback --- the function below.  At this point, we're
7588    always safe to start a vStopped sequence. :
7589
7590     2.6) --> vStopped
7591     2.7) <-- T05 thread:2
7592     2.8) --> vStopped
7593     2.9) --> OK
7594 */
7595
7596 void
7597 remote_target::remote_notif_get_pending_events (notif_client *nc)
7598 {
7599   struct remote_state *rs = get_remote_state ();
7600
7601   if (rs->notif_state->pending_event[nc->id] != NULL)
7602     {
7603       if (notif_debug)
7604         fprintf_unfiltered (gdb_stdlog,
7605                             "notif: process: '%s' ack pending event\n",
7606                             nc->name);
7607
7608       /* acknowledge */
7609       nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7610       rs->notif_state->pending_event[nc->id] = NULL;
7611
7612       while (1)
7613         {
7614           getpkt (&rs->buf, &rs->buf_size, 0);
7615           if (strcmp (rs->buf, "OK") == 0)
7616             break;
7617           else
7618             remote_notif_ack (this, nc, rs->buf);
7619         }
7620     }
7621   else
7622     {
7623       if (notif_debug)
7624         fprintf_unfiltered (gdb_stdlog,
7625                             "notif: process: '%s' no pending reply\n",
7626                             nc->name);
7627     }
7628 }
7629
7630 /* Wrapper around remote_target::remote_notif_get_pending_events to
7631    avoid having to export the whole remote_target class.  */
7632
7633 void
7634 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7635 {
7636   remote->remote_notif_get_pending_events (nc);
7637 }
7638
7639 /* Called when it is decided that STOP_REPLY holds the info of the
7640    event that is to be returned to the core.  This function always
7641    destroys STOP_REPLY.  */
7642
7643 ptid_t
7644 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7645                                    struct target_waitstatus *status)
7646 {
7647   ptid_t ptid;
7648
7649   *status = stop_reply->ws;
7650   ptid = stop_reply->ptid;
7651
7652   /* If no thread/process was reported by the stub, assume the current
7653      inferior.  */
7654   if (ptid == null_ptid)
7655     ptid = inferior_ptid;
7656
7657   if (status->kind != TARGET_WAITKIND_EXITED
7658       && status->kind != TARGET_WAITKIND_SIGNALLED
7659       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7660     {
7661       /* Expedited registers.  */
7662       if (stop_reply->regcache)
7663         {
7664           struct regcache *regcache
7665             = get_thread_arch_regcache (ptid, stop_reply->arch);
7666           cached_reg_t *reg;
7667           int ix;
7668
7669           for (ix = 0;
7670                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7671                ix++)
7672           {
7673             regcache->raw_supply (reg->num, reg->data);
7674             xfree (reg->data);
7675           }
7676
7677           VEC_free (cached_reg_t, stop_reply->regcache);
7678         }
7679
7680       remote_notice_new_inferior (ptid, 0);
7681       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7682       remote_thr->core = stop_reply->core;
7683       remote_thr->stop_reason = stop_reply->stop_reason;
7684       remote_thr->watch_data_address = stop_reply->watch_data_address;
7685       remote_thr->vcont_resumed = 0;
7686     }
7687
7688   stop_reply_xfree (stop_reply);
7689   return ptid;
7690 }
7691
7692 /* The non-stop mode version of target_wait.  */
7693
7694 ptid_t
7695 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7696 {
7697   struct remote_state *rs = get_remote_state ();
7698   struct stop_reply *stop_reply;
7699   int ret;
7700   int is_notif = 0;
7701
7702   /* If in non-stop mode, get out of getpkt even if a
7703      notification is received.  */
7704
7705   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7706                               0 /* forever */, &is_notif);
7707   while (1)
7708     {
7709       if (ret != -1 && !is_notif)
7710         switch (rs->buf[0])
7711           {
7712           case 'E':             /* Error of some sort.  */
7713             /* We're out of sync with the target now.  Did it continue
7714                or not?  We can't tell which thread it was in non-stop,
7715                so just ignore this.  */
7716             warning (_("Remote failure reply: %s"), rs->buf);
7717             break;
7718           case 'O':             /* Console output.  */
7719             remote_console_output (rs->buf + 1);
7720             break;
7721           default:
7722             warning (_("Invalid remote reply: %s"), rs->buf);
7723             break;
7724           }
7725
7726       /* Acknowledge a pending stop reply that may have arrived in the
7727          mean time.  */
7728       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7729         remote_notif_get_pending_events (&notif_client_stop);
7730
7731       /* If indeed we noticed a stop reply, we're done.  */
7732       stop_reply = queued_stop_reply (ptid);
7733       if (stop_reply != NULL)
7734         return process_stop_reply (stop_reply, status);
7735
7736       /* Still no event.  If we're just polling for an event, then
7737          return to the event loop.  */
7738       if (options & TARGET_WNOHANG)
7739         {
7740           status->kind = TARGET_WAITKIND_IGNORE;
7741           return minus_one_ptid;
7742         }
7743
7744       /* Otherwise do a blocking wait.  */
7745       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7746                                   1 /* forever */, &is_notif);
7747     }
7748 }
7749
7750 /* Wait until the remote machine stops, then return, storing status in
7751    STATUS just as `wait' would.  */
7752
7753 ptid_t
7754 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7755 {
7756   struct remote_state *rs = get_remote_state ();
7757   ptid_t event_ptid = null_ptid;
7758   char *buf;
7759   struct stop_reply *stop_reply;
7760
7761  again:
7762
7763   status->kind = TARGET_WAITKIND_IGNORE;
7764   status->value.integer = 0;
7765
7766   stop_reply = queued_stop_reply (ptid);
7767   if (stop_reply != NULL)
7768     return process_stop_reply (stop_reply, status);
7769
7770   if (rs->cached_wait_status)
7771     /* Use the cached wait status, but only once.  */
7772     rs->cached_wait_status = 0;
7773   else
7774     {
7775       int ret;
7776       int is_notif;
7777       int forever = ((options & TARGET_WNOHANG) == 0
7778                      && rs->wait_forever_enabled_p);
7779
7780       if (!rs->waiting_for_stop_reply)
7781         {
7782           status->kind = TARGET_WAITKIND_NO_RESUMED;
7783           return minus_one_ptid;
7784         }
7785
7786       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7787          _never_ wait for ever -> test on target_is_async_p().
7788          However, before we do that we need to ensure that the caller
7789          knows how to take the target into/out of async mode.  */
7790       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7791                                   forever, &is_notif);
7792
7793       /* GDB gets a notification.  Return to core as this event is
7794          not interesting.  */
7795       if (ret != -1 && is_notif)
7796         return minus_one_ptid;
7797
7798       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7799         return minus_one_ptid;
7800     }
7801
7802   buf = rs->buf;
7803
7804   /* Assume that the target has acknowledged Ctrl-C unless we receive
7805      an 'F' or 'O' packet.  */
7806   if (buf[0] != 'F' && buf[0] != 'O')
7807     rs->ctrlc_pending_p = 0;
7808
7809   switch (buf[0])
7810     {
7811     case 'E':           /* Error of some sort.  */
7812       /* We're out of sync with the target now.  Did it continue or
7813          not?  Not is more likely, so report a stop.  */
7814       rs->waiting_for_stop_reply = 0;
7815
7816       warning (_("Remote failure reply: %s"), buf);
7817       status->kind = TARGET_WAITKIND_STOPPED;
7818       status->value.sig = GDB_SIGNAL_0;
7819       break;
7820     case 'F':           /* File-I/O request.  */
7821       /* GDB may access the inferior memory while handling the File-I/O
7822          request, but we don't want GDB accessing memory while waiting
7823          for a stop reply.  See the comments in putpkt_binary.  Set
7824          waiting_for_stop_reply to 0 temporarily.  */
7825       rs->waiting_for_stop_reply = 0;
7826       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7827       rs->ctrlc_pending_p = 0;
7828       /* GDB handled the File-I/O request, and the target is running
7829          again.  Keep waiting for events.  */
7830       rs->waiting_for_stop_reply = 1;
7831       break;
7832     case 'N': case 'T': case 'S': case 'X': case 'W':
7833       {
7834         struct stop_reply *stop_reply;
7835
7836         /* There is a stop reply to handle.  */
7837         rs->waiting_for_stop_reply = 0;
7838
7839         stop_reply
7840           = (struct stop_reply *) remote_notif_parse (this,
7841                                                       &notif_client_stop,
7842                                                       rs->buf);
7843
7844         event_ptid = process_stop_reply (stop_reply, status);
7845         break;
7846       }
7847     case 'O':           /* Console output.  */
7848       remote_console_output (buf + 1);
7849       break;
7850     case '\0':
7851       if (rs->last_sent_signal != GDB_SIGNAL_0)
7852         {
7853           /* Zero length reply means that we tried 'S' or 'C' and the
7854              remote system doesn't support it.  */
7855           target_terminal::ours_for_output ();
7856           printf_filtered
7857             ("Can't send signals to this remote system.  %s not sent.\n",
7858              gdb_signal_to_name (rs->last_sent_signal));
7859           rs->last_sent_signal = GDB_SIGNAL_0;
7860           target_terminal::inferior ();
7861
7862           strcpy (buf, rs->last_sent_step ? "s" : "c");
7863           putpkt (buf);
7864           break;
7865         }
7866       /* fallthrough */
7867     default:
7868       warning (_("Invalid remote reply: %s"), buf);
7869       break;
7870     }
7871
7872   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7873     return minus_one_ptid;
7874   else if (status->kind == TARGET_WAITKIND_IGNORE)
7875     {
7876       /* Nothing interesting happened.  If we're doing a non-blocking
7877          poll, we're done.  Otherwise, go back to waiting.  */
7878       if (options & TARGET_WNOHANG)
7879         return minus_one_ptid;
7880       else
7881         goto again;
7882     }
7883   else if (status->kind != TARGET_WAITKIND_EXITED
7884            && status->kind != TARGET_WAITKIND_SIGNALLED)
7885     {
7886       if (event_ptid != null_ptid)
7887         record_currthread (rs, event_ptid);
7888       else
7889         event_ptid = inferior_ptid;
7890     }
7891   else
7892     /* A process exit.  Invalidate our notion of current thread.  */
7893     record_currthread (rs, minus_one_ptid);
7894
7895   return event_ptid;
7896 }
7897
7898 /* Wait until the remote machine stops, then return, storing status in
7899    STATUS just as `wait' would.  */
7900
7901 ptid_t
7902 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7903 {
7904   ptid_t event_ptid;
7905
7906   if (target_is_non_stop_p ())
7907     event_ptid = wait_ns (ptid, status, options);
7908   else
7909     event_ptid = wait_as (ptid, status, options);
7910
7911   if (target_is_async_p ())
7912     {
7913       remote_state *rs = get_remote_state ();
7914
7915       /* If there are are events left in the queue tell the event loop
7916          to return here.  */
7917       if (!rs->stop_reply_queue.empty ())
7918         mark_async_event_handler (rs->remote_async_inferior_event_token);
7919     }
7920
7921   return event_ptid;
7922 }
7923
7924 /* Fetch a single register using a 'p' packet.  */
7925
7926 int
7927 remote_target::fetch_register_using_p (struct regcache *regcache,
7928                                        packet_reg *reg)
7929 {
7930   struct gdbarch *gdbarch = regcache->arch ();
7931   struct remote_state *rs = get_remote_state ();
7932   char *buf, *p;
7933   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7934   int i;
7935
7936   if (packet_support (PACKET_p) == PACKET_DISABLE)
7937     return 0;
7938
7939   if (reg->pnum == -1)
7940     return 0;
7941
7942   p = rs->buf;
7943   *p++ = 'p';
7944   p += hexnumstr (p, reg->pnum);
7945   *p++ = '\0';
7946   putpkt (rs->buf);
7947   getpkt (&rs->buf, &rs->buf_size, 0);
7948
7949   buf = rs->buf;
7950
7951   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7952     {
7953     case PACKET_OK:
7954       break;
7955     case PACKET_UNKNOWN:
7956       return 0;
7957     case PACKET_ERROR:
7958       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7959              gdbarch_register_name (regcache->arch (), 
7960                                     reg->regnum), 
7961              buf);
7962     }
7963
7964   /* If this register is unfetchable, tell the regcache.  */
7965   if (buf[0] == 'x')
7966     {
7967       regcache->raw_supply (reg->regnum, NULL);
7968       return 1;
7969     }
7970
7971   /* Otherwise, parse and supply the value.  */
7972   p = buf;
7973   i = 0;
7974   while (p[0] != 0)
7975     {
7976       if (p[1] == 0)
7977         error (_("fetch_register_using_p: early buf termination"));
7978
7979       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7980       p += 2;
7981     }
7982   regcache->raw_supply (reg->regnum, regp);
7983   return 1;
7984 }
7985
7986 /* Fetch the registers included in the target's 'g' packet.  */
7987
7988 int
7989 remote_target::send_g_packet ()
7990 {
7991   struct remote_state *rs = get_remote_state ();
7992   int buf_len;
7993
7994   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7995   putpkt (rs->buf);
7996   getpkt (&rs->buf, &rs->buf_size, 0);
7997   if (packet_check_result (rs->buf) == PACKET_ERROR)
7998     error (_("Could not read registers; remote failure reply '%s'"),
7999            rs->buf);
8000
8001   /* We can get out of synch in various cases.  If the first character
8002      in the buffer is not a hex character, assume that has happened
8003      and try to fetch another packet to read.  */
8004   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8005          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8006          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8007          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
8008     {
8009       if (remote_debug)
8010         fprintf_unfiltered (gdb_stdlog,
8011                             "Bad register packet; fetching a new packet\n");
8012       getpkt (&rs->buf, &rs->buf_size, 0);
8013     }
8014
8015   buf_len = strlen (rs->buf);
8016
8017   /* Sanity check the received packet.  */
8018   if (buf_len % 2 != 0)
8019     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8020
8021   return buf_len / 2;
8022 }
8023
8024 void
8025 remote_target::process_g_packet (struct regcache *regcache)
8026 {
8027   struct gdbarch *gdbarch = regcache->arch ();
8028   struct remote_state *rs = get_remote_state ();
8029   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8030   int i, buf_len;
8031   char *p;
8032   char *regs;
8033
8034   buf_len = strlen (rs->buf);
8035
8036   /* Further sanity checks, with knowledge of the architecture.  */
8037   if (buf_len > 2 * rsa->sizeof_g_packet)
8038     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8039              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8040
8041   /* Save the size of the packet sent to us by the target.  It is used
8042      as a heuristic when determining the max size of packets that the
8043      target can safely receive.  */
8044   if (rsa->actual_register_packet_size == 0)
8045     rsa->actual_register_packet_size = buf_len;
8046
8047   /* If this is smaller than we guessed the 'g' packet would be,
8048      update our records.  A 'g' reply that doesn't include a register's
8049      value implies either that the register is not available, or that
8050      the 'p' packet must be used.  */
8051   if (buf_len < 2 * rsa->sizeof_g_packet)
8052     {
8053       long sizeof_g_packet = buf_len / 2;
8054
8055       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8056         {
8057           long offset = rsa->regs[i].offset;
8058           long reg_size = register_size (gdbarch, i);
8059
8060           if (rsa->regs[i].pnum == -1)
8061             continue;
8062
8063           if (offset >= sizeof_g_packet)
8064             rsa->regs[i].in_g_packet = 0;
8065           else if (offset + reg_size > sizeof_g_packet)
8066             error (_("Truncated register %d in remote 'g' packet"), i);
8067           else
8068             rsa->regs[i].in_g_packet = 1;
8069         }
8070
8071       /* Looks valid enough, we can assume this is the correct length
8072          for a 'g' packet.  It's important not to adjust
8073          rsa->sizeof_g_packet if we have truncated registers otherwise
8074          this "if" won't be run the next time the method is called
8075          with a packet of the same size and one of the internal errors
8076          below will trigger instead.  */
8077       rsa->sizeof_g_packet = sizeof_g_packet;
8078     }
8079
8080   regs = (char *) alloca (rsa->sizeof_g_packet);
8081
8082   /* Unimplemented registers read as all bits zero.  */
8083   memset (regs, 0, rsa->sizeof_g_packet);
8084
8085   /* Reply describes registers byte by byte, each byte encoded as two
8086      hex characters.  Suck them all up, then supply them to the
8087      register cacheing/storage mechanism.  */
8088
8089   p = rs->buf;
8090   for (i = 0; i < rsa->sizeof_g_packet; i++)
8091     {
8092       if (p[0] == 0 || p[1] == 0)
8093         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
8094         internal_error (__FILE__, __LINE__,
8095                         _("unexpected end of 'g' packet reply"));
8096
8097       if (p[0] == 'x' && p[1] == 'x')
8098         regs[i] = 0;            /* 'x' */
8099       else
8100         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8101       p += 2;
8102     }
8103
8104   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8105     {
8106       struct packet_reg *r = &rsa->regs[i];
8107       long reg_size = register_size (gdbarch, i);
8108
8109       if (r->in_g_packet)
8110         {
8111           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8112             /* This shouldn't happen - we adjusted in_g_packet above.  */
8113             internal_error (__FILE__, __LINE__,
8114                             _("unexpected end of 'g' packet reply"));
8115           else if (rs->buf[r->offset * 2] == 'x')
8116             {
8117               gdb_assert (r->offset * 2 < strlen (rs->buf));
8118               /* The register isn't available, mark it as such (at
8119                  the same time setting the value to zero).  */
8120               regcache->raw_supply (r->regnum, NULL);
8121             }
8122           else
8123             regcache->raw_supply (r->regnum, regs + r->offset);
8124         }
8125     }
8126 }
8127
8128 void
8129 remote_target::fetch_registers_using_g (struct regcache *regcache)
8130 {
8131   send_g_packet ();
8132   process_g_packet (regcache);
8133 }
8134
8135 /* Make the remote selected traceframe match GDB's selected
8136    traceframe.  */
8137
8138 void
8139 remote_target::set_remote_traceframe ()
8140 {
8141   int newnum;
8142   struct remote_state *rs = get_remote_state ();
8143
8144   if (rs->remote_traceframe_number == get_traceframe_number ())
8145     return;
8146
8147   /* Avoid recursion, remote_trace_find calls us again.  */
8148   rs->remote_traceframe_number = get_traceframe_number ();
8149
8150   newnum = target_trace_find (tfind_number,
8151                               get_traceframe_number (), 0, 0, NULL);
8152
8153   /* Should not happen.  If it does, all bets are off.  */
8154   if (newnum != get_traceframe_number ())
8155     warning (_("could not set remote traceframe"));
8156 }
8157
8158 void
8159 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8160 {
8161   struct gdbarch *gdbarch = regcache->arch ();
8162   struct remote_state *rs = get_remote_state ();
8163   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8164   int i;
8165
8166   set_remote_traceframe ();
8167   set_general_thread (regcache->ptid ());
8168
8169   if (regnum >= 0)
8170     {
8171       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8172
8173       gdb_assert (reg != NULL);
8174
8175       /* If this register might be in the 'g' packet, try that first -
8176          we are likely to read more than one register.  If this is the
8177          first 'g' packet, we might be overly optimistic about its
8178          contents, so fall back to 'p'.  */
8179       if (reg->in_g_packet)
8180         {
8181           fetch_registers_using_g (regcache);
8182           if (reg->in_g_packet)
8183             return;
8184         }
8185
8186       if (fetch_register_using_p (regcache, reg))
8187         return;
8188
8189       /* This register is not available.  */
8190       regcache->raw_supply (reg->regnum, NULL);
8191
8192       return;
8193     }
8194
8195   fetch_registers_using_g (regcache);
8196
8197   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8198     if (!rsa->regs[i].in_g_packet)
8199       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8200         {
8201           /* This register is not available.  */
8202           regcache->raw_supply (i, NULL);
8203         }
8204 }
8205
8206 /* Prepare to store registers.  Since we may send them all (using a
8207    'G' request), we have to read out the ones we don't want to change
8208    first.  */
8209
8210 void
8211 remote_target::prepare_to_store (struct regcache *regcache)
8212 {
8213   struct remote_state *rs = get_remote_state ();
8214   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8215   int i;
8216
8217   /* Make sure the entire registers array is valid.  */
8218   switch (packet_support (PACKET_P))
8219     {
8220     case PACKET_DISABLE:
8221     case PACKET_SUPPORT_UNKNOWN:
8222       /* Make sure all the necessary registers are cached.  */
8223       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8224         if (rsa->regs[i].in_g_packet)
8225           regcache->raw_update (rsa->regs[i].regnum);
8226       break;
8227     case PACKET_ENABLE:
8228       break;
8229     }
8230 }
8231
8232 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8233    packet was not recognized.  */
8234
8235 int
8236 remote_target::store_register_using_P (const struct regcache *regcache,
8237                                        packet_reg *reg)
8238 {
8239   struct gdbarch *gdbarch = regcache->arch ();
8240   struct remote_state *rs = get_remote_state ();
8241   /* Try storing a single register.  */
8242   char *buf = rs->buf;
8243   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8244   char *p;
8245
8246   if (packet_support (PACKET_P) == PACKET_DISABLE)
8247     return 0;
8248
8249   if (reg->pnum == -1)
8250     return 0;
8251
8252   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8253   p = buf + strlen (buf);
8254   regcache->raw_collect (reg->regnum, regp);
8255   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8256   putpkt (rs->buf);
8257   getpkt (&rs->buf, &rs->buf_size, 0);
8258
8259   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8260     {
8261     case PACKET_OK:
8262       return 1;
8263     case PACKET_ERROR:
8264       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8265              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8266     case PACKET_UNKNOWN:
8267       return 0;
8268     default:
8269       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8270     }
8271 }
8272
8273 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8274    contents of the register cache buffer.  FIXME: ignores errors.  */
8275
8276 void
8277 remote_target::store_registers_using_G (const struct regcache *regcache)
8278 {
8279   struct remote_state *rs = get_remote_state ();
8280   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8281   gdb_byte *regs;
8282   char *p;
8283
8284   /* Extract all the registers in the regcache copying them into a
8285      local buffer.  */
8286   {
8287     int i;
8288
8289     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8290     memset (regs, 0, rsa->sizeof_g_packet);
8291     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8292       {
8293         struct packet_reg *r = &rsa->regs[i];
8294
8295         if (r->in_g_packet)
8296           regcache->raw_collect (r->regnum, regs + r->offset);
8297       }
8298   }
8299
8300   /* Command describes registers byte by byte,
8301      each byte encoded as two hex characters.  */
8302   p = rs->buf;
8303   *p++ = 'G';
8304   bin2hex (regs, p, rsa->sizeof_g_packet);
8305   putpkt (rs->buf);
8306   getpkt (&rs->buf, &rs->buf_size, 0);
8307   if (packet_check_result (rs->buf) == PACKET_ERROR)
8308     error (_("Could not write registers; remote failure reply '%s'"), 
8309            rs->buf);
8310 }
8311
8312 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8313    of the register cache buffer.  FIXME: ignores errors.  */
8314
8315 void
8316 remote_target::store_registers (struct regcache *regcache, int regnum)
8317 {
8318   struct gdbarch *gdbarch = regcache->arch ();
8319   struct remote_state *rs = get_remote_state ();
8320   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8321   int i;
8322
8323   set_remote_traceframe ();
8324   set_general_thread (regcache->ptid ());
8325
8326   if (regnum >= 0)
8327     {
8328       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8329
8330       gdb_assert (reg != NULL);
8331
8332       /* Always prefer to store registers using the 'P' packet if
8333          possible; we often change only a small number of registers.
8334          Sometimes we change a larger number; we'd need help from a
8335          higher layer to know to use 'G'.  */
8336       if (store_register_using_P (regcache, reg))
8337         return;
8338
8339       /* For now, don't complain if we have no way to write the
8340          register.  GDB loses track of unavailable registers too
8341          easily.  Some day, this may be an error.  We don't have
8342          any way to read the register, either...  */
8343       if (!reg->in_g_packet)
8344         return;
8345
8346       store_registers_using_G (regcache);
8347       return;
8348     }
8349
8350   store_registers_using_G (regcache);
8351
8352   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8353     if (!rsa->regs[i].in_g_packet)
8354       if (!store_register_using_P (regcache, &rsa->regs[i]))
8355         /* See above for why we do not issue an error here.  */
8356         continue;
8357 }
8358 \f
8359
8360 /* Return the number of hex digits in num.  */
8361
8362 static int
8363 hexnumlen (ULONGEST num)
8364 {
8365   int i;
8366
8367   for (i = 0; num != 0; i++)
8368     num >>= 4;
8369
8370   return std::max (i, 1);
8371 }
8372
8373 /* Set BUF to the minimum number of hex digits representing NUM.  */
8374
8375 static int
8376 hexnumstr (char *buf, ULONGEST num)
8377 {
8378   int len = hexnumlen (num);
8379
8380   return hexnumnstr (buf, num, len);
8381 }
8382
8383
8384 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8385
8386 static int
8387 hexnumnstr (char *buf, ULONGEST num, int width)
8388 {
8389   int i;
8390
8391   buf[width] = '\0';
8392
8393   for (i = width - 1; i >= 0; i--)
8394     {
8395       buf[i] = "0123456789abcdef"[(num & 0xf)];
8396       num >>= 4;
8397     }
8398
8399   return width;
8400 }
8401
8402 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8403
8404 static CORE_ADDR
8405 remote_address_masked (CORE_ADDR addr)
8406 {
8407   unsigned int address_size = remote_address_size;
8408
8409   /* If "remoteaddresssize" was not set, default to target address size.  */
8410   if (!address_size)
8411     address_size = gdbarch_addr_bit (target_gdbarch ());
8412
8413   if (address_size > 0
8414       && address_size < (sizeof (ULONGEST) * 8))
8415     {
8416       /* Only create a mask when that mask can safely be constructed
8417          in a ULONGEST variable.  */
8418       ULONGEST mask = 1;
8419
8420       mask = (mask << address_size) - 1;
8421       addr &= mask;
8422     }
8423   return addr;
8424 }
8425
8426 /* Determine whether the remote target supports binary downloading.
8427    This is accomplished by sending a no-op memory write of zero length
8428    to the target at the specified address. It does not suffice to send
8429    the whole packet, since many stubs strip the eighth bit and
8430    subsequently compute a wrong checksum, which causes real havoc with
8431    remote_write_bytes.
8432
8433    NOTE: This can still lose if the serial line is not eight-bit
8434    clean.  In cases like this, the user should clear "remote
8435    X-packet".  */
8436
8437 void
8438 remote_target::check_binary_download (CORE_ADDR addr)
8439 {
8440   struct remote_state *rs = get_remote_state ();
8441
8442   switch (packet_support (PACKET_X))
8443     {
8444     case PACKET_DISABLE:
8445       break;
8446     case PACKET_ENABLE:
8447       break;
8448     case PACKET_SUPPORT_UNKNOWN:
8449       {
8450         char *p;
8451
8452         p = rs->buf;
8453         *p++ = 'X';
8454         p += hexnumstr (p, (ULONGEST) addr);
8455         *p++ = ',';
8456         p += hexnumstr (p, (ULONGEST) 0);
8457         *p++ = ':';
8458         *p = '\0';
8459
8460         putpkt_binary (rs->buf, (int) (p - rs->buf));
8461         getpkt (&rs->buf, &rs->buf_size, 0);
8462
8463         if (rs->buf[0] == '\0')
8464           {
8465             if (remote_debug)
8466               fprintf_unfiltered (gdb_stdlog,
8467                                   "binary downloading NOT "
8468                                   "supported by target\n");
8469             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8470           }
8471         else
8472           {
8473             if (remote_debug)
8474               fprintf_unfiltered (gdb_stdlog,
8475                                   "binary downloading supported by target\n");
8476             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8477           }
8478         break;
8479       }
8480     }
8481 }
8482
8483 /* Helper function to resize the payload in order to try to get a good
8484    alignment.  We try to write an amount of data such that the next write will
8485    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8486
8487 static int
8488 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8489 {
8490   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8491 }
8492
8493 /* Write memory data directly to the remote machine.
8494    This does not inform the data cache; the data cache uses this.
8495    HEADER is the starting part of the packet.
8496    MEMADDR is the address in the remote memory space.
8497    MYADDR is the address of the buffer in our space.
8498    LEN_UNITS is the number of addressable units to write.
8499    UNIT_SIZE is the length in bytes of an addressable unit.
8500    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8501    should send data as binary ('X'), or hex-encoded ('M').
8502
8503    The function creates packet of the form
8504        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8505
8506    where encoding of <DATA> is terminated by PACKET_FORMAT.
8507
8508    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8509    are omitted.
8510
8511    Return the transferred status, error or OK (an
8512    'enum target_xfer_status' value).  Save the number of addressable units
8513    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8514
8515    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8516    exchange between gdb and the stub could look like (?? in place of the
8517    checksum):
8518
8519    -> $m1000,4#??
8520    <- aaaabbbbccccdddd
8521
8522    -> $M1000,3:eeeeffffeeee#??
8523    <- OK
8524
8525    -> $m1000,4#??
8526    <- eeeeffffeeeedddd  */
8527
8528 target_xfer_status
8529 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8530                                        const gdb_byte *myaddr,
8531                                        ULONGEST len_units,
8532                                        int unit_size,
8533                                        ULONGEST *xfered_len_units,
8534                                        char packet_format, int use_length)
8535 {
8536   struct remote_state *rs = get_remote_state ();
8537   char *p;
8538   char *plen = NULL;
8539   int plenlen = 0;
8540   int todo_units;
8541   int units_written;
8542   int payload_capacity_bytes;
8543   int payload_length_bytes;
8544
8545   if (packet_format != 'X' && packet_format != 'M')
8546     internal_error (__FILE__, __LINE__,
8547                     _("remote_write_bytes_aux: bad packet format"));
8548
8549   if (len_units == 0)
8550     return TARGET_XFER_EOF;
8551
8552   payload_capacity_bytes = get_memory_write_packet_size ();
8553
8554   /* The packet buffer will be large enough for the payload;
8555      get_memory_packet_size ensures this.  */
8556   rs->buf[0] = '\0';
8557
8558   /* Compute the size of the actual payload by subtracting out the
8559      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8560
8561   payload_capacity_bytes -= strlen ("$,:#NN");
8562   if (!use_length)
8563     /* The comma won't be used.  */
8564     payload_capacity_bytes += 1;
8565   payload_capacity_bytes -= strlen (header);
8566   payload_capacity_bytes -= hexnumlen (memaddr);
8567
8568   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8569
8570   strcat (rs->buf, header);
8571   p = rs->buf + strlen (header);
8572
8573   /* Compute a best guess of the number of bytes actually transfered.  */
8574   if (packet_format == 'X')
8575     {
8576       /* Best guess at number of bytes that will fit.  */
8577       todo_units = std::min (len_units,
8578                              (ULONGEST) payload_capacity_bytes / unit_size);
8579       if (use_length)
8580         payload_capacity_bytes -= hexnumlen (todo_units);
8581       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8582     }
8583   else
8584     {
8585       /* Number of bytes that will fit.  */
8586       todo_units
8587         = std::min (len_units,
8588                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8589       if (use_length)
8590         payload_capacity_bytes -= hexnumlen (todo_units);
8591       todo_units = std::min (todo_units,
8592                              (payload_capacity_bytes / unit_size) / 2);
8593     }
8594
8595   if (todo_units <= 0)
8596     internal_error (__FILE__, __LINE__,
8597                     _("minimum packet size too small to write data"));
8598
8599   /* If we already need another packet, then try to align the end
8600      of this packet to a useful boundary.  */
8601   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8602     todo_units = align_for_efficient_write (todo_units, memaddr);
8603
8604   /* Append "<memaddr>".  */
8605   memaddr = remote_address_masked (memaddr);
8606   p += hexnumstr (p, (ULONGEST) memaddr);
8607
8608   if (use_length)
8609     {
8610       /* Append ",".  */
8611       *p++ = ',';
8612
8613       /* Append the length and retain its location and size.  It may need to be
8614          adjusted once the packet body has been created.  */
8615       plen = p;
8616       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8617       p += plenlen;
8618     }
8619
8620   /* Append ":".  */
8621   *p++ = ':';
8622   *p = '\0';
8623
8624   /* Append the packet body.  */
8625   if (packet_format == 'X')
8626     {
8627       /* Binary mode.  Send target system values byte by byte, in
8628          increasing byte addresses.  Only escape certain critical
8629          characters.  */
8630       payload_length_bytes =
8631           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8632                                 &units_written, payload_capacity_bytes);
8633
8634       /* If not all TODO units fit, then we'll need another packet.  Make
8635          a second try to keep the end of the packet aligned.  Don't do
8636          this if the packet is tiny.  */
8637       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8638         {
8639           int new_todo_units;
8640
8641           new_todo_units = align_for_efficient_write (units_written, memaddr);
8642
8643           if (new_todo_units != units_written)
8644             payload_length_bytes =
8645                 remote_escape_output (myaddr, new_todo_units, unit_size,
8646                                       (gdb_byte *) p, &units_written,
8647                                       payload_capacity_bytes);
8648         }
8649
8650       p += payload_length_bytes;
8651       if (use_length && units_written < todo_units)
8652         {
8653           /* Escape chars have filled up the buffer prematurely,
8654              and we have actually sent fewer units than planned.
8655              Fix-up the length field of the packet.  Use the same
8656              number of characters as before.  */
8657           plen += hexnumnstr (plen, (ULONGEST) units_written,
8658                               plenlen);
8659           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8660         }
8661     }
8662   else
8663     {
8664       /* Normal mode: Send target system values byte by byte, in
8665          increasing byte addresses.  Each byte is encoded as a two hex
8666          value.  */
8667       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8668       units_written = todo_units;
8669     }
8670
8671   putpkt_binary (rs->buf, (int) (p - rs->buf));
8672   getpkt (&rs->buf, &rs->buf_size, 0);
8673
8674   if (rs->buf[0] == 'E')
8675     return TARGET_XFER_E_IO;
8676
8677   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8678      send fewer units than we'd planned.  */
8679   *xfered_len_units = (ULONGEST) units_written;
8680   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8681 }
8682
8683 /* Write memory data directly to the remote machine.
8684    This does not inform the data cache; the data cache uses this.
8685    MEMADDR is the address in the remote memory space.
8686    MYADDR is the address of the buffer in our space.
8687    LEN is the number of bytes.
8688
8689    Return the transferred status, error or OK (an
8690    'enum target_xfer_status' value).  Save the number of bytes
8691    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8692
8693 target_xfer_status
8694 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8695                                    ULONGEST len, int unit_size,
8696                                    ULONGEST *xfered_len)
8697 {
8698   const char *packet_format = NULL;
8699
8700   /* Check whether the target supports binary download.  */
8701   check_binary_download (memaddr);
8702
8703   switch (packet_support (PACKET_X))
8704     {
8705     case PACKET_ENABLE:
8706       packet_format = "X";
8707       break;
8708     case PACKET_DISABLE:
8709       packet_format = "M";
8710       break;
8711     case PACKET_SUPPORT_UNKNOWN:
8712       internal_error (__FILE__, __LINE__,
8713                       _("remote_write_bytes: bad internal state"));
8714     default:
8715       internal_error (__FILE__, __LINE__, _("bad switch"));
8716     }
8717
8718   return remote_write_bytes_aux (packet_format,
8719                                  memaddr, myaddr, len, unit_size, xfered_len,
8720                                  packet_format[0], 1);
8721 }
8722
8723 /* Read memory data directly from the remote machine.
8724    This does not use the data cache; the data cache uses this.
8725    MEMADDR is the address in the remote memory space.
8726    MYADDR is the address of the buffer in our space.
8727    LEN_UNITS is the number of addressable memory units to read..
8728    UNIT_SIZE is the length in bytes of an addressable unit.
8729
8730    Return the transferred status, error or OK (an
8731    'enum target_xfer_status' value).  Save the number of bytes
8732    transferred in *XFERED_LEN_UNITS.
8733
8734    See the comment of remote_write_bytes_aux for an example of
8735    memory read/write exchange between gdb and the stub.  */
8736
8737 target_xfer_status
8738 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8739                                     ULONGEST len_units,
8740                                     int unit_size, ULONGEST *xfered_len_units)
8741 {
8742   struct remote_state *rs = get_remote_state ();
8743   int buf_size_bytes;           /* Max size of packet output buffer.  */
8744   char *p;
8745   int todo_units;
8746   int decoded_bytes;
8747
8748   buf_size_bytes = get_memory_read_packet_size ();
8749   /* The packet buffer will be large enough for the payload;
8750      get_memory_packet_size ensures this.  */
8751
8752   /* Number of units that will fit.  */
8753   todo_units = std::min (len_units,
8754                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8755
8756   /* Construct "m"<memaddr>","<len>".  */
8757   memaddr = remote_address_masked (memaddr);
8758   p = rs->buf;
8759   *p++ = 'm';
8760   p += hexnumstr (p, (ULONGEST) memaddr);
8761   *p++ = ',';
8762   p += hexnumstr (p, (ULONGEST) todo_units);
8763   *p = '\0';
8764   putpkt (rs->buf);
8765   getpkt (&rs->buf, &rs->buf_size, 0);
8766   if (rs->buf[0] == 'E'
8767       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8768       && rs->buf[3] == '\0')
8769     return TARGET_XFER_E_IO;
8770   /* Reply describes memory byte by byte, each byte encoded as two hex
8771      characters.  */
8772   p = rs->buf;
8773   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8774   /* Return what we have.  Let higher layers handle partial reads.  */
8775   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8776   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8777 }
8778
8779 /* Using the set of read-only target sections of remote, read live
8780    read-only memory.
8781
8782    For interface/parameters/return description see target.h,
8783    to_xfer_partial.  */
8784
8785 target_xfer_status
8786 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8787                                                   ULONGEST memaddr,
8788                                                   ULONGEST len,
8789                                                   int unit_size,
8790                                                   ULONGEST *xfered_len)
8791 {
8792   struct target_section *secp;
8793   struct target_section_table *table;
8794
8795   secp = target_section_by_addr (this, memaddr);
8796   if (secp != NULL
8797       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8798                                  secp->the_bfd_section)
8799           & SEC_READONLY))
8800     {
8801       struct target_section *p;
8802       ULONGEST memend = memaddr + len;
8803
8804       table = target_get_section_table (this);
8805
8806       for (p = table->sections; p < table->sections_end; p++)
8807         {
8808           if (memaddr >= p->addr)
8809             {
8810               if (memend <= p->endaddr)
8811                 {
8812                   /* Entire transfer is within this section.  */
8813                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8814                                               xfered_len);
8815                 }
8816               else if (memaddr >= p->endaddr)
8817                 {
8818                   /* This section ends before the transfer starts.  */
8819                   continue;
8820                 }
8821               else
8822                 {
8823                   /* This section overlaps the transfer.  Just do half.  */
8824                   len = p->endaddr - memaddr;
8825                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8826                                               xfered_len);
8827                 }
8828             }
8829         }
8830     }
8831
8832   return TARGET_XFER_EOF;
8833 }
8834
8835 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8836    first if the requested memory is unavailable in traceframe.
8837    Otherwise, fall back to remote_read_bytes_1.  */
8838
8839 target_xfer_status
8840 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8841                                   gdb_byte *myaddr, ULONGEST len, int unit_size,
8842                                   ULONGEST *xfered_len)
8843 {
8844   if (len == 0)
8845     return TARGET_XFER_EOF;
8846
8847   if (get_traceframe_number () != -1)
8848     {
8849       std::vector<mem_range> available;
8850
8851       /* If we fail to get the set of available memory, then the
8852          target does not support querying traceframe info, and so we
8853          attempt reading from the traceframe anyway (assuming the
8854          target implements the old QTro packet then).  */
8855       if (traceframe_available_memory (&available, memaddr, len))
8856         {
8857           if (available.empty () || available[0].start != memaddr)
8858             {
8859               enum target_xfer_status res;
8860
8861               /* Don't read into the traceframe's available
8862                  memory.  */
8863               if (!available.empty ())
8864                 {
8865                   LONGEST oldlen = len;
8866
8867                   len = available[0].start - memaddr;
8868                   gdb_assert (len <= oldlen);
8869                 }
8870
8871               /* This goes through the topmost target again.  */
8872               res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8873                                                        len, unit_size, xfered_len);
8874               if (res == TARGET_XFER_OK)
8875                 return TARGET_XFER_OK;
8876               else
8877                 {
8878                   /* No use trying further, we know some memory starting
8879                      at MEMADDR isn't available.  */
8880                   *xfered_len = len;
8881                   return (*xfered_len != 0) ?
8882                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8883                 }
8884             }
8885
8886           /* Don't try to read more than how much is available, in
8887              case the target implements the deprecated QTro packet to
8888              cater for older GDBs (the target's knowledge of read-only
8889              sections may be outdated by now).  */
8890           len = available[0].length;
8891         }
8892     }
8893
8894   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8895 }
8896
8897 \f
8898
8899 /* Sends a packet with content determined by the printf format string
8900    FORMAT and the remaining arguments, then gets the reply.  Returns
8901    whether the packet was a success, a failure, or unknown.  */
8902
8903 packet_result
8904 remote_target::remote_send_printf (const char *format, ...)
8905 {
8906   struct remote_state *rs = get_remote_state ();
8907   int max_size = get_remote_packet_size ();
8908   va_list ap;
8909
8910   va_start (ap, format);
8911
8912   rs->buf[0] = '\0';
8913   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8914     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8915
8916   if (putpkt (rs->buf) < 0)
8917     error (_("Communication problem with target."));
8918
8919   rs->buf[0] = '\0';
8920   getpkt (&rs->buf, &rs->buf_size, 0);
8921
8922   return packet_check_result (rs->buf);
8923 }
8924
8925 /* Flash writing can take quite some time.  We'll set
8926    effectively infinite timeout for flash operations.
8927    In future, we'll need to decide on a better approach.  */
8928 static const int remote_flash_timeout = 1000;
8929
8930 void
8931 remote_target::flash_erase (ULONGEST address, LONGEST length)
8932 {
8933   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8934   enum packet_result ret;
8935   scoped_restore restore_timeout
8936     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8937
8938   ret = remote_send_printf ("vFlashErase:%s,%s",
8939                             phex (address, addr_size),
8940                             phex (length, 4));
8941   switch (ret)
8942     {
8943     case PACKET_UNKNOWN:
8944       error (_("Remote target does not support flash erase"));
8945     case PACKET_ERROR:
8946       error (_("Error erasing flash with vFlashErase packet"));
8947     default:
8948       break;
8949     }
8950 }
8951
8952 target_xfer_status
8953 remote_target::remote_flash_write (ULONGEST address,
8954                                    ULONGEST length, ULONGEST *xfered_len,
8955                                    const gdb_byte *data)
8956 {
8957   scoped_restore restore_timeout
8958     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8959   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8960                                  xfered_len,'X', 0);
8961 }
8962
8963 void
8964 remote_target::flash_done ()
8965 {
8966   int ret;
8967
8968   scoped_restore restore_timeout
8969     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8970
8971   ret = remote_send_printf ("vFlashDone");
8972
8973   switch (ret)
8974     {
8975     case PACKET_UNKNOWN:
8976       error (_("Remote target does not support vFlashDone"));
8977     case PACKET_ERROR:
8978       error (_("Error finishing flash operation"));
8979     default:
8980       break;
8981     }
8982 }
8983
8984 void
8985 remote_target::files_info ()
8986 {
8987   puts_filtered ("Debugging a target over a serial line.\n");
8988 }
8989 \f
8990 /* Stuff for dealing with the packets which are part of this protocol.
8991    See comment at top of file for details.  */
8992
8993 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8994    error to higher layers.  Called when a serial error is detected.
8995    The exception message is STRING, followed by a colon and a blank,
8996    the system error message for errno at function entry and final dot
8997    for output compatibility with throw_perror_with_name.  */
8998
8999 static void
9000 unpush_and_perror (const char *string)
9001 {
9002   int saved_errno = errno;
9003
9004   remote_unpush_target ();
9005   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9006                safe_strerror (saved_errno));
9007 }
9008
9009 /* Read a single character from the remote end.  The current quit
9010    handler is overridden to avoid quitting in the middle of packet
9011    sequence, as that would break communication with the remote server.
9012    See remote_serial_quit_handler for more detail.  */
9013
9014 int
9015 remote_target::readchar (int timeout)
9016 {
9017   int ch;
9018   struct remote_state *rs = get_remote_state ();
9019
9020   {
9021     scoped_restore restore_quit_target
9022       = make_scoped_restore (&curr_quit_handler_target, this);
9023     scoped_restore restore_quit
9024       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9025
9026     rs->got_ctrlc_during_io = 0;
9027
9028     ch = serial_readchar (rs->remote_desc, timeout);
9029
9030     if (rs->got_ctrlc_during_io)
9031       set_quit_flag ();
9032   }
9033
9034   if (ch >= 0)
9035     return ch;
9036
9037   switch ((enum serial_rc) ch)
9038     {
9039     case SERIAL_EOF:
9040       remote_unpush_target ();
9041       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9042       /* no return */
9043     case SERIAL_ERROR:
9044       unpush_and_perror (_("Remote communication error.  "
9045                            "Target disconnected."));
9046       /* no return */
9047     case SERIAL_TIMEOUT:
9048       break;
9049     }
9050   return ch;
9051 }
9052
9053 /* Wrapper for serial_write that closes the target and throws if
9054    writing fails.  The current quit handler is overridden to avoid
9055    quitting in the middle of packet sequence, as that would break
9056    communication with the remote server.  See
9057    remote_serial_quit_handler for more detail.  */
9058
9059 void
9060 remote_target::remote_serial_write (const char *str, int len)
9061 {
9062   struct remote_state *rs = get_remote_state ();
9063
9064   scoped_restore restore_quit_target
9065     = make_scoped_restore (&curr_quit_handler_target, this);
9066   scoped_restore restore_quit
9067     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9068
9069   rs->got_ctrlc_during_io = 0;
9070
9071   if (serial_write (rs->remote_desc, str, len))
9072     {
9073       unpush_and_perror (_("Remote communication error.  "
9074                            "Target disconnected."));
9075     }
9076
9077   if (rs->got_ctrlc_during_io)
9078     set_quit_flag ();
9079 }
9080
9081 /* Return a string representing an escaped version of BUF, of len N.
9082    E.g. \n is converted to \\n, \t to \\t, etc.  */
9083
9084 static std::string
9085 escape_buffer (const char *buf, int n)
9086 {
9087   string_file stb;
9088
9089   stb.putstrn (buf, n, '\\');
9090   return std::move (stb.string ());
9091 }
9092
9093 /* Display a null-terminated packet on stdout, for debugging, using C
9094    string notation.  */
9095
9096 static void
9097 print_packet (const char *buf)
9098 {
9099   puts_filtered ("\"");
9100   fputstr_filtered (buf, '"', gdb_stdout);
9101   puts_filtered ("\"");
9102 }
9103
9104 int
9105 remote_target::putpkt (const char *buf)
9106 {
9107   return putpkt_binary (buf, strlen (buf));
9108 }
9109
9110 /* Wrapper around remote_target::putpkt to avoid exporting
9111    remote_target.  */
9112
9113 int
9114 putpkt (remote_target *remote, const char *buf)
9115 {
9116   return remote->putpkt (buf);
9117 }
9118
9119 /* Send a packet to the remote machine, with error checking.  The data
9120    of the packet is in BUF.  The string in BUF can be at most
9121    get_remote_packet_size () - 5 to account for the $, # and checksum,
9122    and for a possible /0 if we are debugging (remote_debug) and want
9123    to print the sent packet as a string.  */
9124
9125 int
9126 remote_target::putpkt_binary (const char *buf, int cnt)
9127 {
9128   struct remote_state *rs = get_remote_state ();
9129   int i;
9130   unsigned char csum = 0;
9131   gdb::def_vector<char> data (cnt + 6);
9132   char *buf2 = data.data ();
9133
9134   int ch;
9135   int tcount = 0;
9136   char *p;
9137
9138   /* Catch cases like trying to read memory or listing threads while
9139      we're waiting for a stop reply.  The remote server wouldn't be
9140      ready to handle this request, so we'd hang and timeout.  We don't
9141      have to worry about this in synchronous mode, because in that
9142      case it's not possible to issue a command while the target is
9143      running.  This is not a problem in non-stop mode, because in that
9144      case, the stub is always ready to process serial input.  */
9145   if (!target_is_non_stop_p ()
9146       && target_is_async_p ()
9147       && rs->waiting_for_stop_reply)
9148     {
9149       error (_("Cannot execute this command while the target is running.\n"
9150                "Use the \"interrupt\" command to stop the target\n"
9151                "and then try again."));
9152     }
9153
9154   /* We're sending out a new packet.  Make sure we don't look at a
9155      stale cached response.  */
9156   rs->cached_wait_status = 0;
9157
9158   /* Copy the packet into buffer BUF2, encapsulating it
9159      and giving it a checksum.  */
9160
9161   p = buf2;
9162   *p++ = '$';
9163
9164   for (i = 0; i < cnt; i++)
9165     {
9166       csum += buf[i];
9167       *p++ = buf[i];
9168     }
9169   *p++ = '#';
9170   *p++ = tohex ((csum >> 4) & 0xf);
9171   *p++ = tohex (csum & 0xf);
9172
9173   /* Send it over and over until we get a positive ack.  */
9174
9175   while (1)
9176     {
9177       int started_error_output = 0;
9178
9179       if (remote_debug)
9180         {
9181           *p = '\0';
9182
9183           int len = (int) (p - buf2);
9184
9185           std::string str
9186             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9187
9188           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9189
9190           if (len > REMOTE_DEBUG_MAX_CHAR)
9191             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9192                                 len - REMOTE_DEBUG_MAX_CHAR);
9193
9194           fprintf_unfiltered (gdb_stdlog, "...");
9195
9196           gdb_flush (gdb_stdlog);
9197         }
9198       remote_serial_write (buf2, p - buf2);
9199
9200       /* If this is a no acks version of the remote protocol, send the
9201          packet and move on.  */
9202       if (rs->noack_mode)
9203         break;
9204
9205       /* Read until either a timeout occurs (-2) or '+' is read.
9206          Handle any notification that arrives in the mean time.  */
9207       while (1)
9208         {
9209           ch = readchar (remote_timeout);
9210
9211           if (remote_debug)
9212             {
9213               switch (ch)
9214                 {
9215                 case '+':
9216                 case '-':
9217                 case SERIAL_TIMEOUT:
9218                 case '$':
9219                 case '%':
9220                   if (started_error_output)
9221                     {
9222                       putchar_unfiltered ('\n');
9223                       started_error_output = 0;
9224                     }
9225                 }
9226             }
9227
9228           switch (ch)
9229             {
9230             case '+':
9231               if (remote_debug)
9232                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9233               return 1;
9234             case '-':
9235               if (remote_debug)
9236                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9237               /* FALLTHROUGH */
9238             case SERIAL_TIMEOUT:
9239               tcount++;
9240               if (tcount > 3)
9241                 return 0;
9242               break;            /* Retransmit buffer.  */
9243             case '$':
9244               {
9245                 if (remote_debug)
9246                   fprintf_unfiltered (gdb_stdlog,
9247                                       "Packet instead of Ack, ignoring it\n");
9248                 /* It's probably an old response sent because an ACK
9249                    was lost.  Gobble up the packet and ack it so it
9250                    doesn't get retransmitted when we resend this
9251                    packet.  */
9252                 skip_frame ();
9253                 remote_serial_write ("+", 1);
9254                 continue;       /* Now, go look for +.  */
9255               }
9256
9257             case '%':
9258               {
9259                 int val;
9260
9261                 /* If we got a notification, handle it, and go back to looking
9262                    for an ack.  */
9263                 /* We've found the start of a notification.  Now
9264                    collect the data.  */
9265                 val = read_frame (&rs->buf, &rs->buf_size);
9266                 if (val >= 0)
9267                   {
9268                     if (remote_debug)
9269                       {
9270                         std::string str = escape_buffer (rs->buf, val);
9271
9272                         fprintf_unfiltered (gdb_stdlog,
9273                                             "  Notification received: %s\n",
9274                                             str.c_str ());
9275                       }
9276                     handle_notification (rs->notif_state, rs->buf);
9277                     /* We're in sync now, rewait for the ack.  */
9278                     tcount = 0;
9279                   }
9280                 else
9281                   {
9282                     if (remote_debug)
9283                       {
9284                         if (!started_error_output)
9285                           {
9286                             started_error_output = 1;
9287                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9288                           }
9289                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9290                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9291                       }
9292                   }
9293                 continue;
9294               }
9295               /* fall-through */
9296             default:
9297               if (remote_debug)
9298                 {
9299                   if (!started_error_output)
9300                     {
9301                       started_error_output = 1;
9302                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9303                     }
9304                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9305                 }
9306               continue;
9307             }
9308           break;                /* Here to retransmit.  */
9309         }
9310
9311 #if 0
9312       /* This is wrong.  If doing a long backtrace, the user should be
9313          able to get out next time we call QUIT, without anything as
9314          violent as interrupt_query.  If we want to provide a way out of
9315          here without getting to the next QUIT, it should be based on
9316          hitting ^C twice as in remote_wait.  */
9317       if (quit_flag)
9318         {
9319           quit_flag = 0;
9320           interrupt_query ();
9321         }
9322 #endif
9323     }
9324
9325   return 0;
9326 }
9327
9328 /* Come here after finding the start of a frame when we expected an
9329    ack.  Do our best to discard the rest of this packet.  */
9330
9331 void
9332 remote_target::skip_frame ()
9333 {
9334   int c;
9335
9336   while (1)
9337     {
9338       c = readchar (remote_timeout);
9339       switch (c)
9340         {
9341         case SERIAL_TIMEOUT:
9342           /* Nothing we can do.  */
9343           return;
9344         case '#':
9345           /* Discard the two bytes of checksum and stop.  */
9346           c = readchar (remote_timeout);
9347           if (c >= 0)
9348             c = readchar (remote_timeout);
9349
9350           return;
9351         case '*':               /* Run length encoding.  */
9352           /* Discard the repeat count.  */
9353           c = readchar (remote_timeout);
9354           if (c < 0)
9355             return;
9356           break;
9357         default:
9358           /* A regular character.  */
9359           break;
9360         }
9361     }
9362 }
9363
9364 /* Come here after finding the start of the frame.  Collect the rest
9365    into *BUF, verifying the checksum, length, and handling run-length
9366    compression.  NUL terminate the buffer.  If there is not enough room,
9367    expand *BUF using xrealloc.
9368
9369    Returns -1 on error, number of characters in buffer (ignoring the
9370    trailing NULL) on success. (could be extended to return one of the
9371    SERIAL status indications).  */
9372
9373 long
9374 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9375 {
9376   unsigned char csum;
9377   long bc;
9378   int c;
9379   char *buf = *buf_p;
9380   struct remote_state *rs = get_remote_state ();
9381
9382   csum = 0;
9383   bc = 0;
9384
9385   while (1)
9386     {
9387       c = readchar (remote_timeout);
9388       switch (c)
9389         {
9390         case SERIAL_TIMEOUT:
9391           if (remote_debug)
9392             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9393           return -1;
9394         case '$':
9395           if (remote_debug)
9396             fputs_filtered ("Saw new packet start in middle of old one\n",
9397                             gdb_stdlog);
9398           return -1;            /* Start a new packet, count retries.  */
9399         case '#':
9400           {
9401             unsigned char pktcsum;
9402             int check_0 = 0;
9403             int check_1 = 0;
9404
9405             buf[bc] = '\0';
9406
9407             check_0 = readchar (remote_timeout);
9408             if (check_0 >= 0)
9409               check_1 = readchar (remote_timeout);
9410
9411             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9412               {
9413                 if (remote_debug)
9414                   fputs_filtered ("Timeout in checksum, retrying\n",
9415                                   gdb_stdlog);
9416                 return -1;
9417               }
9418             else if (check_0 < 0 || check_1 < 0)
9419               {
9420                 if (remote_debug)
9421                   fputs_filtered ("Communication error in checksum\n",
9422                                   gdb_stdlog);
9423                 return -1;
9424               }
9425
9426             /* Don't recompute the checksum; with no ack packets we
9427                don't have any way to indicate a packet retransmission
9428                is necessary.  */
9429             if (rs->noack_mode)
9430               return bc;
9431
9432             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9433             if (csum == pktcsum)
9434               return bc;
9435
9436             if (remote_debug)
9437               {
9438                 std::string str = escape_buffer (buf, bc);
9439
9440                 fprintf_unfiltered (gdb_stdlog,
9441                                     "Bad checksum, sentsum=0x%x, "
9442                                     "csum=0x%x, buf=%s\n",
9443                                     pktcsum, csum, str.c_str ());
9444               }
9445             /* Number of characters in buffer ignoring trailing
9446                NULL.  */
9447             return -1;
9448           }
9449         case '*':               /* Run length encoding.  */
9450           {
9451             int repeat;
9452
9453             csum += c;
9454             c = readchar (remote_timeout);
9455             csum += c;
9456             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9457
9458             /* The character before ``*'' is repeated.  */
9459
9460             if (repeat > 0 && repeat <= 255 && bc > 0)
9461               {
9462                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9463                   {
9464                     /* Make some more room in the buffer.  */
9465                     *sizeof_buf += repeat;
9466                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9467                     buf = *buf_p;
9468                   }
9469
9470                 memset (&buf[bc], buf[bc - 1], repeat);
9471                 bc += repeat;
9472                 continue;
9473               }
9474
9475             buf[bc] = '\0';
9476             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9477             return -1;
9478           }
9479         default:
9480           if (bc >= *sizeof_buf - 1)
9481             {
9482               /* Make some more room in the buffer.  */
9483               *sizeof_buf *= 2;
9484               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9485               buf = *buf_p;
9486             }
9487
9488           buf[bc++] = c;
9489           csum += c;
9490           continue;
9491         }
9492     }
9493 }
9494
9495 /* Read a packet from the remote machine, with error checking, and
9496    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9497    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9498    rather than timing out; this is used (in synchronous mode) to wait
9499    for a target that is is executing user code to stop.  */
9500 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9501    don't have to change all the calls to getpkt to deal with the
9502    return value, because at the moment I don't know what the right
9503    thing to do it for those.  */
9504
9505 void
9506 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9507 {
9508   getpkt_sane (buf, sizeof_buf, forever);
9509 }
9510
9511
9512 /* Read a packet from the remote machine, with error checking, and
9513    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9514    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9515    rather than timing out; this is used (in synchronous mode) to wait
9516    for a target that is is executing user code to stop.  If FOREVER ==
9517    0, this function is allowed to time out gracefully and return an
9518    indication of this to the caller.  Otherwise return the number of
9519    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9520    enough reason to return to the caller.  *IS_NOTIF is an output
9521    boolean that indicates whether *BUF holds a notification or not
9522    (a regular packet).  */
9523
9524 int
9525 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9526                                        int forever, int expecting_notif,
9527                                        int *is_notif)
9528 {
9529   struct remote_state *rs = get_remote_state ();
9530   int c;
9531   int tries;
9532   int timeout;
9533   int val = -1;
9534
9535   /* We're reading a new response.  Make sure we don't look at a
9536      previously cached response.  */
9537   rs->cached_wait_status = 0;
9538
9539   strcpy (*buf, "timeout");
9540
9541   if (forever)
9542     timeout = watchdog > 0 ? watchdog : -1;
9543   else if (expecting_notif)
9544     timeout = 0; /* There should already be a char in the buffer.  If
9545                     not, bail out.  */
9546   else
9547     timeout = remote_timeout;
9548
9549 #define MAX_TRIES 3
9550
9551   /* Process any number of notifications, and then return when
9552      we get a packet.  */
9553   for (;;)
9554     {
9555       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9556          times.  */
9557       for (tries = 1; tries <= MAX_TRIES; tries++)
9558         {
9559           /* This can loop forever if the remote side sends us
9560              characters continuously, but if it pauses, we'll get
9561              SERIAL_TIMEOUT from readchar because of timeout.  Then
9562              we'll count that as a retry.
9563
9564              Note that even when forever is set, we will only wait
9565              forever prior to the start of a packet.  After that, we
9566              expect characters to arrive at a brisk pace.  They should
9567              show up within remote_timeout intervals.  */
9568           do
9569             c = readchar (timeout);
9570           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9571
9572           if (c == SERIAL_TIMEOUT)
9573             {
9574               if (expecting_notif)
9575                 return -1; /* Don't complain, it's normal to not get
9576                               anything in this case.  */
9577
9578               if (forever)      /* Watchdog went off?  Kill the target.  */
9579                 {
9580                   remote_unpush_target ();
9581                   throw_error (TARGET_CLOSE_ERROR,
9582                                _("Watchdog timeout has expired.  "
9583                                  "Target detached."));
9584                 }
9585               if (remote_debug)
9586                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9587             }
9588           else
9589             {
9590               /* We've found the start of a packet or notification.
9591                  Now collect the data.  */
9592               val = read_frame (buf, sizeof_buf);
9593               if (val >= 0)
9594                 break;
9595             }
9596
9597           remote_serial_write ("-", 1);
9598         }
9599
9600       if (tries > MAX_TRIES)
9601         {
9602           /* We have tried hard enough, and just can't receive the
9603              packet/notification.  Give up.  */
9604           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9605
9606           /* Skip the ack char if we're in no-ack mode.  */
9607           if (!rs->noack_mode)
9608             remote_serial_write ("+", 1);
9609           return -1;
9610         }
9611
9612       /* If we got an ordinary packet, return that to our caller.  */
9613       if (c == '$')
9614         {
9615           if (remote_debug)
9616             {
9617               std::string str
9618                 = escape_buffer (*buf,
9619                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9620
9621               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9622                                   str.c_str ());
9623
9624               if (val > REMOTE_DEBUG_MAX_CHAR)
9625                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9626                                     val - REMOTE_DEBUG_MAX_CHAR);
9627
9628               fprintf_unfiltered (gdb_stdlog, "\n");
9629             }
9630
9631           /* Skip the ack char if we're in no-ack mode.  */
9632           if (!rs->noack_mode)
9633             remote_serial_write ("+", 1);
9634           if (is_notif != NULL)
9635             *is_notif = 0;
9636           return val;
9637         }
9638
9639        /* If we got a notification, handle it, and go back to looking
9640          for a packet.  */
9641       else
9642         {
9643           gdb_assert (c == '%');
9644
9645           if (remote_debug)
9646             {
9647               std::string str = escape_buffer (*buf, val);
9648
9649               fprintf_unfiltered (gdb_stdlog,
9650                                   "  Notification received: %s\n",
9651                                   str.c_str ());
9652             }
9653           if (is_notif != NULL)
9654             *is_notif = 1;
9655
9656           handle_notification (rs->notif_state, *buf);
9657
9658           /* Notifications require no acknowledgement.  */
9659
9660           if (expecting_notif)
9661             return val;
9662         }
9663     }
9664 }
9665
9666 int
9667 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9668 {
9669   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9670 }
9671
9672 int
9673 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9674                                      int *is_notif)
9675 {
9676   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9677                                  is_notif);
9678 }
9679
9680 /* Kill any new fork children of process PID that haven't been
9681    processed by follow_fork.  */
9682
9683 void
9684 remote_target::kill_new_fork_children (int pid)
9685 {
9686   remote_state *rs = get_remote_state ();
9687   struct thread_info *thread;
9688   struct notif_client *notif = &notif_client_stop;
9689
9690   /* Kill the fork child threads of any threads in process PID
9691      that are stopped at a fork event.  */
9692   ALL_NON_EXITED_THREADS (thread)
9693     {
9694       struct target_waitstatus *ws = &thread->pending_follow;
9695
9696       if (is_pending_fork_parent (ws, pid, thread->ptid))
9697         {
9698           int child_pid = ws->value.related_pid.pid ();
9699           int res;
9700
9701           res = remote_vkill (child_pid);
9702           if (res != 0)
9703             error (_("Can't kill fork child process %d"), child_pid);
9704         }
9705     }
9706
9707   /* Check for any pending fork events (not reported or processed yet)
9708      in process PID and kill those fork child threads as well.  */
9709   remote_notif_get_pending_events (notif);
9710   for (auto &event : rs->stop_reply_queue)
9711     if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9712       {
9713         int child_pid = event->ws.value.related_pid.pid ();
9714         int res;
9715
9716         res = remote_vkill (child_pid);
9717         if (res != 0)
9718           error (_("Can't kill fork child process %d"), child_pid);
9719       }
9720 }
9721
9722 \f
9723 /* Target hook to kill the current inferior.  */
9724
9725 void
9726 remote_target::kill ()
9727 {
9728   int res = -1;
9729   int pid = inferior_ptid.pid ();
9730   struct remote_state *rs = get_remote_state ();
9731
9732   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9733     {
9734       /* If we're stopped while forking and we haven't followed yet,
9735          kill the child task.  We need to do this before killing the
9736          parent task because if this is a vfork then the parent will
9737          be sleeping.  */
9738       kill_new_fork_children (pid);
9739
9740       res = remote_vkill (pid);
9741       if (res == 0)
9742         {
9743           target_mourn_inferior (inferior_ptid);
9744           return;
9745         }
9746     }
9747
9748   /* If we are in 'target remote' mode and we are killing the only
9749      inferior, then we will tell gdbserver to exit and unpush the
9750      target.  */
9751   if (res == -1 && !remote_multi_process_p (rs)
9752       && number_of_live_inferiors () == 1)
9753     {
9754       remote_kill_k ();
9755
9756       /* We've killed the remote end, we get to mourn it.  If we are
9757          not in extended mode, mourning the inferior also unpushes
9758          remote_ops from the target stack, which closes the remote
9759          connection.  */
9760       target_mourn_inferior (inferior_ptid);
9761
9762       return;
9763     }
9764
9765   error (_("Can't kill process"));
9766 }
9767
9768 /* Send a kill request to the target using the 'vKill' packet.  */
9769
9770 int
9771 remote_target::remote_vkill (int pid)
9772 {
9773   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9774     return -1;
9775
9776   remote_state *rs = get_remote_state ();
9777
9778   /* Tell the remote target to detach.  */
9779   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9780   putpkt (rs->buf);
9781   getpkt (&rs->buf, &rs->buf_size, 0);
9782
9783   switch (packet_ok (rs->buf,
9784                      &remote_protocol_packets[PACKET_vKill]))
9785     {
9786     case PACKET_OK:
9787       return 0;
9788     case PACKET_ERROR:
9789       return 1;
9790     case PACKET_UNKNOWN:
9791       return -1;
9792     default:
9793       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9794     }
9795 }
9796
9797 /* Send a kill request to the target using the 'k' packet.  */
9798
9799 void
9800 remote_target::remote_kill_k ()
9801 {
9802   /* Catch errors so the user can quit from gdb even when we
9803      aren't on speaking terms with the remote system.  */
9804   TRY
9805     {
9806       putpkt ("k");
9807     }
9808   CATCH (ex, RETURN_MASK_ERROR)
9809     {
9810       if (ex.error == TARGET_CLOSE_ERROR)
9811         {
9812           /* If we got an (EOF) error that caused the target
9813              to go away, then we're done, that's what we wanted.
9814              "k" is susceptible to cause a premature EOF, given
9815              that the remote server isn't actually required to
9816              reply to "k", and it can happen that it doesn't
9817              even get to reply ACK to the "k".  */
9818           return;
9819         }
9820
9821       /* Otherwise, something went wrong.  We didn't actually kill
9822          the target.  Just propagate the exception, and let the
9823          user or higher layers decide what to do.  */
9824       throw_exception (ex);
9825     }
9826   END_CATCH
9827 }
9828
9829 void
9830 remote_target::mourn_inferior ()
9831 {
9832   struct remote_state *rs = get_remote_state ();
9833
9834   /* We're no longer interested in notification events of an inferior
9835      that exited or was killed/detached.  */
9836   discard_pending_stop_replies (current_inferior ());
9837
9838   /* In 'target remote' mode with one inferior, we close the connection.  */
9839   if (!rs->extended && number_of_live_inferiors () <= 1)
9840     {
9841       unpush_target (this);
9842
9843       /* remote_close takes care of doing most of the clean up.  */
9844       generic_mourn_inferior ();
9845       return;
9846     }
9847
9848   /* In case we got here due to an error, but we're going to stay
9849      connected.  */
9850   rs->waiting_for_stop_reply = 0;
9851
9852   /* If the current general thread belonged to the process we just
9853      detached from or has exited, the remote side current general
9854      thread becomes undefined.  Considering a case like this:
9855
9856      - We just got here due to a detach.
9857      - The process that we're detaching from happens to immediately
9858        report a global breakpoint being hit in non-stop mode, in the
9859        same thread we had selected before.
9860      - GDB attaches to this process again.
9861      - This event happens to be the next event we handle.
9862
9863      GDB would consider that the current general thread didn't need to
9864      be set on the stub side (with Hg), since for all it knew,
9865      GENERAL_THREAD hadn't changed.
9866
9867      Notice that although in all-stop mode, the remote server always
9868      sets the current thread to the thread reporting the stop event,
9869      that doesn't happen in non-stop mode; in non-stop, the stub *must
9870      not* change the current thread when reporting a breakpoint hit,
9871      due to the decoupling of event reporting and event handling.
9872
9873      To keep things simple, we always invalidate our notion of the
9874      current thread.  */
9875   record_currthread (rs, minus_one_ptid);
9876
9877   /* Call common code to mark the inferior as not running.  */
9878   generic_mourn_inferior ();
9879
9880   if (!have_inferiors ())
9881     {
9882       if (!remote_multi_process_p (rs))
9883         {
9884           /* Check whether the target is running now - some remote stubs
9885              automatically restart after kill.  */
9886           putpkt ("?");
9887           getpkt (&rs->buf, &rs->buf_size, 0);
9888
9889           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9890             {
9891               /* Assume that the target has been restarted.  Set
9892                  inferior_ptid so that bits of core GDB realizes
9893                  there's something here, e.g., so that the user can
9894                  say "kill" again.  */
9895               inferior_ptid = magic_null_ptid;
9896             }
9897         }
9898     }
9899 }
9900
9901 bool
9902 extended_remote_target::supports_disable_randomization ()
9903 {
9904   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9905 }
9906
9907 void
9908 remote_target::extended_remote_disable_randomization (int val)
9909 {
9910   struct remote_state *rs = get_remote_state ();
9911   char *reply;
9912
9913   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9914              val);
9915   putpkt (rs->buf);
9916   reply = remote_get_noisy_reply ();
9917   if (*reply == '\0')
9918     error (_("Target does not support QDisableRandomization."));
9919   if (strcmp (reply, "OK") != 0)
9920     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9921 }
9922
9923 int
9924 remote_target::extended_remote_run (const std::string &args)
9925 {
9926   struct remote_state *rs = get_remote_state ();
9927   int len;
9928   const char *remote_exec_file = get_remote_exec_file ();
9929
9930   /* If the user has disabled vRun support, or we have detected that
9931      support is not available, do not try it.  */
9932   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9933     return -1;
9934
9935   strcpy (rs->buf, "vRun;");
9936   len = strlen (rs->buf);
9937
9938   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9939     error (_("Remote file name too long for run packet"));
9940   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9941                       strlen (remote_exec_file));
9942
9943   if (!args.empty ())
9944     {
9945       int i;
9946
9947       gdb_argv argv (args.c_str ());
9948       for (i = 0; argv[i] != NULL; i++)
9949         {
9950           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9951             error (_("Argument list too long for run packet"));
9952           rs->buf[len++] = ';';
9953           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9954                               strlen (argv[i]));
9955         }
9956     }
9957
9958   rs->buf[len++] = '\0';
9959
9960   putpkt (rs->buf);
9961   getpkt (&rs->buf, &rs->buf_size, 0);
9962
9963   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9964     {
9965     case PACKET_OK:
9966       /* We have a wait response.  All is well.  */
9967       return 0;
9968     case PACKET_UNKNOWN:
9969       return -1;
9970     case PACKET_ERROR:
9971       if (remote_exec_file[0] == '\0')
9972         error (_("Running the default executable on the remote target failed; "
9973                  "try \"set remote exec-file\"?"));
9974       else
9975         error (_("Running \"%s\" on the remote target failed"),
9976                remote_exec_file);
9977     default:
9978       gdb_assert_not_reached (_("bad switch"));
9979     }
9980 }
9981
9982 /* Helper function to send set/unset environment packets.  ACTION is
9983    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
9984    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
9985    sent.  */
9986
9987 void
9988 remote_target::send_environment_packet (const char *action,
9989                                         const char *packet,
9990                                         const char *value)
9991 {
9992   remote_state *rs = get_remote_state ();
9993
9994   /* Convert the environment variable to an hex string, which
9995      is the best format to be transmitted over the wire.  */
9996   std::string encoded_value = bin2hex ((const gdb_byte *) value,
9997                                          strlen (value));
9998
9999   xsnprintf (rs->buf, get_remote_packet_size (),
10000              "%s:%s", packet, encoded_value.c_str ());
10001
10002   putpkt (rs->buf);
10003   getpkt (&rs->buf, &rs->buf_size, 0);
10004   if (strcmp (rs->buf, "OK") != 0)
10005     warning (_("Unable to %s environment variable '%s' on remote."),
10006              action, value);
10007 }
10008
10009 /* Helper function to handle the QEnvironment* packets.  */
10010
10011 void
10012 remote_target::extended_remote_environment_support ()
10013 {
10014   remote_state *rs = get_remote_state ();
10015
10016   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10017     {
10018       putpkt ("QEnvironmentReset");
10019       getpkt (&rs->buf, &rs->buf_size, 0);
10020       if (strcmp (rs->buf, "OK") != 0)
10021         warning (_("Unable to reset environment on remote."));
10022     }
10023
10024   gdb_environ *e = &current_inferior ()->environment;
10025
10026   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10027     for (const std::string &el : e->user_set_env ())
10028       send_environment_packet ("set", "QEnvironmentHexEncoded",
10029                                el.c_str ());
10030
10031   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10032     for (const std::string &el : e->user_unset_env ())
10033       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10034 }
10035
10036 /* Helper function to set the current working directory for the
10037    inferior in the remote target.  */
10038
10039 void
10040 remote_target::extended_remote_set_inferior_cwd ()
10041 {
10042   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10043     {
10044       const char *inferior_cwd = get_inferior_cwd ();
10045       remote_state *rs = get_remote_state ();
10046
10047       if (inferior_cwd != NULL)
10048         {
10049           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10050                                          strlen (inferior_cwd));
10051
10052           xsnprintf (rs->buf, get_remote_packet_size (),
10053                      "QSetWorkingDir:%s", hexpath.c_str ());
10054         }
10055       else
10056         {
10057           /* An empty inferior_cwd means that the user wants us to
10058              reset the remote server's inferior's cwd.  */
10059           xsnprintf (rs->buf, get_remote_packet_size (),
10060                      "QSetWorkingDir:");
10061         }
10062
10063       putpkt (rs->buf);
10064       getpkt (&rs->buf, &rs->buf_size, 0);
10065       if (packet_ok (rs->buf,
10066                      &remote_protocol_packets[PACKET_QSetWorkingDir])
10067           != PACKET_OK)
10068         error (_("\
10069 Remote replied unexpectedly while setting the inferior's working\n\
10070 directory: %s"),
10071                rs->buf);
10072
10073     }
10074 }
10075
10076 /* In the extended protocol we want to be able to do things like
10077    "run" and have them basically work as expected.  So we need
10078    a special create_inferior function.  We support changing the
10079    executable file and the command line arguments, but not the
10080    environment.  */
10081
10082 void
10083 extended_remote_target::create_inferior (const char *exec_file,
10084                                          const std::string &args,
10085                                          char **env, int from_tty)
10086 {
10087   int run_worked;
10088   char *stop_reply;
10089   struct remote_state *rs = get_remote_state ();
10090   const char *remote_exec_file = get_remote_exec_file ();
10091
10092   /* If running asynchronously, register the target file descriptor
10093      with the event loop.  */
10094   if (target_can_async_p ())
10095     target_async (1);
10096
10097   /* Disable address space randomization if requested (and supported).  */
10098   if (supports_disable_randomization ())
10099     extended_remote_disable_randomization (disable_randomization);
10100
10101   /* If startup-with-shell is on, we inform gdbserver to start the
10102      remote inferior using a shell.  */
10103   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10104     {
10105       xsnprintf (rs->buf, get_remote_packet_size (),
10106                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10107       putpkt (rs->buf);
10108       getpkt (&rs->buf, &rs->buf_size, 0);
10109       if (strcmp (rs->buf, "OK") != 0)
10110         error (_("\
10111 Remote replied unexpectedly while setting startup-with-shell: %s"),
10112                rs->buf);
10113     }
10114
10115   extended_remote_environment_support ();
10116
10117   extended_remote_set_inferior_cwd ();
10118
10119   /* Now restart the remote server.  */
10120   run_worked = extended_remote_run (args) != -1;
10121   if (!run_worked)
10122     {
10123       /* vRun was not supported.  Fail if we need it to do what the
10124          user requested.  */
10125       if (remote_exec_file[0])
10126         error (_("Remote target does not support \"set remote exec-file\""));
10127       if (!args.empty ())
10128         error (_("Remote target does not support \"set args\" or run <ARGS>"));
10129
10130       /* Fall back to "R".  */
10131       extended_remote_restart ();
10132     }
10133
10134   if (!have_inferiors ())
10135     {
10136       /* Clean up from the last time we ran, before we mark the target
10137          running again.  This will mark breakpoints uninserted, and
10138          get_offsets may insert breakpoints.  */
10139       init_thread_list ();
10140       init_wait_for_inferior ();
10141     }
10142
10143   /* vRun's success return is a stop reply.  */
10144   stop_reply = run_worked ? rs->buf : NULL;
10145   add_current_inferior_and_thread (stop_reply);
10146
10147   /* Get updated offsets, if the stub uses qOffsets.  */
10148   get_offsets ();
10149 }
10150 \f
10151
10152 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10153    the list of conditions (in agent expression bytecode format), if any, the
10154    target needs to evaluate.  The output is placed into the packet buffer
10155    started from BUF and ended at BUF_END.  */
10156
10157 static int
10158 remote_add_target_side_condition (struct gdbarch *gdbarch,
10159                                   struct bp_target_info *bp_tgt, char *buf,
10160                                   char *buf_end)
10161 {
10162   if (bp_tgt->conditions.empty ())
10163     return 0;
10164
10165   buf += strlen (buf);
10166   xsnprintf (buf, buf_end - buf, "%s", ";");
10167   buf++;
10168
10169   /* Send conditions to the target.  */
10170   for (agent_expr *aexpr : bp_tgt->conditions)
10171     {
10172       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10173       buf += strlen (buf);
10174       for (int i = 0; i < aexpr->len; ++i)
10175         buf = pack_hex_byte (buf, aexpr->buf[i]);
10176       *buf = '\0';
10177     }
10178   return 0;
10179 }
10180
10181 static void
10182 remote_add_target_side_commands (struct gdbarch *gdbarch,
10183                                  struct bp_target_info *bp_tgt, char *buf)
10184 {
10185   if (bp_tgt->tcommands.empty ())
10186     return;
10187
10188   buf += strlen (buf);
10189
10190   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10191   buf += strlen (buf);
10192
10193   /* Concatenate all the agent expressions that are commands into the
10194      cmds parameter.  */
10195   for (agent_expr *aexpr : bp_tgt->tcommands)
10196     {
10197       sprintf (buf, "X%x,", aexpr->len);
10198       buf += strlen (buf);
10199       for (int i = 0; i < aexpr->len; ++i)
10200         buf = pack_hex_byte (buf, aexpr->buf[i]);
10201       *buf = '\0';
10202     }
10203 }
10204
10205 /* Insert a breakpoint.  On targets that have software breakpoint
10206    support, we ask the remote target to do the work; on targets
10207    which don't, we insert a traditional memory breakpoint.  */
10208
10209 int
10210 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10211                                   struct bp_target_info *bp_tgt)
10212 {
10213   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10214      If it succeeds, then set the support to PACKET_ENABLE.  If it
10215      fails, and the user has explicitly requested the Z support then
10216      report an error, otherwise, mark it disabled and go on.  */
10217
10218   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10219     {
10220       CORE_ADDR addr = bp_tgt->reqstd_address;
10221       struct remote_state *rs;
10222       char *p, *endbuf;
10223
10224       /* Make sure the remote is pointing at the right process, if
10225          necessary.  */
10226       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10227         set_general_process ();
10228
10229       rs = get_remote_state ();
10230       p = rs->buf;
10231       endbuf = rs->buf + get_remote_packet_size ();
10232
10233       *(p++) = 'Z';
10234       *(p++) = '0';
10235       *(p++) = ',';
10236       addr = (ULONGEST) remote_address_masked (addr);
10237       p += hexnumstr (p, addr);
10238       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10239
10240       if (supports_evaluation_of_breakpoint_conditions ())
10241         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10242
10243       if (can_run_breakpoint_commands ())
10244         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10245
10246       putpkt (rs->buf);
10247       getpkt (&rs->buf, &rs->buf_size, 0);
10248
10249       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10250         {
10251         case PACKET_ERROR:
10252           return -1;
10253         case PACKET_OK:
10254           return 0;
10255         case PACKET_UNKNOWN:
10256           break;
10257         }
10258     }
10259
10260   /* If this breakpoint has target-side commands but this stub doesn't
10261      support Z0 packets, throw error.  */
10262   if (!bp_tgt->tcommands.empty ())
10263     throw_error (NOT_SUPPORTED_ERROR, _("\
10264 Target doesn't support breakpoints that have target side commands."));
10265
10266   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10267 }
10268
10269 int
10270 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10271                                   struct bp_target_info *bp_tgt,
10272                                   enum remove_bp_reason reason)
10273 {
10274   CORE_ADDR addr = bp_tgt->placed_address;
10275   struct remote_state *rs = get_remote_state ();
10276
10277   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10278     {
10279       char *p = rs->buf;
10280       char *endbuf = rs->buf + get_remote_packet_size ();
10281
10282       /* Make sure the remote is pointing at the right process, if
10283          necessary.  */
10284       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10285         set_general_process ();
10286
10287       *(p++) = 'z';
10288       *(p++) = '0';
10289       *(p++) = ',';
10290
10291       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10292       p += hexnumstr (p, addr);
10293       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10294
10295       putpkt (rs->buf);
10296       getpkt (&rs->buf, &rs->buf_size, 0);
10297
10298       return (rs->buf[0] == 'E');
10299     }
10300
10301   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10302 }
10303
10304 static enum Z_packet_type
10305 watchpoint_to_Z_packet (int type)
10306 {
10307   switch (type)
10308     {
10309     case hw_write:
10310       return Z_PACKET_WRITE_WP;
10311       break;
10312     case hw_read:
10313       return Z_PACKET_READ_WP;
10314       break;
10315     case hw_access:
10316       return Z_PACKET_ACCESS_WP;
10317       break;
10318     default:
10319       internal_error (__FILE__, __LINE__,
10320                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10321     }
10322 }
10323
10324 int
10325 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10326                                   enum target_hw_bp_type type, struct expression *cond)
10327 {
10328   struct remote_state *rs = get_remote_state ();
10329   char *endbuf = rs->buf + get_remote_packet_size ();
10330   char *p;
10331   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10332
10333   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10334     return 1;
10335
10336   /* Make sure the remote is pointing at the right process, if
10337      necessary.  */
10338   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10339     set_general_process ();
10340
10341   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10342   p = strchr (rs->buf, '\0');
10343   addr = remote_address_masked (addr);
10344   p += hexnumstr (p, (ULONGEST) addr);
10345   xsnprintf (p, endbuf - p, ",%x", len);
10346
10347   putpkt (rs->buf);
10348   getpkt (&rs->buf, &rs->buf_size, 0);
10349
10350   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10351     {
10352     case PACKET_ERROR:
10353       return -1;
10354     case PACKET_UNKNOWN:
10355       return 1;
10356     case PACKET_OK:
10357       return 0;
10358     }
10359   internal_error (__FILE__, __LINE__,
10360                   _("remote_insert_watchpoint: reached end of function"));
10361 }
10362
10363 bool
10364 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10365                                              CORE_ADDR start, int length)
10366 {
10367   CORE_ADDR diff = remote_address_masked (addr - start);
10368
10369   return diff < length;
10370 }
10371
10372
10373 int
10374 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10375                                   enum target_hw_bp_type type, struct expression *cond)
10376 {
10377   struct remote_state *rs = get_remote_state ();
10378   char *endbuf = rs->buf + get_remote_packet_size ();
10379   char *p;
10380   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10381
10382   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10383     return -1;
10384
10385   /* Make sure the remote is pointing at the right process, if
10386      necessary.  */
10387   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10388     set_general_process ();
10389
10390   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10391   p = strchr (rs->buf, '\0');
10392   addr = remote_address_masked (addr);
10393   p += hexnumstr (p, (ULONGEST) addr);
10394   xsnprintf (p, endbuf - p, ",%x", len);
10395   putpkt (rs->buf);
10396   getpkt (&rs->buf, &rs->buf_size, 0);
10397
10398   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10399     {
10400     case PACKET_ERROR:
10401     case PACKET_UNKNOWN:
10402       return -1;
10403     case PACKET_OK:
10404       return 0;
10405     }
10406   internal_error (__FILE__, __LINE__,
10407                   _("remote_remove_watchpoint: reached end of function"));
10408 }
10409
10410
10411 int remote_hw_watchpoint_limit = -1;
10412 int remote_hw_watchpoint_length_limit = -1;
10413 int remote_hw_breakpoint_limit = -1;
10414
10415 int
10416 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10417 {
10418   if (remote_hw_watchpoint_length_limit == 0)
10419     return 0;
10420   else if (remote_hw_watchpoint_length_limit < 0)
10421     return 1;
10422   else if (len <= remote_hw_watchpoint_length_limit)
10423     return 1;
10424   else
10425     return 0;
10426 }
10427
10428 int
10429 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10430 {
10431   if (type == bp_hardware_breakpoint)
10432     {
10433       if (remote_hw_breakpoint_limit == 0)
10434         return 0;
10435       else if (remote_hw_breakpoint_limit < 0)
10436         return 1;
10437       else if (cnt <= remote_hw_breakpoint_limit)
10438         return 1;
10439     }
10440   else
10441     {
10442       if (remote_hw_watchpoint_limit == 0)
10443         return 0;
10444       else if (remote_hw_watchpoint_limit < 0)
10445         return 1;
10446       else if (ot)
10447         return -1;
10448       else if (cnt <= remote_hw_watchpoint_limit)
10449         return 1;
10450     }
10451   return -1;
10452 }
10453
10454 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10455
10456 bool
10457 remote_target::stopped_by_sw_breakpoint ()
10458 {
10459   struct thread_info *thread = inferior_thread ();
10460
10461   return (thread->priv != NULL
10462           && (get_remote_thread_info (thread)->stop_reason
10463               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10464 }
10465
10466 /* The to_supports_stopped_by_sw_breakpoint method of target
10467    remote.  */
10468
10469 bool
10470 remote_target::supports_stopped_by_sw_breakpoint ()
10471 {
10472   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10473 }
10474
10475 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10476
10477 bool
10478 remote_target::stopped_by_hw_breakpoint ()
10479 {
10480   struct thread_info *thread = inferior_thread ();
10481
10482   return (thread->priv != NULL
10483           && (get_remote_thread_info (thread)->stop_reason
10484               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10485 }
10486
10487 /* The to_supports_stopped_by_hw_breakpoint method of target
10488    remote.  */
10489
10490 bool
10491 remote_target::supports_stopped_by_hw_breakpoint ()
10492 {
10493   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10494 }
10495
10496 bool
10497 remote_target::stopped_by_watchpoint ()
10498 {
10499   struct thread_info *thread = inferior_thread ();
10500
10501   return (thread->priv != NULL
10502           && (get_remote_thread_info (thread)->stop_reason
10503               == TARGET_STOPPED_BY_WATCHPOINT));
10504 }
10505
10506 bool
10507 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10508 {
10509   struct thread_info *thread = inferior_thread ();
10510
10511   if (thread->priv != NULL
10512       && (get_remote_thread_info (thread)->stop_reason
10513           == TARGET_STOPPED_BY_WATCHPOINT))
10514     {
10515       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10516       return true;
10517     }
10518
10519   return false;
10520 }
10521
10522
10523 int
10524 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10525                                      struct bp_target_info *bp_tgt)
10526 {
10527   CORE_ADDR addr = bp_tgt->reqstd_address;
10528   struct remote_state *rs;
10529   char *p, *endbuf;
10530   char *message;
10531
10532   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10533     return -1;
10534
10535   /* Make sure the remote is pointing at the right process, if
10536      necessary.  */
10537   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10538     set_general_process ();
10539
10540   rs = get_remote_state ();
10541   p = rs->buf;
10542   endbuf = rs->buf + get_remote_packet_size ();
10543
10544   *(p++) = 'Z';
10545   *(p++) = '1';
10546   *(p++) = ',';
10547
10548   addr = remote_address_masked (addr);
10549   p += hexnumstr (p, (ULONGEST) addr);
10550   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10551
10552   if (supports_evaluation_of_breakpoint_conditions ())
10553     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10554
10555   if (can_run_breakpoint_commands ())
10556     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10557
10558   putpkt (rs->buf);
10559   getpkt (&rs->buf, &rs->buf_size, 0);
10560
10561   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10562     {
10563     case PACKET_ERROR:
10564       if (rs->buf[1] == '.')
10565         {
10566           message = strchr (rs->buf + 2, '.');
10567           if (message)
10568             error (_("Remote failure reply: %s"), message + 1);
10569         }
10570       return -1;
10571     case PACKET_UNKNOWN:
10572       return -1;
10573     case PACKET_OK:
10574       return 0;
10575     }
10576   internal_error (__FILE__, __LINE__,
10577                   _("remote_insert_hw_breakpoint: reached end of function"));
10578 }
10579
10580
10581 int
10582 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10583                                      struct bp_target_info *bp_tgt)
10584 {
10585   CORE_ADDR addr;
10586   struct remote_state *rs = get_remote_state ();
10587   char *p = rs->buf;
10588   char *endbuf = rs->buf + get_remote_packet_size ();
10589
10590   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10591     return -1;
10592
10593   /* Make sure the remote is pointing at the right process, if
10594      necessary.  */
10595   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10596     set_general_process ();
10597
10598   *(p++) = 'z';
10599   *(p++) = '1';
10600   *(p++) = ',';
10601
10602   addr = remote_address_masked (bp_tgt->placed_address);
10603   p += hexnumstr (p, (ULONGEST) addr);
10604   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10605
10606   putpkt (rs->buf);
10607   getpkt (&rs->buf, &rs->buf_size, 0);
10608
10609   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10610     {
10611     case PACKET_ERROR:
10612     case PACKET_UNKNOWN:
10613       return -1;
10614     case PACKET_OK:
10615       return 0;
10616     }
10617   internal_error (__FILE__, __LINE__,
10618                   _("remote_remove_hw_breakpoint: reached end of function"));
10619 }
10620
10621 /* Verify memory using the "qCRC:" request.  */
10622
10623 int
10624 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10625 {
10626   struct remote_state *rs = get_remote_state ();
10627   unsigned long host_crc, target_crc;
10628   char *tmp;
10629
10630   /* It doesn't make sense to use qCRC if the remote target is
10631      connected but not running.  */
10632   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10633     {
10634       enum packet_result result;
10635
10636       /* Make sure the remote is pointing at the right process.  */
10637       set_general_process ();
10638
10639       /* FIXME: assumes lma can fit into long.  */
10640       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10641                  (long) lma, (long) size);
10642       putpkt (rs->buf);
10643
10644       /* Be clever; compute the host_crc before waiting for target
10645          reply.  */
10646       host_crc = xcrc32 (data, size, 0xffffffff);
10647
10648       getpkt (&rs->buf, &rs->buf_size, 0);
10649
10650       result = packet_ok (rs->buf,
10651                           &remote_protocol_packets[PACKET_qCRC]);
10652       if (result == PACKET_ERROR)
10653         return -1;
10654       else if (result == PACKET_OK)
10655         {
10656           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10657             target_crc = target_crc * 16 + fromhex (*tmp);
10658
10659           return (host_crc == target_crc);
10660         }
10661     }
10662
10663   return simple_verify_memory (this, data, lma, size);
10664 }
10665
10666 /* compare-sections command
10667
10668    With no arguments, compares each loadable section in the exec bfd
10669    with the same memory range on the target, and reports mismatches.
10670    Useful for verifying the image on the target against the exec file.  */
10671
10672 static void
10673 compare_sections_command (const char *args, int from_tty)
10674 {
10675   asection *s;
10676   const char *sectname;
10677   bfd_size_type size;
10678   bfd_vma lma;
10679   int matched = 0;
10680   int mismatched = 0;
10681   int res;
10682   int read_only = 0;
10683
10684   if (!exec_bfd)
10685     error (_("command cannot be used without an exec file"));
10686
10687   if (args != NULL && strcmp (args, "-r") == 0)
10688     {
10689       read_only = 1;
10690       args = NULL;
10691     }
10692
10693   for (s = exec_bfd->sections; s; s = s->next)
10694     {
10695       if (!(s->flags & SEC_LOAD))
10696         continue;               /* Skip non-loadable section.  */
10697
10698       if (read_only && (s->flags & SEC_READONLY) == 0)
10699         continue;               /* Skip writeable sections */
10700
10701       size = bfd_get_section_size (s);
10702       if (size == 0)
10703         continue;               /* Skip zero-length section.  */
10704
10705       sectname = bfd_get_section_name (exec_bfd, s);
10706       if (args && strcmp (args, sectname) != 0)
10707         continue;               /* Not the section selected by user.  */
10708
10709       matched = 1;              /* Do this section.  */
10710       lma = s->lma;
10711
10712       gdb::byte_vector sectdata (size);
10713       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10714
10715       res = target_verify_memory (sectdata.data (), lma, size);
10716
10717       if (res == -1)
10718         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10719                paddress (target_gdbarch (), lma),
10720                paddress (target_gdbarch (), lma + size));
10721
10722       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10723                        paddress (target_gdbarch (), lma),
10724                        paddress (target_gdbarch (), lma + size));
10725       if (res)
10726         printf_filtered ("matched.\n");
10727       else
10728         {
10729           printf_filtered ("MIS-MATCHED!\n");
10730           mismatched++;
10731         }
10732     }
10733   if (mismatched > 0)
10734     warning (_("One or more sections of the target image does not match\n\
10735 the loaded file\n"));
10736   if (args && !matched)
10737     printf_filtered (_("No loaded section named '%s'.\n"), args);
10738 }
10739
10740 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10741    into remote target.  The number of bytes written to the remote
10742    target is returned, or -1 for error.  */
10743
10744 target_xfer_status
10745 remote_target::remote_write_qxfer (const char *object_name,
10746                                    const char *annex, const gdb_byte *writebuf,
10747                                    ULONGEST offset, LONGEST len,
10748                                    ULONGEST *xfered_len,
10749                                    struct packet_config *packet)
10750 {
10751   int i, buf_len;
10752   ULONGEST n;
10753   struct remote_state *rs = get_remote_state ();
10754   int max_size = get_memory_write_packet_size (); 
10755
10756   if (packet_config_support (packet) == PACKET_DISABLE)
10757     return TARGET_XFER_E_IO;
10758
10759   /* Insert header.  */
10760   i = snprintf (rs->buf, max_size, 
10761                 "qXfer:%s:write:%s:%s:",
10762                 object_name, annex ? annex : "",
10763                 phex_nz (offset, sizeof offset));
10764   max_size -= (i + 1);
10765
10766   /* Escape as much data as fits into rs->buf.  */
10767   buf_len = remote_escape_output 
10768     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10769
10770   if (putpkt_binary (rs->buf, i + buf_len) < 0
10771       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10772       || packet_ok (rs->buf, packet) != PACKET_OK)
10773     return TARGET_XFER_E_IO;
10774
10775   unpack_varlen_hex (rs->buf, &n);
10776
10777   *xfered_len = n;
10778   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10779 }
10780
10781 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10782    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10783    number of bytes read is returned, or 0 for EOF, or -1 for error.
10784    The number of bytes read may be less than LEN without indicating an
10785    EOF.  PACKET is checked and updated to indicate whether the remote
10786    target supports this object.  */
10787
10788 target_xfer_status
10789 remote_target::remote_read_qxfer (const char *object_name,
10790                                   const char *annex,
10791                                   gdb_byte *readbuf, ULONGEST offset,
10792                                   LONGEST len,
10793                                   ULONGEST *xfered_len,
10794                                   struct packet_config *packet)
10795 {
10796   struct remote_state *rs = get_remote_state ();
10797   LONGEST i, n, packet_len;
10798
10799   if (packet_config_support (packet) == PACKET_DISABLE)
10800     return TARGET_XFER_E_IO;
10801
10802   /* Check whether we've cached an end-of-object packet that matches
10803      this request.  */
10804   if (rs->finished_object)
10805     {
10806       if (strcmp (object_name, rs->finished_object) == 0
10807           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10808           && offset == rs->finished_offset)
10809         return TARGET_XFER_EOF;
10810
10811
10812       /* Otherwise, we're now reading something different.  Discard
10813          the cache.  */
10814       xfree (rs->finished_object);
10815       xfree (rs->finished_annex);
10816       rs->finished_object = NULL;
10817       rs->finished_annex = NULL;
10818     }
10819
10820   /* Request only enough to fit in a single packet.  The actual data
10821      may not, since we don't know how much of it will need to be escaped;
10822      the target is free to respond with slightly less data.  We subtract
10823      five to account for the response type and the protocol frame.  */
10824   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10825   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10826             object_name, annex ? annex : "",
10827             phex_nz (offset, sizeof offset),
10828             phex_nz (n, sizeof n));
10829   i = putpkt (rs->buf);
10830   if (i < 0)
10831     return TARGET_XFER_E_IO;
10832
10833   rs->buf[0] = '\0';
10834   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10835   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10836     return TARGET_XFER_E_IO;
10837
10838   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10839     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10840
10841   /* 'm' means there is (or at least might be) more data after this
10842      batch.  That does not make sense unless there's at least one byte
10843      of data in this reply.  */
10844   if (rs->buf[0] == 'm' && packet_len == 1)
10845     error (_("Remote qXfer reply contained no data."));
10846
10847   /* Got some data.  */
10848   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10849                              packet_len - 1, readbuf, n);
10850
10851   /* 'l' is an EOF marker, possibly including a final block of data,
10852      or possibly empty.  If we have the final block of a non-empty
10853      object, record this fact to bypass a subsequent partial read.  */
10854   if (rs->buf[0] == 'l' && offset + i > 0)
10855     {
10856       rs->finished_object = xstrdup (object_name);
10857       rs->finished_annex = xstrdup (annex ? annex : "");
10858       rs->finished_offset = offset + i;
10859     }
10860
10861   if (i == 0)
10862     return TARGET_XFER_EOF;
10863   else
10864     {
10865       *xfered_len = i;
10866       return TARGET_XFER_OK;
10867     }
10868 }
10869
10870 enum target_xfer_status
10871 remote_target::xfer_partial (enum target_object object,
10872                              const char *annex, gdb_byte *readbuf,
10873                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10874                              ULONGEST *xfered_len)
10875 {
10876   struct remote_state *rs;
10877   int i;
10878   char *p2;
10879   char query_type;
10880   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10881
10882   set_remote_traceframe ();
10883   set_general_thread (inferior_ptid);
10884
10885   rs = get_remote_state ();
10886
10887   /* Handle memory using the standard memory routines.  */
10888   if (object == TARGET_OBJECT_MEMORY)
10889     {
10890       /* If the remote target is connected but not running, we should
10891          pass this request down to a lower stratum (e.g. the executable
10892          file).  */
10893       if (!target_has_execution)
10894         return TARGET_XFER_EOF;
10895
10896       if (writebuf != NULL)
10897         return remote_write_bytes (offset, writebuf, len, unit_size,
10898                                    xfered_len);
10899       else
10900         return remote_read_bytes (offset, readbuf, len, unit_size,
10901                                   xfered_len);
10902     }
10903
10904   /* Handle SPU memory using qxfer packets.  */
10905   if (object == TARGET_OBJECT_SPU)
10906     {
10907       if (readbuf)
10908         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10909                                   xfered_len, &remote_protocol_packets
10910                                   [PACKET_qXfer_spu_read]);
10911       else
10912         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10913                                    xfered_len, &remote_protocol_packets
10914                                    [PACKET_qXfer_spu_write]);
10915     }
10916
10917   /* Handle extra signal info using qxfer packets.  */
10918   if (object == TARGET_OBJECT_SIGNAL_INFO)
10919     {
10920       if (readbuf)
10921         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10922                                   xfered_len, &remote_protocol_packets
10923                                   [PACKET_qXfer_siginfo_read]);
10924       else
10925         return remote_write_qxfer ("siginfo", annex,
10926                                    writebuf, offset, len, xfered_len,
10927                                    &remote_protocol_packets
10928                                    [PACKET_qXfer_siginfo_write]);
10929     }
10930
10931   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10932     {
10933       if (readbuf)
10934         return remote_read_qxfer ("statictrace", annex,
10935                                   readbuf, offset, len, xfered_len,
10936                                   &remote_protocol_packets
10937                                   [PACKET_qXfer_statictrace_read]);
10938       else
10939         return TARGET_XFER_E_IO;
10940     }
10941
10942   /* Only handle flash writes.  */
10943   if (writebuf != NULL)
10944     {
10945       switch (object)
10946         {
10947         case TARGET_OBJECT_FLASH:
10948           return remote_flash_write (offset, len, xfered_len,
10949                                      writebuf);
10950
10951         default:
10952           return TARGET_XFER_E_IO;
10953         }
10954     }
10955
10956   /* Map pre-existing objects onto letters.  DO NOT do this for new
10957      objects!!!  Instead specify new query packets.  */
10958   switch (object)
10959     {
10960     case TARGET_OBJECT_AVR:
10961       query_type = 'R';
10962       break;
10963
10964     case TARGET_OBJECT_AUXV:
10965       gdb_assert (annex == NULL);
10966       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10967                                 xfered_len,
10968                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10969
10970     case TARGET_OBJECT_AVAILABLE_FEATURES:
10971       return remote_read_qxfer
10972         ("features", annex, readbuf, offset, len, xfered_len,
10973          &remote_protocol_packets[PACKET_qXfer_features]);
10974
10975     case TARGET_OBJECT_LIBRARIES:
10976       return remote_read_qxfer
10977         ("libraries", annex, readbuf, offset, len, xfered_len,
10978          &remote_protocol_packets[PACKET_qXfer_libraries]);
10979
10980     case TARGET_OBJECT_LIBRARIES_SVR4:
10981       return remote_read_qxfer
10982         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10983          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10984
10985     case TARGET_OBJECT_MEMORY_MAP:
10986       gdb_assert (annex == NULL);
10987       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10988                                  xfered_len,
10989                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10990
10991     case TARGET_OBJECT_OSDATA:
10992       /* Should only get here if we're connected.  */
10993       gdb_assert (rs->remote_desc);
10994       return remote_read_qxfer
10995         ("osdata", annex, readbuf, offset, len, xfered_len,
10996         &remote_protocol_packets[PACKET_qXfer_osdata]);
10997
10998     case TARGET_OBJECT_THREADS:
10999       gdb_assert (annex == NULL);
11000       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11001                                 xfered_len,
11002                                 &remote_protocol_packets[PACKET_qXfer_threads]);
11003
11004     case TARGET_OBJECT_TRACEFRAME_INFO:
11005       gdb_assert (annex == NULL);
11006       return remote_read_qxfer
11007         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11008          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11009
11010     case TARGET_OBJECT_FDPIC:
11011       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11012                                 xfered_len,
11013                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11014
11015     case TARGET_OBJECT_OPENVMS_UIB:
11016       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11017                                 xfered_len,
11018                                 &remote_protocol_packets[PACKET_qXfer_uib]);
11019
11020     case TARGET_OBJECT_BTRACE:
11021       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11022                                 xfered_len,
11023         &remote_protocol_packets[PACKET_qXfer_btrace]);
11024
11025     case TARGET_OBJECT_BTRACE_CONF:
11026       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11027                                 len, xfered_len,
11028         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11029
11030     case TARGET_OBJECT_EXEC_FILE:
11031       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11032                                 len, xfered_len,
11033         &remote_protocol_packets[PACKET_qXfer_exec_file]);
11034
11035     default:
11036       return TARGET_XFER_E_IO;
11037     }
11038
11039   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
11040      large enough let the caller deal with it.  */
11041   if (len < get_remote_packet_size ())
11042     return TARGET_XFER_E_IO;
11043   len = get_remote_packet_size ();
11044
11045   /* Except for querying the minimum buffer size, target must be open.  */
11046   if (!rs->remote_desc)
11047     error (_("remote query is only available after target open"));
11048
11049   gdb_assert (annex != NULL);
11050   gdb_assert (readbuf != NULL);
11051
11052   p2 = rs->buf;
11053   *p2++ = 'q';
11054   *p2++ = query_type;
11055
11056   /* We used one buffer char for the remote protocol q command and
11057      another for the query type.  As the remote protocol encapsulation
11058      uses 4 chars plus one extra in case we are debugging
11059      (remote_debug), we have PBUFZIZ - 7 left to pack the query
11060      string.  */
11061   i = 0;
11062   while (annex[i] && (i < (get_remote_packet_size () - 8)))
11063     {
11064       /* Bad caller may have sent forbidden characters.  */
11065       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11066       *p2++ = annex[i];
11067       i++;
11068     }
11069   *p2 = '\0';
11070   gdb_assert (annex[i] == '\0');
11071
11072   i = putpkt (rs->buf);
11073   if (i < 0)
11074     return TARGET_XFER_E_IO;
11075
11076   getpkt (&rs->buf, &rs->buf_size, 0);
11077   strcpy ((char *) readbuf, rs->buf);
11078
11079   *xfered_len = strlen ((char *) readbuf);
11080   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11081 }
11082
11083 /* Implementation of to_get_memory_xfer_limit.  */
11084
11085 ULONGEST
11086 remote_target::get_memory_xfer_limit ()
11087 {
11088   return get_memory_write_packet_size ();
11089 }
11090
11091 int
11092 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11093                               const gdb_byte *pattern, ULONGEST pattern_len,
11094                               CORE_ADDR *found_addrp)
11095 {
11096   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11097   struct remote_state *rs = get_remote_state ();
11098   int max_size = get_memory_write_packet_size ();
11099   struct packet_config *packet =
11100     &remote_protocol_packets[PACKET_qSearch_memory];
11101   /* Number of packet bytes used to encode the pattern;
11102      this could be more than PATTERN_LEN due to escape characters.  */
11103   int escaped_pattern_len;
11104   /* Amount of pattern that was encodable in the packet.  */
11105   int used_pattern_len;
11106   int i;
11107   int found;
11108   ULONGEST found_addr;
11109
11110   /* Don't go to the target if we don't have to.  This is done before
11111      checking packet_config_support to avoid the possibility that a
11112      success for this edge case means the facility works in
11113      general.  */
11114   if (pattern_len > search_space_len)
11115     return 0;
11116   if (pattern_len == 0)
11117     {
11118       *found_addrp = start_addr;
11119       return 1;
11120     }
11121
11122   /* If we already know the packet isn't supported, fall back to the simple
11123      way of searching memory.  */
11124
11125   if (packet_config_support (packet) == PACKET_DISABLE)
11126     {
11127       /* Target doesn't provided special support, fall back and use the
11128          standard support (copy memory and do the search here).  */
11129       return simple_search_memory (this, start_addr, search_space_len,
11130                                    pattern, pattern_len, found_addrp);
11131     }
11132
11133   /* Make sure the remote is pointing at the right process.  */
11134   set_general_process ();
11135
11136   /* Insert header.  */
11137   i = snprintf (rs->buf, max_size, 
11138                 "qSearch:memory:%s;%s;",
11139                 phex_nz (start_addr, addr_size),
11140                 phex_nz (search_space_len, sizeof (search_space_len)));
11141   max_size -= (i + 1);
11142
11143   /* Escape as much data as fits into rs->buf.  */
11144   escaped_pattern_len =
11145     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11146                           &used_pattern_len, max_size);
11147
11148   /* Bail if the pattern is too large.  */
11149   if (used_pattern_len != pattern_len)
11150     error (_("Pattern is too large to transmit to remote target."));
11151
11152   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11153       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11154       || packet_ok (rs->buf, packet) != PACKET_OK)
11155     {
11156       /* The request may not have worked because the command is not
11157          supported.  If so, fall back to the simple way.  */
11158       if (packet_config_support (packet) == PACKET_DISABLE)
11159         {
11160           return simple_search_memory (this, start_addr, search_space_len,
11161                                        pattern, pattern_len, found_addrp);
11162         }
11163       return -1;
11164     }
11165
11166   if (rs->buf[0] == '0')
11167     found = 0;
11168   else if (rs->buf[0] == '1')
11169     {
11170       found = 1;
11171       if (rs->buf[1] != ',')
11172         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11173       unpack_varlen_hex (rs->buf + 2, &found_addr);
11174       *found_addrp = found_addr;
11175     }
11176   else
11177     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11178
11179   return found;
11180 }
11181
11182 void
11183 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11184 {
11185   struct remote_state *rs = get_remote_state ();
11186   char *p = rs->buf;
11187
11188   if (!rs->remote_desc)
11189     error (_("remote rcmd is only available after target open"));
11190
11191   /* Send a NULL command across as an empty command.  */
11192   if (command == NULL)
11193     command = "";
11194
11195   /* The query prefix.  */
11196   strcpy (rs->buf, "qRcmd,");
11197   p = strchr (rs->buf, '\0');
11198
11199   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11200       > get_remote_packet_size ())
11201     error (_("\"monitor\" command ``%s'' is too long."), command);
11202
11203   /* Encode the actual command.  */
11204   bin2hex ((const gdb_byte *) command, p, strlen (command));
11205
11206   if (putpkt (rs->buf) < 0)
11207     error (_("Communication problem with target."));
11208
11209   /* get/display the response */
11210   while (1)
11211     {
11212       char *buf;
11213
11214       /* XXX - see also remote_get_noisy_reply().  */
11215       QUIT;                     /* Allow user to bail out with ^C.  */
11216       rs->buf[0] = '\0';
11217       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11218         { 
11219           /* Timeout.  Continue to (try to) read responses.
11220              This is better than stopping with an error, assuming the stub
11221              is still executing the (long) monitor command.
11222              If needed, the user can interrupt gdb using C-c, obtaining
11223              an effect similar to stop on timeout.  */
11224           continue;
11225         }
11226       buf = rs->buf;
11227       if (buf[0] == '\0')
11228         error (_("Target does not support this command."));
11229       if (buf[0] == 'O' && buf[1] != 'K')
11230         {
11231           remote_console_output (buf + 1); /* 'O' message from stub.  */
11232           continue;
11233         }
11234       if (strcmp (buf, "OK") == 0)
11235         break;
11236       if (strlen (buf) == 3 && buf[0] == 'E'
11237           && isdigit (buf[1]) && isdigit (buf[2]))
11238         {
11239           error (_("Protocol error with Rcmd"));
11240         }
11241       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11242         {
11243           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11244
11245           fputc_unfiltered (c, outbuf);
11246         }
11247       break;
11248     }
11249 }
11250
11251 std::vector<mem_region>
11252 remote_target::memory_map ()
11253 {
11254   std::vector<mem_region> result;
11255   gdb::optional<gdb::char_vector> text
11256     = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11257
11258   if (text)
11259     result = parse_memory_map (text->data ());
11260
11261   return result;
11262 }
11263
11264 static void
11265 packet_command (const char *args, int from_tty)
11266 {
11267   remote_target *remote = get_current_remote_target ();
11268
11269   if (remote == nullptr)
11270     error (_("command can only be used with remote target"));
11271
11272   remote->packet_command (args, from_tty);
11273 }
11274
11275 void
11276 remote_target::packet_command (const char *args, int from_tty)
11277 {
11278   if (!args)
11279     error (_("remote-packet command requires packet text as argument"));
11280
11281   puts_filtered ("sending: ");
11282   print_packet (args);
11283   puts_filtered ("\n");
11284   putpkt (args);
11285
11286   remote_state *rs = get_remote_state ();
11287
11288   getpkt (&rs->buf, &rs->buf_size, 0);
11289   puts_filtered ("received: ");
11290   print_packet (rs->buf);
11291   puts_filtered ("\n");
11292 }
11293
11294 #if 0
11295 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11296
11297 static void display_thread_info (struct gdb_ext_thread_info *info);
11298
11299 static void threadset_test_cmd (char *cmd, int tty);
11300
11301 static void threadalive_test (char *cmd, int tty);
11302
11303 static void threadlist_test_cmd (char *cmd, int tty);
11304
11305 int get_and_display_threadinfo (threadref *ref);
11306
11307 static void threadinfo_test_cmd (char *cmd, int tty);
11308
11309 static int thread_display_step (threadref *ref, void *context);
11310
11311 static void threadlist_update_test_cmd (char *cmd, int tty);
11312
11313 static void init_remote_threadtests (void);
11314
11315 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11316
11317 static void
11318 threadset_test_cmd (const char *cmd, int tty)
11319 {
11320   int sample_thread = SAMPLE_THREAD;
11321
11322   printf_filtered (_("Remote threadset test\n"));
11323   set_general_thread (sample_thread);
11324 }
11325
11326
11327 static void
11328 threadalive_test (const char *cmd, int tty)
11329 {
11330   int sample_thread = SAMPLE_THREAD;
11331   int pid = inferior_ptid.pid ();
11332   ptid_t ptid = ptid_t (pid, sample_thread, 0);
11333
11334   if (remote_thread_alive (ptid))
11335     printf_filtered ("PASS: Thread alive test\n");
11336   else
11337     printf_filtered ("FAIL: Thread alive test\n");
11338 }
11339
11340 void output_threadid (char *title, threadref *ref);
11341
11342 void
11343 output_threadid (char *title, threadref *ref)
11344 {
11345   char hexid[20];
11346
11347   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11348   hexid[16] = 0;
11349   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11350 }
11351
11352 static void
11353 threadlist_test_cmd (const char *cmd, int tty)
11354 {
11355   int startflag = 1;
11356   threadref nextthread;
11357   int done, result_count;
11358   threadref threadlist[3];
11359
11360   printf_filtered ("Remote Threadlist test\n");
11361   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11362                               &result_count, &threadlist[0]))
11363     printf_filtered ("FAIL: threadlist test\n");
11364   else
11365     {
11366       threadref *scan = threadlist;
11367       threadref *limit = scan + result_count;
11368
11369       while (scan < limit)
11370         output_threadid (" thread ", scan++);
11371     }
11372 }
11373
11374 void
11375 display_thread_info (struct gdb_ext_thread_info *info)
11376 {
11377   output_threadid ("Threadid: ", &info->threadid);
11378   printf_filtered ("Name: %s\n ", info->shortname);
11379   printf_filtered ("State: %s\n", info->display);
11380   printf_filtered ("other: %s\n\n", info->more_display);
11381 }
11382
11383 int
11384 get_and_display_threadinfo (threadref *ref)
11385 {
11386   int result;
11387   int set;
11388   struct gdb_ext_thread_info threadinfo;
11389
11390   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11391     | TAG_MOREDISPLAY | TAG_DISPLAY;
11392   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11393     display_thread_info (&threadinfo);
11394   return result;
11395 }
11396
11397 static void
11398 threadinfo_test_cmd (const char *cmd, int tty)
11399 {
11400   int athread = SAMPLE_THREAD;
11401   threadref thread;
11402   int set;
11403
11404   int_to_threadref (&thread, athread);
11405   printf_filtered ("Remote Threadinfo test\n");
11406   if (!get_and_display_threadinfo (&thread))
11407     printf_filtered ("FAIL cannot get thread info\n");
11408 }
11409
11410 static int
11411 thread_display_step (threadref *ref, void *context)
11412 {
11413   /* output_threadid(" threadstep ",ref); *//* simple test */
11414   return get_and_display_threadinfo (ref);
11415 }
11416
11417 static void
11418 threadlist_update_test_cmd (const char *cmd, int tty)
11419 {
11420   printf_filtered ("Remote Threadlist update test\n");
11421   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11422 }
11423
11424 static void
11425 init_remote_threadtests (void)
11426 {
11427   add_com ("tlist", class_obscure, threadlist_test_cmd,
11428            _("Fetch and print the remote list of "
11429              "thread identifiers, one pkt only"));
11430   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11431            _("Fetch and display info about one thread"));
11432   add_com ("tset", class_obscure, threadset_test_cmd,
11433            _("Test setting to a different thread"));
11434   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11435            _("Iterate through updating all remote thread info"));
11436   add_com ("talive", class_obscure, threadalive_test,
11437            _(" Remote thread alive test "));
11438 }
11439
11440 #endif /* 0 */
11441
11442 /* Convert a thread ID to a string.  Returns the string in a static
11443    buffer.  */
11444
11445 const char *
11446 remote_target::pid_to_str (ptid_t ptid)
11447 {
11448   static char buf[64];
11449   struct remote_state *rs = get_remote_state ();
11450
11451   if (ptid == null_ptid)
11452     return normal_pid_to_str (ptid);
11453   else if (ptid.is_pid ())
11454     {
11455       /* Printing an inferior target id.  */
11456
11457       /* When multi-process extensions are off, there's no way in the
11458          remote protocol to know the remote process id, if there's any
11459          at all.  There's one exception --- when we're connected with
11460          target extended-remote, and we manually attached to a process
11461          with "attach PID".  We don't record anywhere a flag that
11462          allows us to distinguish that case from the case of
11463          connecting with extended-remote and the stub already being
11464          attached to a process, and reporting yes to qAttached, hence
11465          no smart special casing here.  */
11466       if (!remote_multi_process_p (rs))
11467         {
11468           xsnprintf (buf, sizeof buf, "Remote target");
11469           return buf;
11470         }
11471
11472       return normal_pid_to_str (ptid);
11473     }
11474   else
11475     {
11476       if (magic_null_ptid == ptid)
11477         xsnprintf (buf, sizeof buf, "Thread <main>");
11478       else if (remote_multi_process_p (rs))
11479         if (ptid.lwp () == 0)
11480           return normal_pid_to_str (ptid);
11481         else
11482           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11483                      ptid.pid (), ptid.lwp ());
11484       else
11485         xsnprintf (buf, sizeof buf, "Thread %ld",
11486                    ptid.lwp ());
11487       return buf;
11488     }
11489 }
11490
11491 /* Get the address of the thread local variable in OBJFILE which is
11492    stored at OFFSET within the thread local storage for thread PTID.  */
11493
11494 CORE_ADDR
11495 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11496                                          CORE_ADDR offset)
11497 {
11498   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11499     {
11500       struct remote_state *rs = get_remote_state ();
11501       char *p = rs->buf;
11502       char *endp = rs->buf + get_remote_packet_size ();
11503       enum packet_result result;
11504
11505       strcpy (p, "qGetTLSAddr:");
11506       p += strlen (p);
11507       p = write_ptid (p, endp, ptid);
11508       *p++ = ',';
11509       p += hexnumstr (p, offset);
11510       *p++ = ',';
11511       p += hexnumstr (p, lm);
11512       *p++ = '\0';
11513
11514       putpkt (rs->buf);
11515       getpkt (&rs->buf, &rs->buf_size, 0);
11516       result = packet_ok (rs->buf,
11517                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11518       if (result == PACKET_OK)
11519         {
11520           ULONGEST result;
11521
11522           unpack_varlen_hex (rs->buf, &result);
11523           return result;
11524         }
11525       else if (result == PACKET_UNKNOWN)
11526         throw_error (TLS_GENERIC_ERROR,
11527                      _("Remote target doesn't support qGetTLSAddr packet"));
11528       else
11529         throw_error (TLS_GENERIC_ERROR,
11530                      _("Remote target failed to process qGetTLSAddr request"));
11531     }
11532   else
11533     throw_error (TLS_GENERIC_ERROR,
11534                  _("TLS not supported or disabled on this target"));
11535   /* Not reached.  */
11536   return 0;
11537 }
11538
11539 /* Provide thread local base, i.e. Thread Information Block address.
11540    Returns 1 if ptid is found and thread_local_base is non zero.  */
11541
11542 bool
11543 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11544 {
11545   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11546     {
11547       struct remote_state *rs = get_remote_state ();
11548       char *p = rs->buf;
11549       char *endp = rs->buf + get_remote_packet_size ();
11550       enum packet_result result;
11551
11552       strcpy (p, "qGetTIBAddr:");
11553       p += strlen (p);
11554       p = write_ptid (p, endp, ptid);
11555       *p++ = '\0';
11556
11557       putpkt (rs->buf);
11558       getpkt (&rs->buf, &rs->buf_size, 0);
11559       result = packet_ok (rs->buf,
11560                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11561       if (result == PACKET_OK)
11562         {
11563           ULONGEST result;
11564
11565           unpack_varlen_hex (rs->buf, &result);
11566           if (addr)
11567             *addr = (CORE_ADDR) result;
11568           return true;
11569         }
11570       else if (result == PACKET_UNKNOWN)
11571         error (_("Remote target doesn't support qGetTIBAddr packet"));
11572       else
11573         error (_("Remote target failed to process qGetTIBAddr request"));
11574     }
11575   else
11576     error (_("qGetTIBAddr not supported or disabled on this target"));
11577   /* Not reached.  */
11578   return false;
11579 }
11580
11581 /* Support for inferring a target description based on the current
11582    architecture and the size of a 'g' packet.  While the 'g' packet
11583    can have any size (since optional registers can be left off the
11584    end), some sizes are easily recognizable given knowledge of the
11585    approximate architecture.  */
11586
11587 struct remote_g_packet_guess
11588 {
11589   int bytes;
11590   const struct target_desc *tdesc;
11591 };
11592 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11593 DEF_VEC_O(remote_g_packet_guess_s);
11594
11595 struct remote_g_packet_data
11596 {
11597   VEC(remote_g_packet_guess_s) *guesses;
11598 };
11599
11600 static struct gdbarch_data *remote_g_packet_data_handle;
11601
11602 static void *
11603 remote_g_packet_data_init (struct obstack *obstack)
11604 {
11605   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11606 }
11607
11608 void
11609 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11610                                 const struct target_desc *tdesc)
11611 {
11612   struct remote_g_packet_data *data
11613     = ((struct remote_g_packet_data *)
11614        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11615   struct remote_g_packet_guess new_guess, *guess;
11616   int ix;
11617
11618   gdb_assert (tdesc != NULL);
11619
11620   for (ix = 0;
11621        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11622        ix++)
11623     if (guess->bytes == bytes)
11624       internal_error (__FILE__, __LINE__,
11625                       _("Duplicate g packet description added for size %d"),
11626                       bytes);
11627
11628   new_guess.bytes = bytes;
11629   new_guess.tdesc = tdesc;
11630   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11631 }
11632
11633 /* Return 1 if remote_read_description would do anything on this target
11634    and architecture, 0 otherwise.  */
11635
11636 static int
11637 remote_read_description_p (struct target_ops *target)
11638 {
11639   struct remote_g_packet_data *data
11640     = ((struct remote_g_packet_data *)
11641        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11642
11643   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11644     return 1;
11645
11646   return 0;
11647 }
11648
11649 const struct target_desc *
11650 remote_target::read_description ()
11651 {
11652   struct remote_g_packet_data *data
11653     = ((struct remote_g_packet_data *)
11654        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11655
11656   /* Do not try this during initial connection, when we do not know
11657      whether there is a running but stopped thread.  */
11658   if (!target_has_execution || inferior_ptid == null_ptid)
11659     return beneath ()->read_description ();
11660
11661   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11662     {
11663       struct remote_g_packet_guess *guess;
11664       int ix;
11665       int bytes = send_g_packet ();
11666
11667       for (ix = 0;
11668            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11669            ix++)
11670         if (guess->bytes == bytes)
11671           return guess->tdesc;
11672
11673       /* We discard the g packet.  A minor optimization would be to
11674          hold on to it, and fill the register cache once we have selected
11675          an architecture, but it's too tricky to do safely.  */
11676     }
11677
11678   return beneath ()->read_description ();
11679 }
11680
11681 /* Remote file transfer support.  This is host-initiated I/O, not
11682    target-initiated; for target-initiated, see remote-fileio.c.  */
11683
11684 /* If *LEFT is at least the length of STRING, copy STRING to
11685    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11686    decrease *LEFT.  Otherwise raise an error.  */
11687
11688 static void
11689 remote_buffer_add_string (char **buffer, int *left, const char *string)
11690 {
11691   int len = strlen (string);
11692
11693   if (len > *left)
11694     error (_("Packet too long for target."));
11695
11696   memcpy (*buffer, string, len);
11697   *buffer += len;
11698   *left -= len;
11699
11700   /* NUL-terminate the buffer as a convenience, if there is
11701      room.  */
11702   if (*left)
11703     **buffer = '\0';
11704 }
11705
11706 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11707    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11708    decrease *LEFT.  Otherwise raise an error.  */
11709
11710 static void
11711 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11712                          int len)
11713 {
11714   if (2 * len > *left)
11715     error (_("Packet too long for target."));
11716
11717   bin2hex (bytes, *buffer, len);
11718   *buffer += 2 * len;
11719   *left -= 2 * len;
11720
11721   /* NUL-terminate the buffer as a convenience, if there is
11722      room.  */
11723   if (*left)
11724     **buffer = '\0';
11725 }
11726
11727 /* If *LEFT is large enough, convert VALUE to hex and add it to
11728    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11729    decrease *LEFT.  Otherwise raise an error.  */
11730
11731 static void
11732 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11733 {
11734   int len = hexnumlen (value);
11735
11736   if (len > *left)
11737     error (_("Packet too long for target."));
11738
11739   hexnumstr (*buffer, value);
11740   *buffer += len;
11741   *left -= len;
11742
11743   /* NUL-terminate the buffer as a convenience, if there is
11744      room.  */
11745   if (*left)
11746     **buffer = '\0';
11747 }
11748
11749 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11750    value, *REMOTE_ERRNO to the remote error number or zero if none
11751    was included, and *ATTACHMENT to point to the start of the annex
11752    if any.  The length of the packet isn't needed here; there may
11753    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11754
11755    Return 0 if the packet could be parsed, -1 if it could not.  If
11756    -1 is returned, the other variables may not be initialized.  */
11757
11758 static int
11759 remote_hostio_parse_result (char *buffer, int *retcode,
11760                             int *remote_errno, char **attachment)
11761 {
11762   char *p, *p2;
11763
11764   *remote_errno = 0;
11765   *attachment = NULL;
11766
11767   if (buffer[0] != 'F')
11768     return -1;
11769
11770   errno = 0;
11771   *retcode = strtol (&buffer[1], &p, 16);
11772   if (errno != 0 || p == &buffer[1])
11773     return -1;
11774
11775   /* Check for ",errno".  */
11776   if (*p == ',')
11777     {
11778       errno = 0;
11779       *remote_errno = strtol (p + 1, &p2, 16);
11780       if (errno != 0 || p + 1 == p2)
11781         return -1;
11782       p = p2;
11783     }
11784
11785   /* Check for ";attachment".  If there is no attachment, the
11786      packet should end here.  */
11787   if (*p == ';')
11788     {
11789       *attachment = p + 1;
11790       return 0;
11791     }
11792   else if (*p == '\0')
11793     return 0;
11794   else
11795     return -1;
11796 }
11797
11798 /* Send a prepared I/O packet to the target and read its response.
11799    The prepared packet is in the global RS->BUF before this function
11800    is called, and the answer is there when we return.
11801
11802    COMMAND_BYTES is the length of the request to send, which may include
11803    binary data.  WHICH_PACKET is the packet configuration to check
11804    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11805    is set to the error number and -1 is returned.  Otherwise the value
11806    returned by the function is returned.
11807
11808    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11809    attachment is expected; an error will be reported if there's a
11810    mismatch.  If one is found, *ATTACHMENT will be set to point into
11811    the packet buffer and *ATTACHMENT_LEN will be set to the
11812    attachment's length.  */
11813
11814 int
11815 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11816                                            int *remote_errno, char **attachment,
11817                                            int *attachment_len)
11818 {
11819   struct remote_state *rs = get_remote_state ();
11820   int ret, bytes_read;
11821   char *attachment_tmp;
11822
11823   if (packet_support (which_packet) == PACKET_DISABLE)
11824     {
11825       *remote_errno = FILEIO_ENOSYS;
11826       return -1;
11827     }
11828
11829   putpkt_binary (rs->buf, command_bytes);
11830   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11831
11832   /* If it timed out, something is wrong.  Don't try to parse the
11833      buffer.  */
11834   if (bytes_read < 0)
11835     {
11836       *remote_errno = FILEIO_EINVAL;
11837       return -1;
11838     }
11839
11840   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11841     {
11842     case PACKET_ERROR:
11843       *remote_errno = FILEIO_EINVAL;
11844       return -1;
11845     case PACKET_UNKNOWN:
11846       *remote_errno = FILEIO_ENOSYS;
11847       return -1;
11848     case PACKET_OK:
11849       break;
11850     }
11851
11852   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11853                                   &attachment_tmp))
11854     {
11855       *remote_errno = FILEIO_EINVAL;
11856       return -1;
11857     }
11858
11859   /* Make sure we saw an attachment if and only if we expected one.  */
11860   if ((attachment_tmp == NULL && attachment != NULL)
11861       || (attachment_tmp != NULL && attachment == NULL))
11862     {
11863       *remote_errno = FILEIO_EINVAL;
11864       return -1;
11865     }
11866
11867   /* If an attachment was found, it must point into the packet buffer;
11868      work out how many bytes there were.  */
11869   if (attachment_tmp != NULL)
11870     {
11871       *attachment = attachment_tmp;
11872       *attachment_len = bytes_read - (*attachment - rs->buf);
11873     }
11874
11875   return ret;
11876 }
11877
11878 /* See declaration.h.  */
11879
11880 void
11881 readahead_cache::invalidate ()
11882 {
11883   this->fd = -1;
11884 }
11885
11886 /* See declaration.h.  */
11887
11888 void
11889 readahead_cache::invalidate_fd (int fd)
11890 {
11891   if (this->fd == fd)
11892     this->fd = -1;
11893 }
11894
11895 /* Set the filesystem remote_hostio functions that take FILENAME
11896    arguments will use.  Return 0 on success, or -1 if an error
11897    occurs (and set *REMOTE_ERRNO).  */
11898
11899 int
11900 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11901                                              int *remote_errno)
11902 {
11903   struct remote_state *rs = get_remote_state ();
11904   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11905   char *p = rs->buf;
11906   int left = get_remote_packet_size () - 1;
11907   char arg[9];
11908   int ret;
11909
11910   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11911     return 0;
11912
11913   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11914     return 0;
11915
11916   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11917
11918   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11919   remote_buffer_add_string (&p, &left, arg);
11920
11921   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11922                                     remote_errno, NULL, NULL);
11923
11924   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11925     return 0;
11926
11927   if (ret == 0)
11928     rs->fs_pid = required_pid;
11929
11930   return ret;
11931 }
11932
11933 /* Implementation of to_fileio_open.  */
11934
11935 int
11936 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11937                                    int flags, int mode, int warn_if_slow,
11938                                    int *remote_errno)
11939 {
11940   struct remote_state *rs = get_remote_state ();
11941   char *p = rs->buf;
11942   int left = get_remote_packet_size () - 1;
11943
11944   if (warn_if_slow)
11945     {
11946       static int warning_issued = 0;
11947
11948       printf_unfiltered (_("Reading %s from remote target...\n"),
11949                          filename);
11950
11951       if (!warning_issued)
11952         {
11953           warning (_("File transfers from remote targets can be slow."
11954                      " Use \"set sysroot\" to access files locally"
11955                      " instead."));
11956           warning_issued = 1;
11957         }
11958     }
11959
11960   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11961     return -1;
11962
11963   remote_buffer_add_string (&p, &left, "vFile:open:");
11964
11965   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11966                            strlen (filename));
11967   remote_buffer_add_string (&p, &left, ",");
11968
11969   remote_buffer_add_int (&p, &left, flags);
11970   remote_buffer_add_string (&p, &left, ",");
11971
11972   remote_buffer_add_int (&p, &left, mode);
11973
11974   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11975                                      remote_errno, NULL, NULL);
11976 }
11977
11978 int
11979 remote_target::fileio_open (struct inferior *inf, const char *filename,
11980                             int flags, int mode, int warn_if_slow,
11981                             int *remote_errno)
11982 {
11983   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
11984                              remote_errno);
11985 }
11986
11987 /* Implementation of to_fileio_pwrite.  */
11988
11989 int
11990 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11991                                      ULONGEST offset, int *remote_errno)
11992 {
11993   struct remote_state *rs = get_remote_state ();
11994   char *p = rs->buf;
11995   int left = get_remote_packet_size ();
11996   int out_len;
11997
11998   rs->readahead_cache.invalidate_fd (fd);
11999
12000   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12001
12002   remote_buffer_add_int (&p, &left, fd);
12003   remote_buffer_add_string (&p, &left, ",");
12004
12005   remote_buffer_add_int (&p, &left, offset);
12006   remote_buffer_add_string (&p, &left, ",");
12007
12008   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12009                              get_remote_packet_size () - (p - rs->buf));
12010
12011   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12012                                      remote_errno, NULL, NULL);
12013 }
12014
12015 int
12016 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12017                               ULONGEST offset, int *remote_errno)
12018 {
12019   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12020 }
12021
12022 /* Helper for the implementation of to_fileio_pread.  Read the file
12023    from the remote side with vFile:pread.  */
12024
12025 int
12026 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12027                                           ULONGEST offset, int *remote_errno)
12028 {
12029   struct remote_state *rs = get_remote_state ();
12030   char *p = rs->buf;
12031   char *attachment;
12032   int left = get_remote_packet_size ();
12033   int ret, attachment_len;
12034   int read_len;
12035
12036   remote_buffer_add_string (&p, &left, "vFile:pread:");
12037
12038   remote_buffer_add_int (&p, &left, fd);
12039   remote_buffer_add_string (&p, &left, ",");
12040
12041   remote_buffer_add_int (&p, &left, len);
12042   remote_buffer_add_string (&p, &left, ",");
12043
12044   remote_buffer_add_int (&p, &left, offset);
12045
12046   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12047                                     remote_errno, &attachment,
12048                                     &attachment_len);
12049
12050   if (ret < 0)
12051     return ret;
12052
12053   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12054                                     read_buf, len);
12055   if (read_len != ret)
12056     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12057
12058   return ret;
12059 }
12060
12061 /* See declaration.h.  */
12062
12063 int
12064 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12065                         ULONGEST offset)
12066 {
12067   if (this->fd == fd
12068       && this->offset <= offset
12069       && offset < this->offset + this->bufsize)
12070     {
12071       ULONGEST max = this->offset + this->bufsize;
12072
12073       if (offset + len > max)
12074         len = max - offset;
12075
12076       memcpy (read_buf, this->buf + offset - this->offset, len);
12077       return len;
12078     }
12079
12080   return 0;
12081 }
12082
12083 /* Implementation of to_fileio_pread.  */
12084
12085 int
12086 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12087                                     ULONGEST offset, int *remote_errno)
12088 {
12089   int ret;
12090   struct remote_state *rs = get_remote_state ();
12091   readahead_cache *cache = &rs->readahead_cache;
12092
12093   ret = cache->pread (fd, read_buf, len, offset);
12094   if (ret > 0)
12095     {
12096       cache->hit_count++;
12097
12098       if (remote_debug)
12099         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12100                             pulongest (cache->hit_count));
12101       return ret;
12102     }
12103
12104   cache->miss_count++;
12105   if (remote_debug)
12106     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12107                         pulongest (cache->miss_count));
12108
12109   cache->fd = fd;
12110   cache->offset = offset;
12111   cache->bufsize = get_remote_packet_size ();
12112   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12113
12114   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12115                                    cache->offset, remote_errno);
12116   if (ret <= 0)
12117     {
12118       cache->invalidate_fd (fd);
12119       return ret;
12120     }
12121
12122   cache->bufsize = ret;
12123   return cache->pread (fd, read_buf, len, offset);
12124 }
12125
12126 int
12127 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12128                              ULONGEST offset, int *remote_errno)
12129 {
12130   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12131 }
12132
12133 /* Implementation of to_fileio_close.  */
12134
12135 int
12136 remote_target::remote_hostio_close (int fd, int *remote_errno)
12137 {
12138   struct remote_state *rs = get_remote_state ();
12139   char *p = rs->buf;
12140   int left = get_remote_packet_size () - 1;
12141
12142   rs->readahead_cache.invalidate_fd (fd);
12143
12144   remote_buffer_add_string (&p, &left, "vFile:close:");
12145
12146   remote_buffer_add_int (&p, &left, fd);
12147
12148   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12149                                      remote_errno, NULL, NULL);
12150 }
12151
12152 int
12153 remote_target::fileio_close (int fd, int *remote_errno)
12154 {
12155   return remote_hostio_close (fd, remote_errno);
12156 }
12157
12158 /* Implementation of to_fileio_unlink.  */
12159
12160 int
12161 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12162                                      int *remote_errno)
12163 {
12164   struct remote_state *rs = get_remote_state ();
12165   char *p = rs->buf;
12166   int left = get_remote_packet_size () - 1;
12167
12168   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12169     return -1;
12170
12171   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12172
12173   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12174                            strlen (filename));
12175
12176   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12177                                      remote_errno, NULL, NULL);
12178 }
12179
12180 int
12181 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12182                               int *remote_errno)
12183 {
12184   return remote_hostio_unlink (inf, filename, remote_errno);
12185 }
12186
12187 /* Implementation of to_fileio_readlink.  */
12188
12189 gdb::optional<std::string>
12190 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12191                                 int *remote_errno)
12192 {
12193   struct remote_state *rs = get_remote_state ();
12194   char *p = rs->buf;
12195   char *attachment;
12196   int left = get_remote_packet_size ();
12197   int len, attachment_len;
12198   int read_len;
12199
12200   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12201     return {};
12202
12203   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12204
12205   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12206                            strlen (filename));
12207
12208   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12209                                     remote_errno, &attachment,
12210                                     &attachment_len);
12211
12212   if (len < 0)
12213     return {};
12214
12215   std::string ret (len, '\0');
12216
12217   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12218                                     (gdb_byte *) &ret[0], len);
12219   if (read_len != len)
12220     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12221
12222   return ret;
12223 }
12224
12225 /* Implementation of to_fileio_fstat.  */
12226
12227 int
12228 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12229 {
12230   struct remote_state *rs = get_remote_state ();
12231   char *p = rs->buf;
12232   int left = get_remote_packet_size ();
12233   int attachment_len, ret;
12234   char *attachment;
12235   struct fio_stat fst;
12236   int read_len;
12237
12238   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12239
12240   remote_buffer_add_int (&p, &left, fd);
12241
12242   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12243                                     remote_errno, &attachment,
12244                                     &attachment_len);
12245   if (ret < 0)
12246     {
12247       if (*remote_errno != FILEIO_ENOSYS)
12248         return ret;
12249
12250       /* Strictly we should return -1, ENOSYS here, but when
12251          "set sysroot remote:" was implemented in August 2008
12252          BFD's need for a stat function was sidestepped with
12253          this hack.  This was not remedied until March 2015
12254          so we retain the previous behavior to avoid breaking
12255          compatibility.
12256
12257          Note that the memset is a March 2015 addition; older
12258          GDBs set st_size *and nothing else* so the structure
12259          would have garbage in all other fields.  This might
12260          break something but retaining the previous behavior
12261          here would be just too wrong.  */
12262
12263       memset (st, 0, sizeof (struct stat));
12264       st->st_size = INT_MAX;
12265       return 0;
12266     }
12267
12268   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12269                                     (gdb_byte *) &fst, sizeof (fst));
12270
12271   if (read_len != ret)
12272     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12273
12274   if (read_len != sizeof (fst))
12275     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12276            read_len, (int) sizeof (fst));
12277
12278   remote_fileio_to_host_stat (&fst, st);
12279
12280   return 0;
12281 }
12282
12283 /* Implementation of to_filesystem_is_local.  */
12284
12285 bool
12286 remote_target::filesystem_is_local ()
12287 {
12288   /* Valgrind GDB presents itself as a remote target but works
12289      on the local filesystem: it does not implement remote get
12290      and users are not expected to set a sysroot.  To handle
12291      this case we treat the remote filesystem as local if the
12292      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12293      does not support vFile:open.  */
12294   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12295     {
12296       enum packet_support ps = packet_support (PACKET_vFile_open);
12297
12298       if (ps == PACKET_SUPPORT_UNKNOWN)
12299         {
12300           int fd, remote_errno;
12301
12302           /* Try opening a file to probe support.  The supplied
12303              filename is irrelevant, we only care about whether
12304              the stub recognizes the packet or not.  */
12305           fd = remote_hostio_open (NULL, "just probing",
12306                                    FILEIO_O_RDONLY, 0700, 0,
12307                                    &remote_errno);
12308
12309           if (fd >= 0)
12310             remote_hostio_close (fd, &remote_errno);
12311
12312           ps = packet_support (PACKET_vFile_open);
12313         }
12314
12315       if (ps == PACKET_DISABLE)
12316         {
12317           static int warning_issued = 0;
12318
12319           if (!warning_issued)
12320             {
12321               warning (_("remote target does not support file"
12322                          " transfer, attempting to access files"
12323                          " from local filesystem."));
12324               warning_issued = 1;
12325             }
12326
12327           return true;
12328         }
12329     }
12330
12331   return false;
12332 }
12333
12334 static int
12335 remote_fileio_errno_to_host (int errnum)
12336 {
12337   switch (errnum)
12338     {
12339       case FILEIO_EPERM:
12340         return EPERM;
12341       case FILEIO_ENOENT:
12342         return ENOENT;
12343       case FILEIO_EINTR:
12344         return EINTR;
12345       case FILEIO_EIO:
12346         return EIO;
12347       case FILEIO_EBADF:
12348         return EBADF;
12349       case FILEIO_EACCES:
12350         return EACCES;
12351       case FILEIO_EFAULT:
12352         return EFAULT;
12353       case FILEIO_EBUSY:
12354         return EBUSY;
12355       case FILEIO_EEXIST:
12356         return EEXIST;
12357       case FILEIO_ENODEV:
12358         return ENODEV;
12359       case FILEIO_ENOTDIR:
12360         return ENOTDIR;
12361       case FILEIO_EISDIR:
12362         return EISDIR;
12363       case FILEIO_EINVAL:
12364         return EINVAL;
12365       case FILEIO_ENFILE:
12366         return ENFILE;
12367       case FILEIO_EMFILE:
12368         return EMFILE;
12369       case FILEIO_EFBIG:
12370         return EFBIG;
12371       case FILEIO_ENOSPC:
12372         return ENOSPC;
12373       case FILEIO_ESPIPE:
12374         return ESPIPE;
12375       case FILEIO_EROFS:
12376         return EROFS;
12377       case FILEIO_ENOSYS:
12378         return ENOSYS;
12379       case FILEIO_ENAMETOOLONG:
12380         return ENAMETOOLONG;
12381     }
12382   return -1;
12383 }
12384
12385 static char *
12386 remote_hostio_error (int errnum)
12387 {
12388   int host_error = remote_fileio_errno_to_host (errnum);
12389
12390   if (host_error == -1)
12391     error (_("Unknown remote I/O error %d"), errnum);
12392   else
12393     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12394 }
12395
12396 /* A RAII wrapper around a remote file descriptor.  */
12397
12398 class scoped_remote_fd
12399 {
12400 public:
12401   scoped_remote_fd (remote_target *remote, int fd)
12402     : m_remote (remote), m_fd (fd)
12403   {
12404   }
12405
12406   ~scoped_remote_fd ()
12407   {
12408     if (m_fd != -1)
12409       {
12410         try
12411           {
12412             int remote_errno;
12413             m_remote->remote_hostio_close (m_fd, &remote_errno);
12414           }
12415         catch (...)
12416           {
12417             /* Swallow exception before it escapes the dtor.  If
12418                something goes wrong, likely the connection is gone,
12419                and there's nothing else that can be done.  */
12420           }
12421       }
12422   }
12423
12424   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12425
12426   /* Release ownership of the file descriptor, and return it.  */
12427   int release () noexcept
12428   {
12429     int fd = m_fd;
12430     m_fd = -1;
12431     return fd;
12432   }
12433
12434   /* Return the owned file descriptor.  */
12435   int get () const noexcept
12436   {
12437     return m_fd;
12438   }
12439
12440 private:
12441   /* The remote target.  */
12442   remote_target *m_remote;
12443
12444   /* The owned remote I/O file descriptor.  */
12445   int m_fd;
12446 };
12447
12448 void
12449 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12450 {
12451   remote_target *remote = get_current_remote_target ();
12452
12453   if (remote == nullptr)
12454     error (_("command can only be used with remote target"));
12455
12456   remote->remote_file_put (local_file, remote_file, from_tty);
12457 }
12458
12459 void
12460 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12461                                 int from_tty)
12462 {
12463   int retcode, remote_errno, bytes, io_size;
12464   int bytes_in_buffer;
12465   int saw_eof;
12466   ULONGEST offset;
12467
12468   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12469   if (file == NULL)
12470     perror_with_name (local_file);
12471
12472   scoped_remote_fd fd
12473     (this, remote_hostio_open (NULL,
12474                                remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12475                                              | FILEIO_O_TRUNC),
12476                                0700, 0, &remote_errno));
12477   if (fd.get () == -1)
12478     remote_hostio_error (remote_errno);
12479
12480   /* Send up to this many bytes at once.  They won't all fit in the
12481      remote packet limit, so we'll transfer slightly fewer.  */
12482   io_size = get_remote_packet_size ();
12483   gdb::byte_vector buffer (io_size);
12484
12485   bytes_in_buffer = 0;
12486   saw_eof = 0;
12487   offset = 0;
12488   while (bytes_in_buffer || !saw_eof)
12489     {
12490       if (!saw_eof)
12491         {
12492           bytes = fread (buffer.data () + bytes_in_buffer, 1,
12493                          io_size - bytes_in_buffer,
12494                          file.get ());
12495           if (bytes == 0)
12496             {
12497               if (ferror (file.get ()))
12498                 error (_("Error reading %s."), local_file);
12499               else
12500                 {
12501                   /* EOF.  Unless there is something still in the
12502                      buffer from the last iteration, we are done.  */
12503                   saw_eof = 1;
12504                   if (bytes_in_buffer == 0)
12505                     break;
12506                 }
12507             }
12508         }
12509       else
12510         bytes = 0;
12511
12512       bytes += bytes_in_buffer;
12513       bytes_in_buffer = 0;
12514
12515       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12516                                       offset, &remote_errno);
12517
12518       if (retcode < 0)
12519         remote_hostio_error (remote_errno);
12520       else if (retcode == 0)
12521         error (_("Remote write of %d bytes returned 0!"), bytes);
12522       else if (retcode < bytes)
12523         {
12524           /* Short write.  Save the rest of the read data for the next
12525              write.  */
12526           bytes_in_buffer = bytes - retcode;
12527           memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12528         }
12529
12530       offset += retcode;
12531     }
12532
12533   if (remote_hostio_close (fd.release (), &remote_errno))
12534     remote_hostio_error (remote_errno);
12535
12536   if (from_tty)
12537     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12538 }
12539
12540 void
12541 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12542 {
12543   remote_target *remote = get_current_remote_target ();
12544
12545   if (remote == nullptr)
12546     error (_("command can only be used with remote target"));
12547
12548   remote->remote_file_get (remote_file, local_file, from_tty);
12549 }
12550
12551 void
12552 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12553                                 int from_tty)
12554 {
12555   int remote_errno, bytes, io_size;
12556   ULONGEST offset;
12557
12558   scoped_remote_fd fd
12559     (this, remote_hostio_open (NULL,
12560                                remote_file, FILEIO_O_RDONLY, 0, 0,
12561                                &remote_errno));
12562   if (fd.get () == -1)
12563     remote_hostio_error (remote_errno);
12564
12565   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12566   if (file == NULL)
12567     perror_with_name (local_file);
12568
12569   /* Send up to this many bytes at once.  They won't all fit in the
12570      remote packet limit, so we'll transfer slightly fewer.  */
12571   io_size = get_remote_packet_size ();
12572   gdb::byte_vector buffer (io_size);
12573
12574   offset = 0;
12575   while (1)
12576     {
12577       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12578                                    &remote_errno);
12579       if (bytes == 0)
12580         /* Success, but no bytes, means end-of-file.  */
12581         break;
12582       if (bytes == -1)
12583         remote_hostio_error (remote_errno);
12584
12585       offset += bytes;
12586
12587       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12588       if (bytes == 0)
12589         perror_with_name (local_file);
12590     }
12591
12592   if (remote_hostio_close (fd.release (), &remote_errno))
12593     remote_hostio_error (remote_errno);
12594
12595   if (from_tty)
12596     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12597 }
12598
12599 void
12600 remote_file_delete (const char *remote_file, int from_tty)
12601 {
12602   remote_target *remote = get_current_remote_target ();
12603
12604   if (remote == nullptr)
12605     error (_("command can only be used with remote target"));
12606
12607   remote->remote_file_delete (remote_file, from_tty);
12608 }
12609
12610 void
12611 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12612 {
12613   int retcode, remote_errno;
12614
12615   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12616   if (retcode == -1)
12617     remote_hostio_error (remote_errno);
12618
12619   if (from_tty)
12620     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12621 }
12622
12623 static void
12624 remote_put_command (const char *args, int from_tty)
12625 {
12626   if (args == NULL)
12627     error_no_arg (_("file to put"));
12628
12629   gdb_argv argv (args);
12630   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12631     error (_("Invalid parameters to remote put"));
12632
12633   remote_file_put (argv[0], argv[1], from_tty);
12634 }
12635
12636 static void
12637 remote_get_command (const char *args, int from_tty)
12638 {
12639   if (args == NULL)
12640     error_no_arg (_("file to get"));
12641
12642   gdb_argv argv (args);
12643   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12644     error (_("Invalid parameters to remote get"));
12645
12646   remote_file_get (argv[0], argv[1], from_tty);
12647 }
12648
12649 static void
12650 remote_delete_command (const char *args, int from_tty)
12651 {
12652   if (args == NULL)
12653     error_no_arg (_("file to delete"));
12654
12655   gdb_argv argv (args);
12656   if (argv[0] == NULL || argv[1] != NULL)
12657     error (_("Invalid parameters to remote delete"));
12658
12659   remote_file_delete (argv[0], from_tty);
12660 }
12661
12662 static void
12663 remote_command (const char *args, int from_tty)
12664 {
12665   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12666 }
12667
12668 bool
12669 remote_target::can_execute_reverse ()
12670 {
12671   if (packet_support (PACKET_bs) == PACKET_ENABLE
12672       || packet_support (PACKET_bc) == PACKET_ENABLE)
12673     return true;
12674   else
12675     return false;
12676 }
12677
12678 bool
12679 remote_target::supports_non_stop ()
12680 {
12681   return true;
12682 }
12683
12684 bool
12685 remote_target::supports_disable_randomization ()
12686 {
12687   /* Only supported in extended mode.  */
12688   return false;
12689 }
12690
12691 bool
12692 remote_target::supports_multi_process ()
12693 {
12694   struct remote_state *rs = get_remote_state ();
12695
12696   return remote_multi_process_p (rs);
12697 }
12698
12699 static int
12700 remote_supports_cond_tracepoints ()
12701 {
12702   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12703 }
12704
12705 bool
12706 remote_target::supports_evaluation_of_breakpoint_conditions ()
12707 {
12708   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12709 }
12710
12711 static int
12712 remote_supports_fast_tracepoints ()
12713 {
12714   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12715 }
12716
12717 static int
12718 remote_supports_static_tracepoints ()
12719 {
12720   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12721 }
12722
12723 static int
12724 remote_supports_install_in_trace ()
12725 {
12726   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12727 }
12728
12729 bool
12730 remote_target::supports_enable_disable_tracepoint ()
12731 {
12732   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12733           == PACKET_ENABLE);
12734 }
12735
12736 bool
12737 remote_target::supports_string_tracing ()
12738 {
12739   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12740 }
12741
12742 bool
12743 remote_target::can_run_breakpoint_commands ()
12744 {
12745   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12746 }
12747
12748 void
12749 remote_target::trace_init ()
12750 {
12751   struct remote_state *rs = get_remote_state ();
12752
12753   putpkt ("QTinit");
12754   remote_get_noisy_reply ();
12755   if (strcmp (rs->buf, "OK") != 0)
12756     error (_("Target does not support this command."));
12757 }
12758
12759 /* Recursive routine to walk through command list including loops, and
12760    download packets for each command.  */
12761
12762 void
12763 remote_target::remote_download_command_source (int num, ULONGEST addr,
12764                                                struct command_line *cmds)
12765 {
12766   struct remote_state *rs = get_remote_state ();
12767   struct command_line *cmd;
12768
12769   for (cmd = cmds; cmd; cmd = cmd->next)
12770     {
12771       QUIT;     /* Allow user to bail out with ^C.  */
12772       strcpy (rs->buf, "QTDPsrc:");
12773       encode_source_string (num, addr, "cmd", cmd->line,
12774                             rs->buf + strlen (rs->buf),
12775                             rs->buf_size - strlen (rs->buf));
12776       putpkt (rs->buf);
12777       remote_get_noisy_reply ();
12778       if (strcmp (rs->buf, "OK"))
12779         warning (_("Target does not support source download."));
12780
12781       if (cmd->control_type == while_control
12782           || cmd->control_type == while_stepping_control)
12783         {
12784           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12785
12786           QUIT; /* Allow user to bail out with ^C.  */
12787           strcpy (rs->buf, "QTDPsrc:");
12788           encode_source_string (num, addr, "cmd", "end",
12789                                 rs->buf + strlen (rs->buf),
12790                                 rs->buf_size - strlen (rs->buf));
12791           putpkt (rs->buf);
12792           remote_get_noisy_reply ();
12793           if (strcmp (rs->buf, "OK"))
12794             warning (_("Target does not support source download."));
12795         }
12796     }
12797 }
12798
12799 void
12800 remote_target::download_tracepoint (struct bp_location *loc)
12801 {
12802 #define BUF_SIZE 2048
12803
12804   CORE_ADDR tpaddr;
12805   char addrbuf[40];
12806   char buf[BUF_SIZE];
12807   std::vector<std::string> tdp_actions;
12808   std::vector<std::string> stepping_actions;
12809   char *pkt;
12810   struct breakpoint *b = loc->owner;
12811   struct tracepoint *t = (struct tracepoint *) b;
12812   struct remote_state *rs = get_remote_state ();
12813
12814   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12815
12816   tpaddr = loc->address;
12817   sprintf_vma (addrbuf, tpaddr);
12818   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12819              addrbuf, /* address */
12820              (b->enable_state == bp_enabled ? 'E' : 'D'),
12821              t->step_count, t->pass_count);
12822   /* Fast tracepoints are mostly handled by the target, but we can
12823      tell the target how big of an instruction block should be moved
12824      around.  */
12825   if (b->type == bp_fast_tracepoint)
12826     {
12827       /* Only test for support at download time; we may not know
12828          target capabilities at definition time.  */
12829       if (remote_supports_fast_tracepoints ())
12830         {
12831           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12832                                                 NULL))
12833             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12834                        gdb_insn_length (loc->gdbarch, tpaddr));
12835           else
12836             /* If it passed validation at definition but fails now,
12837                something is very wrong.  */
12838             internal_error (__FILE__, __LINE__,
12839                             _("Fast tracepoint not "
12840                               "valid during download"));
12841         }
12842       else
12843         /* Fast tracepoints are functionally identical to regular
12844            tracepoints, so don't take lack of support as a reason to
12845            give up on the trace run.  */
12846         warning (_("Target does not support fast tracepoints, "
12847                    "downloading %d as regular tracepoint"), b->number);
12848     }
12849   else if (b->type == bp_static_tracepoint)
12850     {
12851       /* Only test for support at download time; we may not know
12852          target capabilities at definition time.  */
12853       if (remote_supports_static_tracepoints ())
12854         {
12855           struct static_tracepoint_marker marker;
12856
12857           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12858             strcat (buf, ":S");
12859           else
12860             error (_("Static tracepoint not valid during download"));
12861         }
12862       else
12863         /* Fast tracepoints are functionally identical to regular
12864            tracepoints, so don't take lack of support as a reason
12865            to give up on the trace run.  */
12866         error (_("Target does not support static tracepoints"));
12867     }
12868   /* If the tracepoint has a conditional, make it into an agent
12869      expression and append to the definition.  */
12870   if (loc->cond)
12871     {
12872       /* Only test support at download time, we may not know target
12873          capabilities at definition time.  */
12874       if (remote_supports_cond_tracepoints ())
12875         {
12876           agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12877           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12878                      aexpr->len);
12879           pkt = buf + strlen (buf);
12880           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12881             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12882           *pkt = '\0';
12883         }
12884       else
12885         warning (_("Target does not support conditional tracepoints, "
12886                    "ignoring tp %d cond"), b->number);
12887     }
12888
12889   if (b->commands || *default_collect)
12890     strcat (buf, "-");
12891   putpkt (buf);
12892   remote_get_noisy_reply ();
12893   if (strcmp (rs->buf, "OK"))
12894     error (_("Target does not support tracepoints."));
12895
12896   /* do_single_steps (t); */
12897   for (auto action_it = tdp_actions.begin ();
12898        action_it != tdp_actions.end (); action_it++)
12899     {
12900       QUIT;     /* Allow user to bail out with ^C.  */
12901
12902       bool has_more = (action_it != tdp_actions.end ()
12903                        || !stepping_actions.empty ());
12904
12905       xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12906                  b->number, addrbuf, /* address */
12907                  action_it->c_str (),
12908                  has_more ? '-' : 0);
12909       putpkt (buf);
12910       remote_get_noisy_reply ();
12911       if (strcmp (rs->buf, "OK"))
12912         error (_("Error on target while setting tracepoints."));
12913     }
12914
12915     for (auto action_it = stepping_actions.begin ();
12916          action_it != stepping_actions.end (); action_it++)
12917       {
12918         QUIT;   /* Allow user to bail out with ^C.  */
12919
12920         bool is_first = action_it == stepping_actions.begin ();
12921         bool has_more = action_it != stepping_actions.end ();
12922
12923         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12924                    b->number, addrbuf, /* address */
12925                    is_first ? "S" : "",
12926                    action_it->c_str (),
12927                    has_more ? "-" : "");
12928         putpkt (buf);
12929         remote_get_noisy_reply ();
12930         if (strcmp (rs->buf, "OK"))
12931           error (_("Error on target while setting tracepoints."));
12932       }
12933
12934   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12935     {
12936       if (b->location != NULL)
12937         {
12938           strcpy (buf, "QTDPsrc:");
12939           encode_source_string (b->number, loc->address, "at",
12940                                 event_location_to_string (b->location.get ()),
12941                                 buf + strlen (buf), 2048 - strlen (buf));
12942           putpkt (buf);
12943           remote_get_noisy_reply ();
12944           if (strcmp (rs->buf, "OK"))
12945             warning (_("Target does not support source download."));
12946         }
12947       if (b->cond_string)
12948         {
12949           strcpy (buf, "QTDPsrc:");
12950           encode_source_string (b->number, loc->address,
12951                                 "cond", b->cond_string, buf + strlen (buf),
12952                                 2048 - strlen (buf));
12953           putpkt (buf);
12954           remote_get_noisy_reply ();
12955           if (strcmp (rs->buf, "OK"))
12956             warning (_("Target does not support source download."));
12957         }
12958       remote_download_command_source (b->number, loc->address,
12959                                       breakpoint_commands (b));
12960     }
12961 }
12962
12963 bool
12964 remote_target::can_download_tracepoint ()
12965 {
12966   struct remote_state *rs = get_remote_state ();
12967   struct trace_status *ts;
12968   int status;
12969
12970   /* Don't try to install tracepoints until we've relocated our
12971      symbols, and fetched and merged the target's tracepoint list with
12972      ours.  */
12973   if (rs->starting_up)
12974     return false;
12975
12976   ts = current_trace_status ();
12977   status = get_trace_status (ts);
12978
12979   if (status == -1 || !ts->running_known || !ts->running)
12980     return false;
12981
12982   /* If we are in a tracing experiment, but remote stub doesn't support
12983      installing tracepoint in trace, we have to return.  */
12984   if (!remote_supports_install_in_trace ())
12985     return false;
12986
12987   return true;
12988 }
12989
12990
12991 void
12992 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12993 {
12994   struct remote_state *rs = get_remote_state ();
12995   char *p;
12996
12997   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12998              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12999              tsv.builtin);
13000   p = rs->buf + strlen (rs->buf);
13001   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
13002     error (_("Trace state variable name too long for tsv definition packet"));
13003   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13004   *p++ = '\0';
13005   putpkt (rs->buf);
13006   remote_get_noisy_reply ();
13007   if (*rs->buf == '\0')
13008     error (_("Target does not support this command."));
13009   if (strcmp (rs->buf, "OK") != 0)
13010     error (_("Error on target while downloading trace state variable."));
13011 }
13012
13013 void
13014 remote_target::enable_tracepoint (struct bp_location *location)
13015 {
13016   struct remote_state *rs = get_remote_state ();
13017   char addr_buf[40];
13018
13019   sprintf_vma (addr_buf, location->address);
13020   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13021              location->owner->number, addr_buf);
13022   putpkt (rs->buf);
13023   remote_get_noisy_reply ();
13024   if (*rs->buf == '\0')
13025     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13026   if (strcmp (rs->buf, "OK") != 0)
13027     error (_("Error on target while enabling tracepoint."));
13028 }
13029
13030 void
13031 remote_target::disable_tracepoint (struct bp_location *location)
13032 {
13033   struct remote_state *rs = get_remote_state ();
13034   char addr_buf[40];
13035
13036   sprintf_vma (addr_buf, location->address);
13037   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13038              location->owner->number, addr_buf);
13039   putpkt (rs->buf);
13040   remote_get_noisy_reply ();
13041   if (*rs->buf == '\0')
13042     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13043   if (strcmp (rs->buf, "OK") != 0)
13044     error (_("Error on target while disabling tracepoint."));
13045 }
13046
13047 void
13048 remote_target::trace_set_readonly_regions ()
13049 {
13050   asection *s;
13051   bfd *abfd = NULL;
13052   bfd_size_type size;
13053   bfd_vma vma;
13054   int anysecs = 0;
13055   int offset = 0;
13056
13057   if (!exec_bfd)
13058     return;                     /* No information to give.  */
13059
13060   struct remote_state *rs = get_remote_state ();
13061
13062   strcpy (rs->buf, "QTro");
13063   offset = strlen (rs->buf);
13064   for (s = exec_bfd->sections; s; s = s->next)
13065     {
13066       char tmp1[40], tmp2[40];
13067       int sec_length;
13068
13069       if ((s->flags & SEC_LOAD) == 0 ||
13070       /*  (s->flags & SEC_CODE) == 0 || */
13071           (s->flags & SEC_READONLY) == 0)
13072         continue;
13073
13074       anysecs = 1;
13075       vma = bfd_get_section_vma (abfd, s);
13076       size = bfd_get_section_size (s);
13077       sprintf_vma (tmp1, vma);
13078       sprintf_vma (tmp2, vma + size);
13079       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13080       if (offset + sec_length + 1 > rs->buf_size)
13081         {
13082           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13083             warning (_("\
13084 Too many sections for read-only sections definition packet."));
13085           break;
13086         }
13087       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13088                  tmp1, tmp2);
13089       offset += sec_length;
13090     }
13091   if (anysecs)
13092     {
13093       putpkt (rs->buf);
13094       getpkt (&rs->buf, &rs->buf_size, 0);
13095     }
13096 }
13097
13098 void
13099 remote_target::trace_start ()
13100 {
13101   struct remote_state *rs = get_remote_state ();
13102
13103   putpkt ("QTStart");
13104   remote_get_noisy_reply ();
13105   if (*rs->buf == '\0')
13106     error (_("Target does not support this command."));
13107   if (strcmp (rs->buf, "OK") != 0)
13108     error (_("Bogus reply from target: %s"), rs->buf);
13109 }
13110
13111 int
13112 remote_target::get_trace_status (struct trace_status *ts)
13113 {
13114   /* Initialize it just to avoid a GCC false warning.  */
13115   char *p = NULL;
13116   /* FIXME we need to get register block size some other way.  */
13117   extern int trace_regblock_size;
13118   enum packet_result result;
13119   struct remote_state *rs = get_remote_state ();
13120
13121   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13122     return -1;
13123
13124   trace_regblock_size
13125     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13126
13127   putpkt ("qTStatus");
13128
13129   TRY
13130     {
13131       p = remote_get_noisy_reply ();
13132     }
13133   CATCH (ex, RETURN_MASK_ERROR)
13134     {
13135       if (ex.error != TARGET_CLOSE_ERROR)
13136         {
13137           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13138           return -1;
13139         }
13140       throw_exception (ex);
13141     }
13142   END_CATCH
13143
13144   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13145
13146   /* If the remote target doesn't do tracing, flag it.  */
13147   if (result == PACKET_UNKNOWN)
13148     return -1;
13149
13150   /* We're working with a live target.  */
13151   ts->filename = NULL;
13152
13153   if (*p++ != 'T')
13154     error (_("Bogus trace status reply from target: %s"), rs->buf);
13155
13156   /* Function 'parse_trace_status' sets default value of each field of
13157      'ts' at first, so we don't have to do it here.  */
13158   parse_trace_status (p, ts);
13159
13160   return ts->running;
13161 }
13162
13163 void
13164 remote_target::get_tracepoint_status (struct breakpoint *bp,
13165                                       struct uploaded_tp *utp)
13166 {
13167   struct remote_state *rs = get_remote_state ();
13168   char *reply;
13169   struct bp_location *loc;
13170   struct tracepoint *tp = (struct tracepoint *) bp;
13171   size_t size = get_remote_packet_size ();
13172
13173   if (tp)
13174     {
13175       tp->hit_count = 0;
13176       tp->traceframe_usage = 0;
13177       for (loc = tp->loc; loc; loc = loc->next)
13178         {
13179           /* If the tracepoint was never downloaded, don't go asking for
13180              any status.  */
13181           if (tp->number_on_target == 0)
13182             continue;
13183           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13184                      phex_nz (loc->address, 0));
13185           putpkt (rs->buf);
13186           reply = remote_get_noisy_reply ();
13187           if (reply && *reply)
13188             {
13189               if (*reply == 'V')
13190                 parse_tracepoint_status (reply + 1, bp, utp);
13191             }
13192         }
13193     }
13194   else if (utp)
13195     {
13196       utp->hit_count = 0;
13197       utp->traceframe_usage = 0;
13198       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13199                  phex_nz (utp->addr, 0));
13200       putpkt (rs->buf);
13201       reply = remote_get_noisy_reply ();
13202       if (reply && *reply)
13203         {
13204           if (*reply == 'V')
13205             parse_tracepoint_status (reply + 1, bp, utp);
13206         }
13207     }
13208 }
13209
13210 void
13211 remote_target::trace_stop ()
13212 {
13213   struct remote_state *rs = get_remote_state ();
13214
13215   putpkt ("QTStop");
13216   remote_get_noisy_reply ();
13217   if (*rs->buf == '\0')
13218     error (_("Target does not support this command."));
13219   if (strcmp (rs->buf, "OK") != 0)
13220     error (_("Bogus reply from target: %s"), rs->buf);
13221 }
13222
13223 int
13224 remote_target::trace_find (enum trace_find_type type, int num,
13225                            CORE_ADDR addr1, CORE_ADDR addr2,
13226                            int *tpp)
13227 {
13228   struct remote_state *rs = get_remote_state ();
13229   char *endbuf = rs->buf + get_remote_packet_size ();
13230   char *p, *reply;
13231   int target_frameno = -1, target_tracept = -1;
13232
13233   /* Lookups other than by absolute frame number depend on the current
13234      trace selected, so make sure it is correct on the remote end
13235      first.  */
13236   if (type != tfind_number)
13237     set_remote_traceframe ();
13238
13239   p = rs->buf;
13240   strcpy (p, "QTFrame:");
13241   p = strchr (p, '\0');
13242   switch (type)
13243     {
13244     case tfind_number:
13245       xsnprintf (p, endbuf - p, "%x", num);
13246       break;
13247     case tfind_pc:
13248       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13249       break;
13250     case tfind_tp:
13251       xsnprintf (p, endbuf - p, "tdp:%x", num);
13252       break;
13253     case tfind_range:
13254       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13255                  phex_nz (addr2, 0));
13256       break;
13257     case tfind_outside:
13258       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13259                  phex_nz (addr2, 0));
13260       break;
13261     default:
13262       error (_("Unknown trace find type %d"), type);
13263     }
13264
13265   putpkt (rs->buf);
13266   reply = remote_get_noisy_reply ();
13267   if (*reply == '\0')
13268     error (_("Target does not support this command."));
13269
13270   while (reply && *reply)
13271     switch (*reply)
13272       {
13273       case 'F':
13274         p = ++reply;
13275         target_frameno = (int) strtol (p, &reply, 16);
13276         if (reply == p)
13277           error (_("Unable to parse trace frame number"));
13278         /* Don't update our remote traceframe number cache on failure
13279            to select a remote traceframe.  */
13280         if (target_frameno == -1)
13281           return -1;
13282         break;
13283       case 'T':
13284         p = ++reply;
13285         target_tracept = (int) strtol (p, &reply, 16);
13286         if (reply == p)
13287           error (_("Unable to parse tracepoint number"));
13288         break;
13289       case 'O':         /* "OK"? */
13290         if (reply[1] == 'K' && reply[2] == '\0')
13291           reply += 2;
13292         else
13293           error (_("Bogus reply from target: %s"), reply);
13294         break;
13295       default:
13296         error (_("Bogus reply from target: %s"), reply);
13297       }
13298   if (tpp)
13299     *tpp = target_tracept;
13300
13301   rs->remote_traceframe_number = target_frameno;
13302   return target_frameno;
13303 }
13304
13305 bool
13306 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13307 {
13308   struct remote_state *rs = get_remote_state ();
13309   char *reply;
13310   ULONGEST uval;
13311
13312   set_remote_traceframe ();
13313
13314   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13315   putpkt (rs->buf);
13316   reply = remote_get_noisy_reply ();
13317   if (reply && *reply)
13318     {
13319       if (*reply == 'V')
13320         {
13321           unpack_varlen_hex (reply + 1, &uval);
13322           *val = (LONGEST) uval;
13323           return true;
13324         }
13325     }
13326   return false;
13327 }
13328
13329 int
13330 remote_target::save_trace_data (const char *filename)
13331 {
13332   struct remote_state *rs = get_remote_state ();
13333   char *p, *reply;
13334
13335   p = rs->buf;
13336   strcpy (p, "QTSave:");
13337   p += strlen (p);
13338   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13339     error (_("Remote file name too long for trace save packet"));
13340   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13341   *p++ = '\0';
13342   putpkt (rs->buf);
13343   reply = remote_get_noisy_reply ();
13344   if (*reply == '\0')
13345     error (_("Target does not support this command."));
13346   if (strcmp (reply, "OK") != 0)
13347     error (_("Bogus reply from target: %s"), reply);
13348   return 0;
13349 }
13350
13351 /* This is basically a memory transfer, but needs to be its own packet
13352    because we don't know how the target actually organizes its trace
13353    memory, plus we want to be able to ask for as much as possible, but
13354    not be unhappy if we don't get as much as we ask for.  */
13355
13356 LONGEST
13357 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13358 {
13359   struct remote_state *rs = get_remote_state ();
13360   char *reply;
13361   char *p;
13362   int rslt;
13363
13364   p = rs->buf;
13365   strcpy (p, "qTBuffer:");
13366   p += strlen (p);
13367   p += hexnumstr (p, offset);
13368   *p++ = ',';
13369   p += hexnumstr (p, len);
13370   *p++ = '\0';
13371
13372   putpkt (rs->buf);
13373   reply = remote_get_noisy_reply ();
13374   if (reply && *reply)
13375     {
13376       /* 'l' by itself means we're at the end of the buffer and
13377          there is nothing more to get.  */
13378       if (*reply == 'l')
13379         return 0;
13380
13381       /* Convert the reply into binary.  Limit the number of bytes to
13382          convert according to our passed-in buffer size, rather than
13383          what was returned in the packet; if the target is
13384          unexpectedly generous and gives us a bigger reply than we
13385          asked for, we don't want to crash.  */
13386       rslt = hex2bin (reply, buf, len);
13387       return rslt;
13388     }
13389
13390   /* Something went wrong, flag as an error.  */
13391   return -1;
13392 }
13393
13394 void
13395 remote_target::set_disconnected_tracing (int val)
13396 {
13397   struct remote_state *rs = get_remote_state ();
13398
13399   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13400     {
13401       char *reply;
13402
13403       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13404       putpkt (rs->buf);
13405       reply = remote_get_noisy_reply ();
13406       if (*reply == '\0')
13407         error (_("Target does not support this command."));
13408       if (strcmp (reply, "OK") != 0)
13409         error (_("Bogus reply from target: %s"), reply);
13410     }
13411   else if (val)
13412     warning (_("Target does not support disconnected tracing."));
13413 }
13414
13415 int
13416 remote_target::core_of_thread (ptid_t ptid)
13417 {
13418   struct thread_info *info = find_thread_ptid (ptid);
13419
13420   if (info != NULL && info->priv != NULL)
13421     return get_remote_thread_info (info)->core;
13422
13423   return -1;
13424 }
13425
13426 void
13427 remote_target::set_circular_trace_buffer (int val)
13428 {
13429   struct remote_state *rs = get_remote_state ();
13430   char *reply;
13431
13432   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13433   putpkt (rs->buf);
13434   reply = remote_get_noisy_reply ();
13435   if (*reply == '\0')
13436     error (_("Target does not support this command."));
13437   if (strcmp (reply, "OK") != 0)
13438     error (_("Bogus reply from target: %s"), reply);
13439 }
13440
13441 traceframe_info_up
13442 remote_target::traceframe_info ()
13443 {
13444   gdb::optional<gdb::char_vector> text
13445     = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13446                             NULL);
13447   if (text)
13448     return parse_traceframe_info (text->data ());
13449
13450   return NULL;
13451 }
13452
13453 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13454    instruction on which a fast tracepoint may be placed.  Returns -1
13455    if the packet is not supported, and 0 if the minimum instruction
13456    length is unknown.  */
13457
13458 int
13459 remote_target::get_min_fast_tracepoint_insn_len ()
13460 {
13461   struct remote_state *rs = get_remote_state ();
13462   char *reply;
13463
13464   /* If we're not debugging a process yet, the IPA can't be
13465      loaded.  */
13466   if (!target_has_execution)
13467     return 0;
13468
13469   /* Make sure the remote is pointing at the right process.  */
13470   set_general_process ();
13471
13472   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13473   putpkt (rs->buf);
13474   reply = remote_get_noisy_reply ();
13475   if (*reply == '\0')
13476     return -1;
13477   else
13478     {
13479       ULONGEST min_insn_len;
13480
13481       unpack_varlen_hex (reply, &min_insn_len);
13482
13483       return (int) min_insn_len;
13484     }
13485 }
13486
13487 void
13488 remote_target::set_trace_buffer_size (LONGEST val)
13489 {
13490   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13491     {
13492       struct remote_state *rs = get_remote_state ();
13493       char *buf = rs->buf;
13494       char *endbuf = rs->buf + get_remote_packet_size ();
13495       enum packet_result result;
13496
13497       gdb_assert (val >= 0 || val == -1);
13498       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13499       /* Send -1 as literal "-1" to avoid host size dependency.  */
13500       if (val < 0)
13501         {
13502           *buf++ = '-';
13503           buf += hexnumstr (buf, (ULONGEST) -val);
13504         }
13505       else
13506         buf += hexnumstr (buf, (ULONGEST) val);
13507
13508       putpkt (rs->buf);
13509       remote_get_noisy_reply ();
13510       result = packet_ok (rs->buf,
13511                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13512
13513       if (result != PACKET_OK)
13514         warning (_("Bogus reply from target: %s"), rs->buf);
13515     }
13516 }
13517
13518 bool
13519 remote_target::set_trace_notes (const char *user, const char *notes,
13520                                 const char *stop_notes)
13521 {
13522   struct remote_state *rs = get_remote_state ();
13523   char *reply;
13524   char *buf = rs->buf;
13525   char *endbuf = rs->buf + get_remote_packet_size ();
13526   int nbytes;
13527
13528   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13529   if (user)
13530     {
13531       buf += xsnprintf (buf, endbuf - buf, "user:");
13532       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13533       buf += 2 * nbytes;
13534       *buf++ = ';';
13535     }
13536   if (notes)
13537     {
13538       buf += xsnprintf (buf, endbuf - buf, "notes:");
13539       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13540       buf += 2 * nbytes;
13541       *buf++ = ';';
13542     }
13543   if (stop_notes)
13544     {
13545       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13546       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13547       buf += 2 * nbytes;
13548       *buf++ = ';';
13549     }
13550   /* Ensure the buffer is terminated.  */
13551   *buf = '\0';
13552
13553   putpkt (rs->buf);
13554   reply = remote_get_noisy_reply ();
13555   if (*reply == '\0')
13556     return false;
13557
13558   if (strcmp (reply, "OK") != 0)
13559     error (_("Bogus reply from target: %s"), reply);
13560
13561   return true;
13562 }
13563
13564 bool
13565 remote_target::use_agent (bool use)
13566 {
13567   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13568     {
13569       struct remote_state *rs = get_remote_state ();
13570
13571       /* If the stub supports QAgent.  */
13572       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13573       putpkt (rs->buf);
13574       getpkt (&rs->buf, &rs->buf_size, 0);
13575
13576       if (strcmp (rs->buf, "OK") == 0)
13577         {
13578           ::use_agent = use;
13579           return true;
13580         }
13581     }
13582
13583   return false;
13584 }
13585
13586 bool
13587 remote_target::can_use_agent ()
13588 {
13589   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13590 }
13591
13592 struct btrace_target_info
13593 {
13594   /* The ptid of the traced thread.  */
13595   ptid_t ptid;
13596
13597   /* The obtained branch trace configuration.  */
13598   struct btrace_config conf;
13599 };
13600
13601 /* Reset our idea of our target's btrace configuration.  */
13602
13603 static void
13604 remote_btrace_reset (remote_state *rs)
13605 {
13606   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13607 }
13608
13609 /* Synchronize the configuration with the target.  */
13610
13611 void
13612 remote_target::btrace_sync_conf (const btrace_config *conf)
13613 {
13614   struct packet_config *packet;
13615   struct remote_state *rs;
13616   char *buf, *pos, *endbuf;
13617
13618   rs = get_remote_state ();
13619   buf = rs->buf;
13620   endbuf = buf + get_remote_packet_size ();
13621
13622   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13623   if (packet_config_support (packet) == PACKET_ENABLE
13624       && conf->bts.size != rs->btrace_config.bts.size)
13625     {
13626       pos = buf;
13627       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13628                         conf->bts.size);
13629
13630       putpkt (buf);
13631       getpkt (&buf, &rs->buf_size, 0);
13632
13633       if (packet_ok (buf, packet) == PACKET_ERROR)
13634         {
13635           if (buf[0] == 'E' && buf[1] == '.')
13636             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13637           else
13638             error (_("Failed to configure the BTS buffer size."));
13639         }
13640
13641       rs->btrace_config.bts.size = conf->bts.size;
13642     }
13643
13644   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13645   if (packet_config_support (packet) == PACKET_ENABLE
13646       && conf->pt.size != rs->btrace_config.pt.size)
13647     {
13648       pos = buf;
13649       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13650                         conf->pt.size);
13651
13652       putpkt (buf);
13653       getpkt (&buf, &rs->buf_size, 0);
13654
13655       if (packet_ok (buf, packet) == PACKET_ERROR)
13656         {
13657           if (buf[0] == 'E' && buf[1] == '.')
13658             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13659           else
13660             error (_("Failed to configure the trace buffer size."));
13661         }
13662
13663       rs->btrace_config.pt.size = conf->pt.size;
13664     }
13665 }
13666
13667 /* Read the current thread's btrace configuration from the target and
13668    store it into CONF.  */
13669
13670 static void
13671 btrace_read_config (struct btrace_config *conf)
13672 {
13673   gdb::optional<gdb::char_vector> xml
13674     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13675   if (xml)
13676     parse_xml_btrace_conf (conf, xml->data ());
13677 }
13678
13679 /* Maybe reopen target btrace.  */
13680
13681 void
13682 remote_target::remote_btrace_maybe_reopen ()
13683 {
13684   struct remote_state *rs = get_remote_state ();
13685   struct thread_info *tp;
13686   int btrace_target_pushed = 0;
13687   int warned = 0;
13688
13689   scoped_restore_current_thread restore_thread;
13690
13691   ALL_NON_EXITED_THREADS (tp)
13692     {
13693       set_general_thread (tp->ptid);
13694
13695       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13696       btrace_read_config (&rs->btrace_config);
13697
13698       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13699         continue;
13700
13701 #if !defined (HAVE_LIBIPT)
13702       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13703         {
13704           if (!warned)
13705             {
13706               warned = 1;
13707               warning (_("Target is recording using Intel Processor Trace "
13708                          "but support was disabled at compile time."));
13709             }
13710
13711           continue;
13712         }
13713 #endif /* !defined (HAVE_LIBIPT) */
13714
13715       /* Push target, once, but before anything else happens.  This way our
13716          changes to the threads will be cleaned up by unpushing the target
13717          in case btrace_read_config () throws.  */
13718       if (!btrace_target_pushed)
13719         {
13720           btrace_target_pushed = 1;
13721           record_btrace_push_target ();
13722           printf_filtered (_("Target is recording using %s.\n"),
13723                            btrace_format_string (rs->btrace_config.format));
13724         }
13725
13726       tp->btrace.target = XCNEW (struct btrace_target_info);
13727       tp->btrace.target->ptid = tp->ptid;
13728       tp->btrace.target->conf = rs->btrace_config;
13729     }
13730 }
13731
13732 /* Enable branch tracing.  */
13733
13734 struct btrace_target_info *
13735 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13736 {
13737   struct btrace_target_info *tinfo = NULL;
13738   struct packet_config *packet = NULL;
13739   struct remote_state *rs = get_remote_state ();
13740   char *buf = rs->buf;
13741   char *endbuf = rs->buf + get_remote_packet_size ();
13742
13743   switch (conf->format)
13744     {
13745       case BTRACE_FORMAT_BTS:
13746         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13747         break;
13748
13749       case BTRACE_FORMAT_PT:
13750         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13751         break;
13752     }
13753
13754   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13755     error (_("Target does not support branch tracing."));
13756
13757   btrace_sync_conf (conf);
13758
13759   set_general_thread (ptid);
13760
13761   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13762   putpkt (rs->buf);
13763   getpkt (&rs->buf, &rs->buf_size, 0);
13764
13765   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13766     {
13767       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13768         error (_("Could not enable branch tracing for %s: %s"),
13769                target_pid_to_str (ptid), rs->buf + 2);
13770       else
13771         error (_("Could not enable branch tracing for %s."),
13772                target_pid_to_str (ptid));
13773     }
13774
13775   tinfo = XCNEW (struct btrace_target_info);
13776   tinfo->ptid = ptid;
13777
13778   /* If we fail to read the configuration, we lose some information, but the
13779      tracing itself is not impacted.  */
13780   TRY
13781     {
13782       btrace_read_config (&tinfo->conf);
13783     }
13784   CATCH (err, RETURN_MASK_ERROR)
13785     {
13786       if (err.message != NULL)
13787         warning ("%s", err.message);
13788     }
13789   END_CATCH
13790
13791   return tinfo;
13792 }
13793
13794 /* Disable branch tracing.  */
13795
13796 void
13797 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13798 {
13799   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13800   struct remote_state *rs = get_remote_state ();
13801   char *buf = rs->buf;
13802   char *endbuf = rs->buf + get_remote_packet_size ();
13803
13804   if (packet_config_support (packet) != PACKET_ENABLE)
13805     error (_("Target does not support branch tracing."));
13806
13807   set_general_thread (tinfo->ptid);
13808
13809   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13810   putpkt (rs->buf);
13811   getpkt (&rs->buf, &rs->buf_size, 0);
13812
13813   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13814     {
13815       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13816         error (_("Could not disable branch tracing for %s: %s"),
13817                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13818       else
13819         error (_("Could not disable branch tracing for %s."),
13820                target_pid_to_str (tinfo->ptid));
13821     }
13822
13823   xfree (tinfo);
13824 }
13825
13826 /* Teardown branch tracing.  */
13827
13828 void
13829 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13830 {
13831   /* We must not talk to the target during teardown.  */
13832   xfree (tinfo);
13833 }
13834
13835 /* Read the branch trace.  */
13836
13837 enum btrace_error
13838 remote_target::read_btrace (struct btrace_data *btrace,
13839                             struct btrace_target_info *tinfo,
13840                             enum btrace_read_type type)
13841 {
13842   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13843   const char *annex;
13844
13845   if (packet_config_support (packet) != PACKET_ENABLE)
13846     error (_("Target does not support branch tracing."));
13847
13848 #if !defined(HAVE_LIBEXPAT)
13849   error (_("Cannot process branch tracing result. XML parsing not supported."));
13850 #endif
13851
13852   switch (type)
13853     {
13854     case BTRACE_READ_ALL:
13855       annex = "all";
13856       break;
13857     case BTRACE_READ_NEW:
13858       annex = "new";
13859       break;
13860     case BTRACE_READ_DELTA:
13861       annex = "delta";
13862       break;
13863     default:
13864       internal_error (__FILE__, __LINE__,
13865                       _("Bad branch tracing read type: %u."),
13866                       (unsigned int) type);
13867     }
13868
13869   gdb::optional<gdb::char_vector> xml
13870     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13871   if (!xml)
13872     return BTRACE_ERR_UNKNOWN;
13873
13874   parse_xml_btrace (btrace, xml->data ());
13875
13876   return BTRACE_ERR_NONE;
13877 }
13878
13879 const struct btrace_config *
13880 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13881 {
13882   return &tinfo->conf;
13883 }
13884
13885 bool
13886 remote_target::augmented_libraries_svr4_read ()
13887 {
13888   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13889           == PACKET_ENABLE);
13890 }
13891
13892 /* Implementation of to_load.  */
13893
13894 void
13895 remote_target::load (const char *name, int from_tty)
13896 {
13897   generic_load (name, from_tty);
13898 }
13899
13900 /* Accepts an integer PID; returns a string representing a file that
13901    can be opened on the remote side to get the symbols for the child
13902    process.  Returns NULL if the operation is not supported.  */
13903
13904 char *
13905 remote_target::pid_to_exec_file (int pid)
13906 {
13907   static gdb::optional<gdb::char_vector> filename;
13908   struct inferior *inf;
13909   char *annex = NULL;
13910
13911   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13912     return NULL;
13913
13914   inf = find_inferior_pid (pid);
13915   if (inf == NULL)
13916     internal_error (__FILE__, __LINE__,
13917                     _("not currently attached to process %d"), pid);
13918
13919   if (!inf->fake_pid_p)
13920     {
13921       const int annex_size = 9;
13922
13923       annex = (char *) alloca (annex_size);
13924       xsnprintf (annex, annex_size, "%x", pid);
13925     }
13926
13927   filename = target_read_stralloc (current_top_target (),
13928                                    TARGET_OBJECT_EXEC_FILE, annex);
13929
13930   return filename ? filename->data () : nullptr;
13931 }
13932
13933 /* Implement the to_can_do_single_step target_ops method.  */
13934
13935 int
13936 remote_target::can_do_single_step ()
13937 {
13938   /* We can only tell whether target supports single step or not by
13939      supported s and S vCont actions if the stub supports vContSupported
13940      feature.  If the stub doesn't support vContSupported feature,
13941      we have conservatively to think target doesn't supports single
13942      step.  */
13943   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13944     {
13945       struct remote_state *rs = get_remote_state ();
13946
13947       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13948         remote_vcont_probe ();
13949
13950       return rs->supports_vCont.s && rs->supports_vCont.S;
13951     }
13952   else
13953     return 0;
13954 }
13955
13956 /* Implementation of the to_execution_direction method for the remote
13957    target.  */
13958
13959 enum exec_direction_kind
13960 remote_target::execution_direction ()
13961 {
13962   struct remote_state *rs = get_remote_state ();
13963
13964   return rs->last_resume_exec_dir;
13965 }
13966
13967 /* Return pointer to the thread_info struct which corresponds to
13968    THREAD_HANDLE (having length HANDLE_LEN).  */
13969
13970 thread_info *
13971 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13972                                              int handle_len,
13973                                              inferior *inf)
13974 {
13975   struct thread_info *tp;
13976
13977   ALL_NON_EXITED_THREADS (tp)
13978     {
13979       remote_thread_info *priv = get_remote_thread_info (tp);
13980
13981       if (tp->inf == inf && priv != NULL)
13982         {
13983           if (handle_len != priv->thread_handle.size ())
13984             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13985                    handle_len, priv->thread_handle.size ());
13986           if (memcmp (thread_handle, priv->thread_handle.data (),
13987                       handle_len) == 0)
13988             return tp;
13989         }
13990     }
13991
13992   return NULL;
13993 }
13994
13995 bool
13996 remote_target::can_async_p ()
13997 {
13998   struct remote_state *rs = get_remote_state ();
13999
14000   /* We don't go async if the user has explicitly prevented it with the
14001      "maint set target-async" command.  */
14002   if (!target_async_permitted)
14003     return false;
14004
14005   /* We're async whenever the serial device is.  */
14006   return serial_can_async_p (rs->remote_desc);
14007 }
14008
14009 bool
14010 remote_target::is_async_p ()
14011 {
14012   struct remote_state *rs = get_remote_state ();
14013
14014   if (!target_async_permitted)
14015     /* We only enable async when the user specifically asks for it.  */
14016     return false;
14017
14018   /* We're async whenever the serial device is.  */
14019   return serial_is_async_p (rs->remote_desc);
14020 }
14021
14022 /* Pass the SERIAL event on and up to the client.  One day this code
14023    will be able to delay notifying the client of an event until the
14024    point where an entire packet has been received.  */
14025
14026 static serial_event_ftype remote_async_serial_handler;
14027
14028 static void
14029 remote_async_serial_handler (struct serial *scb, void *context)
14030 {
14031   /* Don't propogate error information up to the client.  Instead let
14032      the client find out about the error by querying the target.  */
14033   inferior_event_handler (INF_REG_EVENT, NULL);
14034 }
14035
14036 static void
14037 remote_async_inferior_event_handler (gdb_client_data data)
14038 {
14039   inferior_event_handler (INF_REG_EVENT, data);
14040 }
14041
14042 void
14043 remote_target::async (int enable)
14044 {
14045   struct remote_state *rs = get_remote_state ();
14046
14047   if (enable)
14048     {
14049       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14050
14051       /* If there are pending events in the stop reply queue tell the
14052          event loop to process them.  */
14053       if (!rs->stop_reply_queue.empty ())
14054         mark_async_event_handler (rs->remote_async_inferior_event_token);
14055       /* For simplicity, below we clear the pending events token
14056          without remembering whether it is marked, so here we always
14057          mark it.  If there's actually no pending notification to
14058          process, this ends up being a no-op (other than a spurious
14059          event-loop wakeup).  */
14060       if (target_is_non_stop_p ())
14061         mark_async_event_handler (rs->notif_state->get_pending_events_token);
14062     }
14063   else
14064     {
14065       serial_async (rs->remote_desc, NULL, NULL);
14066       /* If the core is disabling async, it doesn't want to be
14067          disturbed with target events.  Clear all async event sources
14068          too.  */
14069       clear_async_event_handler (rs->remote_async_inferior_event_token);
14070       if (target_is_non_stop_p ())
14071         clear_async_event_handler (rs->notif_state->get_pending_events_token);
14072     }
14073 }
14074
14075 /* Implementation of the to_thread_events method.  */
14076
14077 void
14078 remote_target::thread_events (int enable)
14079 {
14080   struct remote_state *rs = get_remote_state ();
14081   size_t size = get_remote_packet_size ();
14082
14083   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14084     return;
14085
14086   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14087   putpkt (rs->buf);
14088   getpkt (&rs->buf, &rs->buf_size, 0);
14089
14090   switch (packet_ok (rs->buf,
14091                      &remote_protocol_packets[PACKET_QThreadEvents]))
14092     {
14093     case PACKET_OK:
14094       if (strcmp (rs->buf, "OK") != 0)
14095         error (_("Remote refused setting thread events: %s"), rs->buf);
14096       break;
14097     case PACKET_ERROR:
14098       warning (_("Remote failure reply: %s"), rs->buf);
14099       break;
14100     case PACKET_UNKNOWN:
14101       break;
14102     }
14103 }
14104
14105 static void
14106 set_remote_cmd (const char *args, int from_tty)
14107 {
14108   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14109 }
14110
14111 static void
14112 show_remote_cmd (const char *args, int from_tty)
14113 {
14114   /* We can't just use cmd_show_list here, because we want to skip
14115      the redundant "show remote Z-packet" and the legacy aliases.  */
14116   struct cmd_list_element *list = remote_show_cmdlist;
14117   struct ui_out *uiout = current_uiout;
14118
14119   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14120   for (; list != NULL; list = list->next)
14121     if (strcmp (list->name, "Z-packet") == 0)
14122       continue;
14123     else if (list->type == not_set_cmd)
14124       /* Alias commands are exactly like the original, except they
14125          don't have the normal type.  */
14126       continue;
14127     else
14128       {
14129         ui_out_emit_tuple option_emitter (uiout, "option");
14130
14131         uiout->field_string ("name", list->name);
14132         uiout->text (":  ");
14133         if (list->type == show_cmd)
14134           do_show_command (NULL, from_tty, list);
14135         else
14136           cmd_func (list, NULL, from_tty);
14137       }
14138 }
14139
14140
14141 /* Function to be called whenever a new objfile (shlib) is detected.  */
14142 static void
14143 remote_new_objfile (struct objfile *objfile)
14144 {
14145   remote_target *remote = get_current_remote_target ();
14146
14147   if (remote != NULL)                   /* Have a remote connection.  */
14148     remote->remote_check_symbols ();
14149 }
14150
14151 /* Pull all the tracepoints defined on the target and create local
14152    data structures representing them.  We don't want to create real
14153    tracepoints yet, we don't want to mess up the user's existing
14154    collection.  */
14155   
14156 int
14157 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14158 {
14159   struct remote_state *rs = get_remote_state ();
14160   char *p;
14161
14162   /* Ask for a first packet of tracepoint definition.  */
14163   putpkt ("qTfP");
14164   getpkt (&rs->buf, &rs->buf_size, 0);
14165   p = rs->buf;
14166   while (*p && *p != 'l')
14167     {
14168       parse_tracepoint_definition (p, utpp);
14169       /* Ask for another packet of tracepoint definition.  */
14170       putpkt ("qTsP");
14171       getpkt (&rs->buf, &rs->buf_size, 0);
14172       p = rs->buf;
14173     }
14174   return 0;
14175 }
14176
14177 int
14178 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14179 {
14180   struct remote_state *rs = get_remote_state ();
14181   char *p;
14182
14183   /* Ask for a first packet of variable definition.  */
14184   putpkt ("qTfV");
14185   getpkt (&rs->buf, &rs->buf_size, 0);
14186   p = rs->buf;
14187   while (*p && *p != 'l')
14188     {
14189       parse_tsv_definition (p, utsvp);
14190       /* Ask for another packet of variable definition.  */
14191       putpkt ("qTsV");
14192       getpkt (&rs->buf, &rs->buf_size, 0);
14193       p = rs->buf;
14194     }
14195   return 0;
14196 }
14197
14198 /* The "set/show range-stepping" show hook.  */
14199
14200 static void
14201 show_range_stepping (struct ui_file *file, int from_tty,
14202                      struct cmd_list_element *c,
14203                      const char *value)
14204 {
14205   fprintf_filtered (file,
14206                     _("Debugger's willingness to use range stepping "
14207                       "is %s.\n"), value);
14208 }
14209
14210 /* Return true if the vCont;r action is supported by the remote
14211    stub.  */
14212
14213 bool
14214 remote_target::vcont_r_supported ()
14215 {
14216   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14217     remote_vcont_probe ();
14218
14219   return (packet_support (PACKET_vCont) == PACKET_ENABLE
14220           && get_remote_state ()->supports_vCont.r);
14221 }
14222
14223 /* The "set/show range-stepping" set hook.  */
14224
14225 static void
14226 set_range_stepping (const char *ignore_args, int from_tty,
14227                     struct cmd_list_element *c)
14228 {
14229   /* When enabling, check whether range stepping is actually supported
14230      by the target, and warn if not.  */
14231   if (use_range_stepping)
14232     {
14233       remote_target *remote = get_current_remote_target ();
14234       if (remote == NULL
14235           || !remote->vcont_r_supported ())
14236         warning (_("Range stepping is not supported by the current target"));
14237     }
14238 }
14239
14240 void
14241 _initialize_remote (void)
14242 {
14243   struct cmd_list_element *cmd;
14244   const char *cmd_name;
14245
14246   /* architecture specific data */
14247   remote_g_packet_data_handle =
14248     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14249
14250   remote_pspace_data
14251     = register_program_space_data_with_cleanup (NULL,
14252                                                 remote_pspace_data_cleanup);
14253
14254   add_target (remote_target_info, remote_target::open);
14255   add_target (extended_remote_target_info, extended_remote_target::open);
14256
14257   /* Hook into new objfile notification.  */
14258   gdb::observers::new_objfile.attach (remote_new_objfile);
14259
14260 #if 0
14261   init_remote_threadtests ();
14262 #endif
14263
14264   /* set/show remote ...  */
14265
14266   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14267 Remote protocol specific variables\n\
14268 Configure various remote-protocol specific variables such as\n\
14269 the packets being used"),
14270                   &remote_set_cmdlist, "set remote ",
14271                   0 /* allow-unknown */, &setlist);
14272   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14273 Remote protocol specific variables\n\
14274 Configure various remote-protocol specific variables such as\n\
14275 the packets being used"),
14276                   &remote_show_cmdlist, "show remote ",
14277                   0 /* allow-unknown */, &showlist);
14278
14279   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14280 Compare section data on target to the exec file.\n\
14281 Argument is a single section name (default: all loaded sections).\n\
14282 To compare only read-only loaded sections, specify the -r option."),
14283            &cmdlist);
14284
14285   add_cmd ("packet", class_maintenance, packet_command, _("\
14286 Send an arbitrary packet to a remote target.\n\
14287    maintenance packet TEXT\n\
14288 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14289 this command sends the string TEXT to the inferior, and displays the\n\
14290 response packet.  GDB supplies the initial `$' character, and the\n\
14291 terminating `#' character and checksum."),
14292            &maintenancelist);
14293
14294   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14295 Set whether to send break if interrupted."), _("\
14296 Show whether to send break if interrupted."), _("\
14297 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14298                            set_remotebreak, show_remotebreak,
14299                            &setlist, &showlist);
14300   cmd_name = "remotebreak";
14301   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14302   deprecate_cmd (cmd, "set remote interrupt-sequence");
14303   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14304   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14305   deprecate_cmd (cmd, "show remote interrupt-sequence");
14306
14307   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14308                         interrupt_sequence_modes, &interrupt_sequence_mode,
14309                         _("\
14310 Set interrupt sequence to remote target."), _("\
14311 Show interrupt sequence to remote target."), _("\
14312 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14313                         NULL, show_interrupt_sequence,
14314                         &remote_set_cmdlist,
14315                         &remote_show_cmdlist);
14316
14317   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14318                            &interrupt_on_connect, _("\
14319 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14320 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14321 If set, interrupt sequence is sent to remote target."),
14322                            NULL, NULL,
14323                            &remote_set_cmdlist, &remote_show_cmdlist);
14324
14325   /* Install commands for configuring memory read/write packets.  */
14326
14327   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14328 Set the maximum number of bytes per memory write packet (deprecated)."),
14329            &setlist);
14330   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14331 Show the maximum number of bytes per memory write packet (deprecated)."),
14332            &showlist);
14333   add_cmd ("memory-write-packet-size", no_class,
14334            set_memory_write_packet_size, _("\
14335 Set the maximum number of bytes per memory-write packet.\n\
14336 Specify the number of bytes in a packet or 0 (zero) for the\n\
14337 default packet size.  The actual limit is further reduced\n\
14338 dependent on the target.  Specify ``fixed'' to disable the\n\
14339 further restriction and ``limit'' to enable that restriction."),
14340            &remote_set_cmdlist);
14341   add_cmd ("memory-read-packet-size", no_class,
14342            set_memory_read_packet_size, _("\
14343 Set the maximum number of bytes per memory-read packet.\n\
14344 Specify the number of bytes in a packet or 0 (zero) for the\n\
14345 default packet size.  The actual limit is further reduced\n\
14346 dependent on the target.  Specify ``fixed'' to disable the\n\
14347 further restriction and ``limit'' to enable that restriction."),
14348            &remote_set_cmdlist);
14349   add_cmd ("memory-write-packet-size", no_class,
14350            show_memory_write_packet_size,
14351            _("Show the maximum number of bytes per memory-write packet."),
14352            &remote_show_cmdlist);
14353   add_cmd ("memory-read-packet-size", no_class,
14354            show_memory_read_packet_size,
14355            _("Show the maximum number of bytes per memory-read packet."),
14356            &remote_show_cmdlist);
14357
14358   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14359                             &remote_hw_watchpoint_limit, _("\
14360 Set the maximum number of target hardware watchpoints."), _("\
14361 Show the maximum number of target hardware watchpoints."), _("\
14362 Specify a negative limit for unlimited."),
14363                             NULL, NULL, /* FIXME: i18n: The maximum
14364                                            number of target hardware
14365                                            watchpoints is %s.  */
14366                             &remote_set_cmdlist, &remote_show_cmdlist);
14367   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14368                             &remote_hw_watchpoint_length_limit, _("\
14369 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14370 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14371 Specify a negative limit for unlimited."),
14372                             NULL, NULL, /* FIXME: i18n: The maximum
14373                                            length (in bytes) of a target
14374                                            hardware watchpoint is %s.  */
14375                             &remote_set_cmdlist, &remote_show_cmdlist);
14376   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14377                             &remote_hw_breakpoint_limit, _("\
14378 Set the maximum number of target hardware breakpoints."), _("\
14379 Show the maximum number of target hardware breakpoints."), _("\
14380 Specify a negative limit for unlimited."),
14381                             NULL, NULL, /* FIXME: i18n: The maximum
14382                                            number of target hardware
14383                                            breakpoints is %s.  */
14384                             &remote_set_cmdlist, &remote_show_cmdlist);
14385
14386   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14387                              &remote_address_size, _("\
14388 Set the maximum size of the address (in bits) in a memory packet."), _("\
14389 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14390                              NULL,
14391                              NULL, /* FIXME: i18n: */
14392                              &setlist, &showlist);
14393
14394   init_all_packet_configs ();
14395
14396   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14397                          "X", "binary-download", 1);
14398
14399   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14400                          "vCont", "verbose-resume", 0);
14401
14402   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14403                          "QPassSignals", "pass-signals", 0);
14404
14405   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14406                          "QCatchSyscalls", "catch-syscalls", 0);
14407
14408   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14409                          "QProgramSignals", "program-signals", 0);
14410
14411   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14412                          "QSetWorkingDir", "set-working-dir", 0);
14413
14414   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14415                          "QStartupWithShell", "startup-with-shell", 0);
14416
14417   add_packet_config_cmd (&remote_protocol_packets
14418                          [PACKET_QEnvironmentHexEncoded],
14419                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14420                          0);
14421
14422   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14423                          "QEnvironmentReset", "environment-reset",
14424                          0);
14425
14426   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14427                          "QEnvironmentUnset", "environment-unset",
14428                          0);
14429
14430   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14431                          "qSymbol", "symbol-lookup", 0);
14432
14433   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14434                          "P", "set-register", 1);
14435
14436   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14437                          "p", "fetch-register", 1);
14438
14439   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14440                          "Z0", "software-breakpoint", 0);
14441
14442   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14443                          "Z1", "hardware-breakpoint", 0);
14444
14445   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14446                          "Z2", "write-watchpoint", 0);
14447
14448   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14449                          "Z3", "read-watchpoint", 0);
14450
14451   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14452                          "Z4", "access-watchpoint", 0);
14453
14454   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14455                          "qXfer:auxv:read", "read-aux-vector", 0);
14456
14457   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14458                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14459
14460   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14461                          "qXfer:features:read", "target-features", 0);
14462
14463   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14464                          "qXfer:libraries:read", "library-info", 0);
14465
14466   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14467                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14468
14469   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14470                          "qXfer:memory-map:read", "memory-map", 0);
14471
14472   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14473                          "qXfer:spu:read", "read-spu-object", 0);
14474
14475   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14476                          "qXfer:spu:write", "write-spu-object", 0);
14477
14478   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14479                         "qXfer:osdata:read", "osdata", 0);
14480
14481   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14482                          "qXfer:threads:read", "threads", 0);
14483
14484   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14485                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14486
14487   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14488                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14489
14490   add_packet_config_cmd
14491     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14492      "qXfer:traceframe-info:read", "traceframe-info", 0);
14493
14494   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14495                          "qXfer:uib:read", "unwind-info-block", 0);
14496
14497   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14498                          "qGetTLSAddr", "get-thread-local-storage-address",
14499                          0);
14500
14501   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14502                          "qGetTIBAddr", "get-thread-information-block-address",
14503                          0);
14504
14505   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14506                          "bc", "reverse-continue", 0);
14507
14508   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14509                          "bs", "reverse-step", 0);
14510
14511   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14512                          "qSupported", "supported-packets", 0);
14513
14514   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14515                          "qSearch:memory", "search-memory", 0);
14516
14517   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14518                          "qTStatus", "trace-status", 0);
14519
14520   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14521                          "vFile:setfs", "hostio-setfs", 0);
14522
14523   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14524                          "vFile:open", "hostio-open", 0);
14525
14526   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14527                          "vFile:pread", "hostio-pread", 0);
14528
14529   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14530                          "vFile:pwrite", "hostio-pwrite", 0);
14531
14532   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14533                          "vFile:close", "hostio-close", 0);
14534
14535   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14536                          "vFile:unlink", "hostio-unlink", 0);
14537
14538   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14539                          "vFile:readlink", "hostio-readlink", 0);
14540
14541   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14542                          "vFile:fstat", "hostio-fstat", 0);
14543
14544   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14545                          "vAttach", "attach", 0);
14546
14547   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14548                          "vRun", "run", 0);
14549
14550   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14551                          "QStartNoAckMode", "noack", 0);
14552
14553   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14554                          "vKill", "kill", 0);
14555
14556   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14557                          "qAttached", "query-attached", 0);
14558
14559   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14560                          "ConditionalTracepoints",
14561                          "conditional-tracepoints", 0);
14562
14563   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14564                          "ConditionalBreakpoints",
14565                          "conditional-breakpoints", 0);
14566
14567   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14568                          "BreakpointCommands",
14569                          "breakpoint-commands", 0);
14570
14571   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14572                          "FastTracepoints", "fast-tracepoints", 0);
14573
14574   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14575                          "TracepointSource", "TracepointSource", 0);
14576
14577   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14578                          "QAllow", "allow", 0);
14579
14580   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14581                          "StaticTracepoints", "static-tracepoints", 0);
14582
14583   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14584                          "InstallInTrace", "install-in-trace", 0);
14585
14586   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14587                          "qXfer:statictrace:read", "read-sdata-object", 0);
14588
14589   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14590                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14591
14592   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14593                          "QDisableRandomization", "disable-randomization", 0);
14594
14595   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14596                          "QAgent", "agent", 0);
14597
14598   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14599                          "QTBuffer:size", "trace-buffer-size", 0);
14600
14601   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14602        "Qbtrace:off", "disable-btrace", 0);
14603
14604   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14605        "Qbtrace:bts", "enable-btrace-bts", 0);
14606
14607   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14608        "Qbtrace:pt", "enable-btrace-pt", 0);
14609
14610   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14611        "qXfer:btrace", "read-btrace", 0);
14612
14613   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14614        "qXfer:btrace-conf", "read-btrace-conf", 0);
14615
14616   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14617        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14618
14619   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14620        "multiprocess-feature", "multiprocess-feature", 0);
14621
14622   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14623                          "swbreak-feature", "swbreak-feature", 0);
14624
14625   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14626                          "hwbreak-feature", "hwbreak-feature", 0);
14627
14628   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14629                          "fork-event-feature", "fork-event-feature", 0);
14630
14631   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14632                          "vfork-event-feature", "vfork-event-feature", 0);
14633
14634   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14635        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14636
14637   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14638                          "vContSupported", "verbose-resume-supported", 0);
14639
14640   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14641                          "exec-event-feature", "exec-event-feature", 0);
14642
14643   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14644                          "vCtrlC", "ctrl-c", 0);
14645
14646   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14647                          "QThreadEvents", "thread-events", 0);
14648
14649   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14650                          "N stop reply", "no-resumed-stop-reply", 0);
14651
14652   /* Assert that we've registered "set remote foo-packet" commands
14653      for all packet configs.  */
14654   {
14655     int i;
14656
14657     for (i = 0; i < PACKET_MAX; i++)
14658       {
14659         /* Ideally all configs would have a command associated.  Some
14660            still don't though.  */
14661         int excepted;
14662
14663         switch (i)
14664           {
14665           case PACKET_QNonStop:
14666           case PACKET_EnableDisableTracepoints_feature:
14667           case PACKET_tracenz_feature:
14668           case PACKET_DisconnectedTracing_feature:
14669           case PACKET_augmented_libraries_svr4_read_feature:
14670           case PACKET_qCRC:
14671             /* Additions to this list need to be well justified:
14672                pre-existing packets are OK; new packets are not.  */
14673             excepted = 1;
14674             break;
14675           default:
14676             excepted = 0;
14677             break;
14678           }
14679
14680         /* This catches both forgetting to add a config command, and
14681            forgetting to remove a packet from the exception list.  */
14682         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14683       }
14684   }
14685
14686   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14687      Z sub-packet has its own set and show commands, but users may
14688      have sets to this variable in their .gdbinit files (or in their
14689      documentation).  */
14690   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14691                                 &remote_Z_packet_detect, _("\
14692 Set use of remote protocol `Z' packets"), _("\
14693 Show use of remote protocol `Z' packets "), _("\
14694 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14695 packets."),
14696                                 set_remote_protocol_Z_packet_cmd,
14697                                 show_remote_protocol_Z_packet_cmd,
14698                                 /* FIXME: i18n: Use of remote protocol
14699                                    `Z' packets is %s.  */
14700                                 &remote_set_cmdlist, &remote_show_cmdlist);
14701
14702   add_prefix_cmd ("remote", class_files, remote_command, _("\
14703 Manipulate files on the remote system\n\
14704 Transfer files to and from the remote target system."),
14705                   &remote_cmdlist, "remote ",
14706                   0 /* allow-unknown */, &cmdlist);
14707
14708   add_cmd ("put", class_files, remote_put_command,
14709            _("Copy a local file to the remote system."),
14710            &remote_cmdlist);
14711
14712   add_cmd ("get", class_files, remote_get_command,
14713            _("Copy a remote file to the local system."),
14714            &remote_cmdlist);
14715
14716   add_cmd ("delete", class_files, remote_delete_command,
14717            _("Delete a remote file."),
14718            &remote_cmdlist);
14719
14720   add_setshow_string_noescape_cmd ("exec-file", class_files,
14721                                    &remote_exec_file_var, _("\
14722 Set the remote pathname for \"run\""), _("\
14723 Show the remote pathname for \"run\""), NULL,
14724                                    set_remote_exec_file,
14725                                    show_remote_exec_file,
14726                                    &remote_set_cmdlist,
14727                                    &remote_show_cmdlist);
14728
14729   add_setshow_boolean_cmd ("range-stepping", class_run,
14730                            &use_range_stepping, _("\
14731 Enable or disable range stepping."), _("\
14732 Show whether target-assisted range stepping is enabled."), _("\
14733 If on, and the target supports it, when stepping a source line, GDB\n\
14734 tells the target to step the corresponding range of addresses itself instead\n\
14735 of issuing multiple single-steps.  This speeds up source level\n\
14736 stepping.  If off, GDB always issues single-steps, even if range\n\
14737 stepping is supported by the target.  The default is on."),
14738                            set_range_stepping,
14739                            show_range_stepping,
14740                            &setlist,
14741                            &showlist);
14742
14743   /* Eventually initialize fileio.  See fileio.c */
14744   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14745
14746   /* Take advantage of the fact that the TID field is not used, to tag
14747      special ptids with it set to != 0.  */
14748   magic_null_ptid = ptid_t (42000, -1, 1);
14749   not_sent_ptid = ptid_t (42000, -2, 1);
14750   any_thread_ptid = ptid_t (42000, 0, 1);
14751 }