Remove ptid_get_pid
[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 (ptid_is_pid (inferior_ptid)
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 (ptid_equal (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 (ptid_equal (state, ptid))
2718     return;
2719
2720   *buf++ = 'H';
2721   *buf++ = gen ? 'g' : 'c';
2722   if (ptid_equal (ptid, magic_null_ptid))
2723     xsnprintf (buf, endbuf - buf, "0");
2724   else if (ptid_equal (ptid, any_thread_ptid))
2725     xsnprintf (buf, endbuf - buf, "0");
2726   else if (ptid_equal (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_equal (ptid, magic_null_ptid))
2782     /* The main thread is always alive.  */
2783     return 1;
2784
2785   if (ptid.pid () != 0 && ptid_get_lwp (ptid) == 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_get_lwp (ptid);
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 (ptid_equal (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 (ptid_equal (tp->ptid, magic_null_ptid)
3842       || (tp->ptid.pid () != 0 && ptid_get_lwp (tp->ptid) == 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, ptid_get_lwp (tp->ptid));
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_equal (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 (ptid_equal (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   if (remote_multi_process_p (rs))
5632     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5633   else
5634     strcpy (rs->buf, "D");
5635
5636   putpkt (rs->buf);
5637   getpkt (&rs->buf, &rs->buf_size, 0);
5638
5639   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5640     ;
5641   else if (rs->buf[0] == '\0')
5642     error (_("Remote doesn't know how to detach"));
5643   else
5644     error (_("Can't detach process."));
5645 }
5646
5647 /* This detaches a program to which we previously attached, using
5648    inferior_ptid to identify the process.  After this is done, GDB
5649    can be used to debug some other program.  We better not have left
5650    any breakpoints in the target program or it'll die when it hits
5651    one.  */
5652
5653 void
5654 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5655 {
5656   int pid = inferior_ptid.pid ();
5657   struct remote_state *rs = get_remote_state ();
5658   int is_fork_parent;
5659
5660   if (!target_has_execution)
5661     error (_("No process to detach from."));
5662
5663   target_announce_detach (from_tty);
5664
5665   /* Tell the remote target to detach.  */
5666   remote_detach_pid (pid);
5667
5668   /* Exit only if this is the only active inferior.  */
5669   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5670     puts_filtered (_("Ending remote debugging.\n"));
5671
5672   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5673
5674   /* Check to see if we are detaching a fork parent.  Note that if we
5675      are detaching a fork child, tp == NULL.  */
5676   is_fork_parent = (tp != NULL
5677                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5678
5679   /* If doing detach-on-fork, we don't mourn, because that will delete
5680      breakpoints that should be available for the followed inferior.  */
5681   if (!is_fork_parent)
5682     {
5683       /* Save the pid as a string before mourning, since that will
5684          unpush the remote target, and we need the string after.  */
5685       std::string infpid = target_pid_to_str (ptid_t (pid));
5686
5687       target_mourn_inferior (inferior_ptid);
5688       if (print_inferior_events)
5689         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5690                            inf->num, infpid.c_str ());
5691     }
5692   else
5693     {
5694       inferior_ptid = null_ptid;
5695       detach_inferior (current_inferior ());
5696     }
5697 }
5698
5699 void
5700 remote_target::detach (inferior *inf, int from_tty)
5701 {
5702   remote_detach_1 (inf, from_tty);
5703 }
5704
5705 void
5706 extended_remote_target::detach (inferior *inf, int from_tty)
5707 {
5708   remote_detach_1 (inf, from_tty);
5709 }
5710
5711 /* Target follow-fork function for remote targets.  On entry, and
5712    at return, the current inferior is the fork parent.
5713
5714    Note that although this is currently only used for extended-remote,
5715    it is named remote_follow_fork in anticipation of using it for the
5716    remote target as well.  */
5717
5718 int
5719 remote_target::follow_fork (int follow_child, int detach_fork)
5720 {
5721   struct remote_state *rs = get_remote_state ();
5722   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5723
5724   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5725       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5726     {
5727       /* When following the parent and detaching the child, we detach
5728          the child here.  For the case of following the child and
5729          detaching the parent, the detach is done in the target-
5730          independent follow fork code in infrun.c.  We can't use
5731          target_detach when detaching an unfollowed child because
5732          the client side doesn't know anything about the child.  */
5733       if (detach_fork && !follow_child)
5734         {
5735           /* Detach the fork child.  */
5736           ptid_t child_ptid;
5737           pid_t child_pid;
5738
5739           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5740           child_pid = child_ptid.pid ();
5741
5742           remote_detach_pid (child_pid);
5743         }
5744     }
5745   return 0;
5746 }
5747
5748 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5749    in the program space of the new inferior.  On entry and at return the
5750    current inferior is the exec'ing inferior.  INF is the new exec'd
5751    inferior, which may be the same as the exec'ing inferior unless
5752    follow-exec-mode is "new".  */
5753
5754 void
5755 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5756 {
5757   /* We know that this is a target file name, so if it has the "target:"
5758      prefix we strip it off before saving it in the program space.  */
5759   if (is_target_filename (execd_pathname))
5760     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5761
5762   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5763 }
5764
5765 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5766
5767 void
5768 remote_target::disconnect (const char *args, int from_tty)
5769 {
5770   if (args)
5771     error (_("Argument given to \"disconnect\" when remotely debugging."));
5772
5773   /* Make sure we unpush even the extended remote targets.  Calling
5774      target_mourn_inferior won't unpush, and remote_mourn won't
5775      unpush if there is more than one inferior left.  */
5776   unpush_target (this);
5777   generic_mourn_inferior ();
5778
5779   if (from_tty)
5780     puts_filtered ("Ending remote debugging.\n");
5781 }
5782
5783 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5784    be chatty about it.  */
5785
5786 void
5787 extended_remote_target::attach (const char *args, int from_tty)
5788 {
5789   struct remote_state *rs = get_remote_state ();
5790   int pid;
5791   char *wait_status = NULL;
5792
5793   pid = parse_pid_to_attach (args);
5794
5795   /* Remote PID can be freely equal to getpid, do not check it here the same
5796      way as in other targets.  */
5797
5798   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5799     error (_("This target does not support attaching to a process"));
5800
5801   if (from_tty)
5802     {
5803       char *exec_file = get_exec_file (0);
5804
5805       if (exec_file)
5806         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5807                            target_pid_to_str (ptid_t (pid)));
5808       else
5809         printf_unfiltered (_("Attaching to %s\n"),
5810                            target_pid_to_str (ptid_t (pid)));
5811
5812       gdb_flush (gdb_stdout);
5813     }
5814
5815   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5816   putpkt (rs->buf);
5817   getpkt (&rs->buf, &rs->buf_size, 0);
5818
5819   switch (packet_ok (rs->buf,
5820                      &remote_protocol_packets[PACKET_vAttach]))
5821     {
5822     case PACKET_OK:
5823       if (!target_is_non_stop_p ())
5824         {
5825           /* Save the reply for later.  */
5826           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5827           strcpy (wait_status, rs->buf);
5828         }
5829       else if (strcmp (rs->buf, "OK") != 0)
5830         error (_("Attaching to %s failed with: %s"),
5831                target_pid_to_str (ptid_t (pid)),
5832                rs->buf);
5833       break;
5834     case PACKET_UNKNOWN:
5835       error (_("This target does not support attaching to a process"));
5836     default:
5837       error (_("Attaching to %s failed"),
5838              target_pid_to_str (ptid_t (pid)));
5839     }
5840
5841   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5842
5843   inferior_ptid = ptid_t (pid);
5844
5845   if (target_is_non_stop_p ())
5846     {
5847       struct thread_info *thread;
5848
5849       /* Get list of threads.  */
5850       update_thread_list ();
5851
5852       thread = first_thread_of_inferior (current_inferior ());
5853       if (thread)
5854         inferior_ptid = thread->ptid;
5855       else
5856         inferior_ptid = ptid_t (pid);
5857
5858       /* Invalidate our notion of the remote current thread.  */
5859       record_currthread (rs, minus_one_ptid);
5860     }
5861   else
5862     {
5863       /* Now, if we have thread information, update inferior_ptid.  */
5864       inferior_ptid = remote_current_thread (inferior_ptid);
5865
5866       /* Add the main thread to the thread list.  */
5867       thread_info *thr = add_thread_silent (inferior_ptid);
5868       /* Don't consider the thread stopped until we've processed the
5869          saved stop reply.  */
5870       set_executing (thr->ptid, true);
5871     }
5872
5873   /* Next, if the target can specify a description, read it.  We do
5874      this before anything involving memory or registers.  */
5875   target_find_description ();
5876
5877   if (!target_is_non_stop_p ())
5878     {
5879       /* Use the previously fetched status.  */
5880       gdb_assert (wait_status != NULL);
5881
5882       if (target_can_async_p ())
5883         {
5884           struct notif_event *reply
5885             =  remote_notif_parse (this, &notif_client_stop, wait_status);
5886
5887           push_stop_reply ((struct stop_reply *) reply);
5888
5889           target_async (1);
5890         }
5891       else
5892         {
5893           gdb_assert (wait_status != NULL);
5894           strcpy (rs->buf, wait_status);
5895           rs->cached_wait_status = 1;
5896         }
5897     }
5898   else
5899     gdb_assert (wait_status == NULL);
5900 }
5901
5902 /* Implementation of the to_post_attach method.  */
5903
5904 void
5905 extended_remote_target::post_attach (int pid)
5906 {
5907   /* Get text, data & bss offsets.  */
5908   get_offsets ();
5909
5910   /* In certain cases GDB might not have had the chance to start
5911      symbol lookup up until now.  This could happen if the debugged
5912      binary is not using shared libraries, the vsyscall page is not
5913      present (on Linux) and the binary itself hadn't changed since the
5914      debugging process was started.  */
5915   if (symfile_objfile != NULL)
5916     remote_check_symbols();
5917 }
5918
5919 \f
5920 /* Check for the availability of vCont.  This function should also check
5921    the response.  */
5922
5923 void
5924 remote_target::remote_vcont_probe ()
5925 {
5926   remote_state *rs = get_remote_state ();
5927   char *buf;
5928
5929   strcpy (rs->buf, "vCont?");
5930   putpkt (rs->buf);
5931   getpkt (&rs->buf, &rs->buf_size, 0);
5932   buf = rs->buf;
5933
5934   /* Make sure that the features we assume are supported.  */
5935   if (startswith (buf, "vCont"))
5936     {
5937       char *p = &buf[5];
5938       int support_c, support_C;
5939
5940       rs->supports_vCont.s = 0;
5941       rs->supports_vCont.S = 0;
5942       support_c = 0;
5943       support_C = 0;
5944       rs->supports_vCont.t = 0;
5945       rs->supports_vCont.r = 0;
5946       while (p && *p == ';')
5947         {
5948           p++;
5949           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5950             rs->supports_vCont.s = 1;
5951           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5952             rs->supports_vCont.S = 1;
5953           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5954             support_c = 1;
5955           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5956             support_C = 1;
5957           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5958             rs->supports_vCont.t = 1;
5959           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5960             rs->supports_vCont.r = 1;
5961
5962           p = strchr (p, ';');
5963         }
5964
5965       /* If c, and C are not all supported, we can't use vCont.  Clearing
5966          BUF will make packet_ok disable the packet.  */
5967       if (!support_c || !support_C)
5968         buf[0] = 0;
5969     }
5970
5971   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5972 }
5973
5974 /* Helper function for building "vCont" resumptions.  Write a
5975    resumption to P.  ENDP points to one-passed-the-end of the buffer
5976    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5977    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5978    resumed thread should be single-stepped and/or signalled.  If PTID
5979    equals minus_one_ptid, then all threads are resumed; if PTID
5980    represents a process, then all threads of the process are resumed;
5981    the thread to be stepped and/or signalled is given in the global
5982    INFERIOR_PTID.  */
5983
5984 char *
5985 remote_target::append_resumption (char *p, char *endp,
5986                                   ptid_t ptid, int step, gdb_signal siggnal)
5987 {
5988   struct remote_state *rs = get_remote_state ();
5989
5990   if (step && siggnal != GDB_SIGNAL_0)
5991     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5992   else if (step
5993            /* GDB is willing to range step.  */
5994            && use_range_stepping
5995            /* Target supports range stepping.  */
5996            && rs->supports_vCont.r
5997            /* We don't currently support range stepping multiple
5998               threads with a wildcard (though the protocol allows it,
5999               so stubs shouldn't make an active effort to forbid
6000               it).  */
6001            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6002     {
6003       struct thread_info *tp;
6004
6005       if (ptid_equal (ptid, minus_one_ptid))
6006         {
6007           /* If we don't know about the target thread's tid, then
6008              we're resuming magic_null_ptid (see caller).  */
6009           tp = find_thread_ptid (magic_null_ptid);
6010         }
6011       else
6012         tp = find_thread_ptid (ptid);
6013       gdb_assert (tp != NULL);
6014
6015       if (tp->control.may_range_step)
6016         {
6017           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6018
6019           p += xsnprintf (p, endp - p, ";r%s,%s",
6020                           phex_nz (tp->control.step_range_start,
6021                                    addr_size),
6022                           phex_nz (tp->control.step_range_end,
6023                                    addr_size));
6024         }
6025       else
6026         p += xsnprintf (p, endp - p, ";s");
6027     }
6028   else if (step)
6029     p += xsnprintf (p, endp - p, ";s");
6030   else if (siggnal != GDB_SIGNAL_0)
6031     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6032   else
6033     p += xsnprintf (p, endp - p, ";c");
6034
6035   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6036     {
6037       ptid_t nptid;
6038
6039       /* All (-1) threads of process.  */
6040       nptid = ptid_t (ptid.pid (), -1, 0);
6041
6042       p += xsnprintf (p, endp - p, ":");
6043       p = write_ptid (p, endp, nptid);
6044     }
6045   else if (!ptid_equal (ptid, minus_one_ptid))
6046     {
6047       p += xsnprintf (p, endp - p, ":");
6048       p = write_ptid (p, endp, ptid);
6049     }
6050
6051   return p;
6052 }
6053
6054 /* Clear the thread's private info on resume.  */
6055
6056 static void
6057 resume_clear_thread_private_info (struct thread_info *thread)
6058 {
6059   if (thread->priv != NULL)
6060     {
6061       remote_thread_info *priv = get_remote_thread_info (thread);
6062
6063       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6064       priv->watch_data_address = 0;
6065     }
6066 }
6067
6068 /* Append a vCont continue-with-signal action for threads that have a
6069    non-zero stop signal.  */
6070
6071 char *
6072 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6073                                                   ptid_t ptid)
6074 {
6075   struct thread_info *thread;
6076
6077   ALL_NON_EXITED_THREADS (thread)
6078     if (ptid_match (thread->ptid, ptid)
6079         && !ptid_equal (inferior_ptid, thread->ptid)
6080         && thread->suspend.stop_signal != GDB_SIGNAL_0)
6081       {
6082         p = append_resumption (p, endp, thread->ptid,
6083                                0, thread->suspend.stop_signal);
6084         thread->suspend.stop_signal = GDB_SIGNAL_0;
6085         resume_clear_thread_private_info (thread);
6086       }
6087
6088   return p;
6089 }
6090
6091 /* Set the target running, using the packets that use Hc
6092    (c/s/C/S).  */
6093
6094 void
6095 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6096                                       gdb_signal siggnal)
6097 {
6098   struct remote_state *rs = get_remote_state ();
6099   struct thread_info *thread;
6100   char *buf;
6101
6102   rs->last_sent_signal = siggnal;
6103   rs->last_sent_step = step;
6104
6105   /* The c/s/C/S resume packets use Hc, so set the continue
6106      thread.  */
6107   if (ptid_equal (ptid, minus_one_ptid))
6108     set_continue_thread (any_thread_ptid);
6109   else
6110     set_continue_thread (ptid);
6111
6112   ALL_NON_EXITED_THREADS (thread)
6113     resume_clear_thread_private_info (thread);
6114
6115   buf = rs->buf;
6116   if (::execution_direction == EXEC_REVERSE)
6117     {
6118       /* We don't pass signals to the target in reverse exec mode.  */
6119       if (info_verbose && siggnal != GDB_SIGNAL_0)
6120         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6121                  siggnal);
6122
6123       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6124         error (_("Remote reverse-step not supported."));
6125       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6126         error (_("Remote reverse-continue not supported."));
6127
6128       strcpy (buf, step ? "bs" : "bc");
6129     }
6130   else if (siggnal != GDB_SIGNAL_0)
6131     {
6132       buf[0] = step ? 'S' : 'C';
6133       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6134       buf[2] = tohex (((int) siggnal) & 0xf);
6135       buf[3] = '\0';
6136     }
6137   else
6138     strcpy (buf, step ? "s" : "c");
6139
6140   putpkt (buf);
6141 }
6142
6143 /* Resume the remote inferior by using a "vCont" packet.  The thread
6144    to be resumed is PTID; STEP and SIGGNAL indicate whether the
6145    resumed thread should be single-stepped and/or signalled.  If PTID
6146    equals minus_one_ptid, then all threads are resumed; the thread to
6147    be stepped and/or signalled is given in the global INFERIOR_PTID.
6148    This function returns non-zero iff it resumes the inferior.
6149
6150    This function issues a strict subset of all possible vCont commands
6151    at the moment.  */
6152
6153 int
6154 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6155                                          enum gdb_signal siggnal)
6156 {
6157   struct remote_state *rs = get_remote_state ();
6158   char *p;
6159   char *endp;
6160
6161   /* No reverse execution actions defined for vCont.  */
6162   if (::execution_direction == EXEC_REVERSE)
6163     return 0;
6164
6165   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6166     remote_vcont_probe ();
6167
6168   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6169     return 0;
6170
6171   p = rs->buf;
6172   endp = rs->buf + get_remote_packet_size ();
6173
6174   /* If we could generate a wider range of packets, we'd have to worry
6175      about overflowing BUF.  Should there be a generic
6176      "multi-part-packet" packet?  */
6177
6178   p += xsnprintf (p, endp - p, "vCont");
6179
6180   if (ptid_equal (ptid, magic_null_ptid))
6181     {
6182       /* MAGIC_NULL_PTID means that we don't have any active threads,
6183          so we don't have any TID numbers the inferior will
6184          understand.  Make sure to only send forms that do not specify
6185          a TID.  */
6186       append_resumption (p, endp, minus_one_ptid, step, siggnal);
6187     }
6188   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
6189     {
6190       /* Resume all threads (of all processes, or of a single
6191          process), with preference for INFERIOR_PTID.  This assumes
6192          inferior_ptid belongs to the set of all threads we are about
6193          to resume.  */
6194       if (step || siggnal != GDB_SIGNAL_0)
6195         {
6196           /* Step inferior_ptid, with or without signal.  */
6197           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6198         }
6199
6200       /* Also pass down any pending signaled resumption for other
6201          threads not the current.  */
6202       p = append_pending_thread_resumptions (p, endp, ptid);
6203
6204       /* And continue others without a signal.  */
6205       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6206     }
6207   else
6208     {
6209       /* Scheduler locking; resume only PTID.  */
6210       append_resumption (p, endp, ptid, step, siggnal);
6211     }
6212
6213   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6214   putpkt (rs->buf);
6215
6216   if (target_is_non_stop_p ())
6217     {
6218       /* In non-stop, the stub replies to vCont with "OK".  The stop
6219          reply will be reported asynchronously by means of a `%Stop'
6220          notification.  */
6221       getpkt (&rs->buf, &rs->buf_size, 0);
6222       if (strcmp (rs->buf, "OK") != 0)
6223         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6224     }
6225
6226   return 1;
6227 }
6228
6229 /* Tell the remote machine to resume.  */
6230
6231 void
6232 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6233 {
6234   struct remote_state *rs = get_remote_state ();
6235
6236   /* When connected in non-stop mode, the core resumes threads
6237      individually.  Resuming remote threads directly in target_resume
6238      would thus result in sending one packet per thread.  Instead, to
6239      minimize roundtrip latency, here we just store the resume
6240      request; the actual remote resumption will be done in
6241      target_commit_resume / remote_commit_resume, where we'll be able
6242      to do vCont action coalescing.  */
6243   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6244     {
6245       remote_thread_info *remote_thr;
6246
6247       if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6248         remote_thr = get_remote_thread_info (inferior_ptid);
6249       else
6250         remote_thr = get_remote_thread_info (ptid);
6251
6252       remote_thr->last_resume_step = step;
6253       remote_thr->last_resume_sig = siggnal;
6254       return;
6255     }
6256
6257   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6258      (explained in remote-notif.c:handle_notification) so
6259      remote_notif_process is not called.  We need find a place where
6260      it is safe to start a 'vNotif' sequence.  It is good to do it
6261      before resuming inferior, because inferior was stopped and no RSP
6262      traffic at that moment.  */
6263   if (!target_is_non_stop_p ())
6264     remote_notif_process (rs->notif_state, &notif_client_stop);
6265
6266   rs->last_resume_exec_dir = ::execution_direction;
6267
6268   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6269   if (!remote_resume_with_vcont (ptid, step, siggnal))
6270     remote_resume_with_hc (ptid, step, siggnal);
6271
6272   /* We are about to start executing the inferior, let's register it
6273      with the event loop.  NOTE: this is the one place where all the
6274      execution commands end up.  We could alternatively do this in each
6275      of the execution commands in infcmd.c.  */
6276   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6277      into infcmd.c in order to allow inferior function calls to work
6278      NOT asynchronously.  */
6279   if (target_can_async_p ())
6280     target_async (1);
6281
6282   /* We've just told the target to resume.  The remote server will
6283      wait for the inferior to stop, and then send a stop reply.  In
6284      the mean time, we can't start another command/query ourselves
6285      because the stub wouldn't be ready to process it.  This applies
6286      only to the base all-stop protocol, however.  In non-stop (which
6287      only supports vCont), the stub replies with an "OK", and is
6288      immediate able to process further serial input.  */
6289   if (!target_is_non_stop_p ())
6290     rs->waiting_for_stop_reply = 1;
6291 }
6292
6293 static int is_pending_fork_parent_thread (struct thread_info *thread);
6294
6295 /* Private per-inferior info for target remote processes.  */
6296
6297 struct remote_inferior : public private_inferior
6298 {
6299   /* Whether we can send a wildcard vCont for this process.  */
6300   bool may_wildcard_vcont = true;
6301 };
6302
6303 /* Get the remote private inferior data associated to INF.  */
6304
6305 static remote_inferior *
6306 get_remote_inferior (inferior *inf)
6307 {
6308   if (inf->priv == NULL)
6309     inf->priv.reset (new remote_inferior);
6310
6311   return static_cast<remote_inferior *> (inf->priv.get ());
6312 }
6313
6314 /* Class used to track the construction of a vCont packet in the
6315    outgoing packet buffer.  This is used to send multiple vCont
6316    packets if we have more actions than would fit a single packet.  */
6317
6318 class vcont_builder
6319 {
6320 public:
6321   explicit vcont_builder (remote_target *remote)
6322     : m_remote (remote)
6323   {
6324     restart ();
6325   }
6326
6327   void flush ();
6328   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6329
6330 private:
6331   void restart ();
6332
6333   /* The remote target.  */
6334   remote_target *m_remote;
6335
6336   /* Pointer to the first action.  P points here if no action has been
6337      appended yet.  */
6338   char *m_first_action;
6339
6340   /* Where the next action will be appended.  */
6341   char *m_p;
6342
6343   /* The end of the buffer.  Must never write past this.  */
6344   char *m_endp;
6345 };
6346
6347 /* Prepare the outgoing buffer for a new vCont packet.  */
6348
6349 void
6350 vcont_builder::restart ()
6351 {
6352   struct remote_state *rs = m_remote->get_remote_state ();
6353
6354   m_p = rs->buf;
6355   m_endp = rs->buf + m_remote->get_remote_packet_size ();
6356   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6357   m_first_action = m_p;
6358 }
6359
6360 /* If the vCont packet being built has any action, send it to the
6361    remote end.  */
6362
6363 void
6364 vcont_builder::flush ()
6365 {
6366   struct remote_state *rs;
6367
6368   if (m_p == m_first_action)
6369     return;
6370
6371   rs = m_remote->get_remote_state ();
6372   m_remote->putpkt (rs->buf);
6373   m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6374   if (strcmp (rs->buf, "OK") != 0)
6375     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6376 }
6377
6378 /* The largest action is range-stepping, with its two addresses.  This
6379    is more than sufficient.  If a new, bigger action is created, it'll
6380    quickly trigger a failed assertion in append_resumption (and we'll
6381    just bump this).  */
6382 #define MAX_ACTION_SIZE 200
6383
6384 /* Append a new vCont action in the outgoing packet being built.  If
6385    the action doesn't fit the packet along with previous actions, push
6386    what we've got so far to the remote end and start over a new vCont
6387    packet (with the new action).  */
6388
6389 void
6390 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6391 {
6392   char buf[MAX_ACTION_SIZE + 1];
6393
6394   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6395                                             ptid, step, siggnal);
6396
6397   /* Check whether this new action would fit in the vCont packet along
6398      with previous actions.  If not, send what we've got so far and
6399      start a new vCont packet.  */
6400   size_t rsize = endp - buf;
6401   if (rsize > m_endp - m_p)
6402     {
6403       flush ();
6404       restart ();
6405
6406       /* Should now fit.  */
6407       gdb_assert (rsize <= m_endp - m_p);
6408     }
6409
6410   memcpy (m_p, buf, rsize);
6411   m_p += rsize;
6412   *m_p = '\0';
6413 }
6414
6415 /* to_commit_resume implementation.  */
6416
6417 void
6418 remote_target::commit_resume ()
6419 {
6420   struct inferior *inf;
6421   struct thread_info *tp;
6422   int any_process_wildcard;
6423   int may_global_wildcard_vcont;
6424
6425   /* If connected in all-stop mode, we'd send the remote resume
6426      request directly from remote_resume.  Likewise if
6427      reverse-debugging, as there are no defined vCont actions for
6428      reverse execution.  */
6429   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6430     return;
6431
6432   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6433      instead of resuming all threads of each process individually.
6434      However, if any thread of a process must remain halted, we can't
6435      send wildcard resumes and must send one action per thread.
6436
6437      Care must be taken to not resume threads/processes the server
6438      side already told us are stopped, but the core doesn't know about
6439      yet, because the events are still in the vStopped notification
6440      queue.  For example:
6441
6442        #1 => vCont s:p1.1;c
6443        #2 <= OK
6444        #3 <= %Stopped T05 p1.1
6445        #4 => vStopped
6446        #5 <= T05 p1.2
6447        #6 => vStopped
6448        #7 <= OK
6449        #8 (infrun handles the stop for p1.1 and continues stepping)
6450        #9 => vCont s:p1.1;c
6451
6452      The last vCont above would resume thread p1.2 by mistake, because
6453      the server has no idea that the event for p1.2 had not been
6454      handled yet.
6455
6456      The server side must similarly ignore resume actions for the
6457      thread that has a pending %Stopped notification (and any other
6458      threads with events pending), until GDB acks the notification
6459      with vStopped.  Otherwise, e.g., the following case is
6460      mishandled:
6461
6462        #1 => g  (or any other packet)
6463        #2 <= [registers]
6464        #3 <= %Stopped T05 p1.2
6465        #4 => vCont s:p1.1;c
6466        #5 <= OK
6467
6468      Above, the server must not resume thread p1.2.  GDB can't know
6469      that p1.2 stopped until it acks the %Stopped notification, and
6470      since from GDB's perspective all threads should be running, it
6471      sends a "c" action.
6472
6473      Finally, special care must also be given to handling fork/vfork
6474      events.  A (v)fork event actually tells us that two processes
6475      stopped -- the parent and the child.  Until we follow the fork,
6476      we must not resume the child.  Therefore, if we have a pending
6477      fork follow, we must not send a global wildcard resume action
6478      (vCont;c).  We can still send process-wide wildcards though.  */
6479
6480   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6481   may_global_wildcard_vcont = 1;
6482
6483   /* And assume every process is individually wildcard-able too.  */
6484   ALL_NON_EXITED_INFERIORS (inf)
6485     {
6486       remote_inferior *priv = get_remote_inferior (inf);
6487
6488       priv->may_wildcard_vcont = true;
6489     }
6490
6491   /* Check for any pending events (not reported or processed yet) and
6492      disable process and global wildcard resumes appropriately.  */
6493   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6494
6495   ALL_NON_EXITED_THREADS (tp)
6496     {
6497       /* If a thread of a process is not meant to be resumed, then we
6498          can't wildcard that process.  */
6499       if (!tp->executing)
6500         {
6501           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6502
6503           /* And if we can't wildcard a process, we can't wildcard
6504              everything either.  */
6505           may_global_wildcard_vcont = 0;
6506           continue;
6507         }
6508
6509       /* If a thread is the parent of an unfollowed fork, then we
6510          can't do a global wildcard, as that would resume the fork
6511          child.  */
6512       if (is_pending_fork_parent_thread (tp))
6513         may_global_wildcard_vcont = 0;
6514     }
6515
6516   /* Now let's build the vCont packet(s).  Actions must be appended
6517      from narrower to wider scopes (thread -> process -> global).  If
6518      we end up with too many actions for a single packet vcont_builder
6519      flushes the current vCont packet to the remote side and starts a
6520      new one.  */
6521   struct vcont_builder vcont_builder (this);
6522
6523   /* Threads first.  */
6524   ALL_NON_EXITED_THREADS (tp)
6525     {
6526       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6527
6528       if (!tp->executing || remote_thr->vcont_resumed)
6529         continue;
6530
6531       gdb_assert (!thread_is_in_step_over_chain (tp));
6532
6533       if (!remote_thr->last_resume_step
6534           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6535           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6536         {
6537           /* We'll send a wildcard resume instead.  */
6538           remote_thr->vcont_resumed = 1;
6539           continue;
6540         }
6541
6542       vcont_builder.push_action (tp->ptid,
6543                                  remote_thr->last_resume_step,
6544                                  remote_thr->last_resume_sig);
6545       remote_thr->vcont_resumed = 1;
6546     }
6547
6548   /* Now check whether we can send any process-wide wildcard.  This is
6549      to avoid sending a global wildcard in the case nothing is
6550      supposed to be resumed.  */
6551   any_process_wildcard = 0;
6552
6553   ALL_NON_EXITED_INFERIORS (inf)
6554     {
6555       if (get_remote_inferior (inf)->may_wildcard_vcont)
6556         {
6557           any_process_wildcard = 1;
6558           break;
6559         }
6560     }
6561
6562   if (any_process_wildcard)
6563     {
6564       /* If all processes are wildcard-able, then send a single "c"
6565          action, otherwise, send an "all (-1) threads of process"
6566          continue action for each running process, if any.  */
6567       if (may_global_wildcard_vcont)
6568         {
6569           vcont_builder.push_action (minus_one_ptid,
6570                                      false, GDB_SIGNAL_0);
6571         }
6572       else
6573         {
6574           ALL_NON_EXITED_INFERIORS (inf)
6575             {
6576               if (get_remote_inferior (inf)->may_wildcard_vcont)
6577                 {
6578                   vcont_builder.push_action (ptid_t (inf->pid),
6579                                              false, GDB_SIGNAL_0);
6580                 }
6581             }
6582         }
6583     }
6584
6585   vcont_builder.flush ();
6586 }
6587
6588 \f
6589
6590 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6591    thread, all threads of a remote process, or all threads of all
6592    processes.  */
6593
6594 void
6595 remote_target::remote_stop_ns (ptid_t ptid)
6596 {
6597   struct remote_state *rs = get_remote_state ();
6598   char *p = rs->buf;
6599   char *endp = rs->buf + get_remote_packet_size ();
6600
6601   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6602     remote_vcont_probe ();
6603
6604   if (!rs->supports_vCont.t)
6605     error (_("Remote server does not support stopping threads"));
6606
6607   if (ptid_equal (ptid, minus_one_ptid)
6608       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6609     p += xsnprintf (p, endp - p, "vCont;t");
6610   else
6611     {
6612       ptid_t nptid;
6613
6614       p += xsnprintf (p, endp - p, "vCont;t:");
6615
6616       if (ptid_is_pid (ptid))
6617           /* All (-1) threads of process.  */
6618         nptid = ptid_t (ptid.pid (), -1, 0);
6619       else
6620         {
6621           /* Small optimization: if we already have a stop reply for
6622              this thread, no use in telling the stub we want this
6623              stopped.  */
6624           if (peek_stop_reply (ptid))
6625             return;
6626
6627           nptid = ptid;
6628         }
6629
6630       write_ptid (p, endp, nptid);
6631     }
6632
6633   /* In non-stop, we get an immediate OK reply.  The stop reply will
6634      come in asynchronously by notification.  */
6635   putpkt (rs->buf);
6636   getpkt (&rs->buf, &rs->buf_size, 0);
6637   if (strcmp (rs->buf, "OK") != 0)
6638     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6639 }
6640
6641 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6642    interrupt the remote target.  It is undefined which thread of which
6643    process reports the interrupt.  */
6644
6645 void
6646 remote_target::remote_interrupt_as ()
6647 {
6648   struct remote_state *rs = get_remote_state ();
6649
6650   rs->ctrlc_pending_p = 1;
6651
6652   /* If the inferior is stopped already, but the core didn't know
6653      about it yet, just ignore the request.  The cached wait status
6654      will be collected in remote_wait.  */
6655   if (rs->cached_wait_status)
6656     return;
6657
6658   /* Send interrupt_sequence to remote target.  */
6659   send_interrupt_sequence ();
6660 }
6661
6662 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6663    the remote target.  It is undefined which thread of which process
6664    reports the interrupt.  Throws an error if the packet is not
6665    supported by the server.  */
6666
6667 void
6668 remote_target::remote_interrupt_ns ()
6669 {
6670   struct remote_state *rs = get_remote_state ();
6671   char *p = rs->buf;
6672   char *endp = rs->buf + get_remote_packet_size ();
6673
6674   xsnprintf (p, endp - p, "vCtrlC");
6675
6676   /* In non-stop, we get an immediate OK reply.  The stop reply will
6677      come in asynchronously by notification.  */
6678   putpkt (rs->buf);
6679   getpkt (&rs->buf, &rs->buf_size, 0);
6680
6681   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6682     {
6683     case PACKET_OK:
6684       break;
6685     case PACKET_UNKNOWN:
6686       error (_("No support for interrupting the remote target."));
6687     case PACKET_ERROR:
6688       error (_("Interrupting target failed: %s"), rs->buf);
6689     }
6690 }
6691
6692 /* Implement the to_stop function for the remote targets.  */
6693
6694 void
6695 remote_target::stop (ptid_t ptid)
6696 {
6697   if (remote_debug)
6698     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6699
6700   if (target_is_non_stop_p ())
6701     remote_stop_ns (ptid);
6702   else
6703     {
6704       /* We don't currently have a way to transparently pause the
6705          remote target in all-stop mode.  Interrupt it instead.  */
6706       remote_interrupt_as ();
6707     }
6708 }
6709
6710 /* Implement the to_interrupt function for the remote targets.  */
6711
6712 void
6713 remote_target::interrupt ()
6714 {
6715   if (remote_debug)
6716     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6717
6718   if (target_is_non_stop_p ())
6719     remote_interrupt_ns ();
6720   else
6721     remote_interrupt_as ();
6722 }
6723
6724 /* Implement the to_pass_ctrlc function for the remote targets.  */
6725
6726 void
6727 remote_target::pass_ctrlc ()
6728 {
6729   struct remote_state *rs = get_remote_state ();
6730
6731   if (remote_debug)
6732     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6733
6734   /* If we're starting up, we're not fully synced yet.  Quit
6735      immediately.  */
6736   if (rs->starting_up)
6737     quit ();
6738   /* If ^C has already been sent once, offer to disconnect.  */
6739   else if (rs->ctrlc_pending_p)
6740     interrupt_query ();
6741   else
6742     target_interrupt ();
6743 }
6744
6745 /* Ask the user what to do when an interrupt is received.  */
6746
6747 void
6748 remote_target::interrupt_query ()
6749 {
6750   struct remote_state *rs = get_remote_state ();
6751
6752   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6753     {
6754       if (query (_("The target is not responding to interrupt requests.\n"
6755                    "Stop debugging it? ")))
6756         {
6757           remote_unpush_target ();
6758           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6759         }
6760     }
6761   else
6762     {
6763       if (query (_("Interrupted while waiting for the program.\n"
6764                    "Give up waiting? ")))
6765         quit ();
6766     }
6767 }
6768
6769 /* Enable/disable target terminal ownership.  Most targets can use
6770    terminal groups to control terminal ownership.  Remote targets are
6771    different in that explicit transfer of ownership to/from GDB/target
6772    is required.  */
6773
6774 void
6775 remote_target::terminal_inferior ()
6776 {
6777   /* NOTE: At this point we could also register our selves as the
6778      recipient of all input.  Any characters typed could then be
6779      passed on down to the target.  */
6780 }
6781
6782 void
6783 remote_target::terminal_ours ()
6784 {
6785 }
6786
6787 static void
6788 remote_console_output (char *msg)
6789 {
6790   char *p;
6791
6792   for (p = msg; p[0] && p[1]; p += 2)
6793     {
6794       char tb[2];
6795       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6796
6797       tb[0] = c;
6798       tb[1] = 0;
6799       fputs_unfiltered (tb, gdb_stdtarg);
6800     }
6801   gdb_flush (gdb_stdtarg);
6802 }
6803
6804 DEF_VEC_O(cached_reg_t);
6805
6806 typedef struct stop_reply
6807 {
6808   struct notif_event base;
6809
6810   /* The identifier of the thread about this event  */
6811   ptid_t ptid;
6812
6813   /* The remote state this event is associated with.  When the remote
6814      connection, represented by a remote_state object, is closed,
6815      all the associated stop_reply events should be released.  */
6816   struct remote_state *rs;
6817
6818   struct target_waitstatus ws;
6819
6820   /* The architecture associated with the expedited registers.  */
6821   gdbarch *arch;
6822
6823   /* Expedited registers.  This makes remote debugging a bit more
6824      efficient for those targets that provide critical registers as
6825      part of their normal status mechanism (as another roundtrip to
6826      fetch them is avoided).  */
6827   VEC(cached_reg_t) *regcache;
6828
6829   enum target_stop_reason stop_reason;
6830
6831   CORE_ADDR watch_data_address;
6832
6833   int core;
6834 } *stop_reply_p;
6835
6836 static void
6837 stop_reply_xfree (struct stop_reply *r)
6838 {
6839   notif_event_xfree ((struct notif_event *) r);
6840 }
6841
6842 /* Return the length of the stop reply queue.  */
6843
6844 int
6845 remote_target::stop_reply_queue_length ()
6846 {
6847   remote_state *rs = get_remote_state ();
6848   return rs->stop_reply_queue.size ();
6849 }
6850
6851 void
6852 remote_notif_stop_parse (remote_target *remote,
6853                          struct notif_client *self, char *buf,
6854                          struct notif_event *event)
6855 {
6856   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6857 }
6858
6859 static void
6860 remote_notif_stop_ack (remote_target *remote,
6861                        struct notif_client *self, char *buf,
6862                        struct notif_event *event)
6863 {
6864   struct stop_reply *stop_reply = (struct stop_reply *) event;
6865
6866   /* acknowledge */
6867   putpkt (remote, self->ack_command);
6868
6869   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6870     {
6871       /* We got an unknown stop reply.  */
6872       error (_("Unknown stop reply"));
6873     }
6874
6875   remote->push_stop_reply (stop_reply);
6876 }
6877
6878 static int
6879 remote_notif_stop_can_get_pending_events (remote_target *remote,
6880                                           struct notif_client *self)
6881 {
6882   /* We can't get pending events in remote_notif_process for
6883      notification stop, and we have to do this in remote_wait_ns
6884      instead.  If we fetch all queued events from stub, remote stub
6885      may exit and we have no chance to process them back in
6886      remote_wait_ns.  */
6887   remote_state *rs = remote->get_remote_state ();
6888   mark_async_event_handler (rs->remote_async_inferior_event_token);
6889   return 0;
6890 }
6891
6892 static void
6893 stop_reply_dtr (struct notif_event *event)
6894 {
6895   struct stop_reply *r = (struct stop_reply *) event;
6896   cached_reg_t *reg;
6897   int ix;
6898
6899   for (ix = 0;
6900        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6901        ix++)
6902     xfree (reg->data);
6903
6904   VEC_free (cached_reg_t, r->regcache);
6905 }
6906
6907 static struct notif_event *
6908 remote_notif_stop_alloc_reply (void)
6909 {
6910   /* We cast to a pointer to the "base class".  */
6911   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6912
6913   r->dtr = stop_reply_dtr;
6914
6915   return r;
6916 }
6917
6918 /* A client of notification Stop.  */
6919
6920 struct notif_client notif_client_stop =
6921 {
6922   "Stop",
6923   "vStopped",
6924   remote_notif_stop_parse,
6925   remote_notif_stop_ack,
6926   remote_notif_stop_can_get_pending_events,
6927   remote_notif_stop_alloc_reply,
6928   REMOTE_NOTIF_STOP,
6929 };
6930
6931 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6932    the pid of the process that owns the threads we want to check, or
6933    -1 if we want to check all threads.  */
6934
6935 static int
6936 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6937                         ptid_t thread_ptid)
6938 {
6939   if (ws->kind == TARGET_WAITKIND_FORKED
6940       || ws->kind == TARGET_WAITKIND_VFORKED)
6941     {
6942       if (event_pid == -1 || event_pid == thread_ptid.pid ())
6943         return 1;
6944     }
6945
6946   return 0;
6947 }
6948
6949 /* Return the thread's pending status used to determine whether the
6950    thread is a fork parent stopped at a fork event.  */
6951
6952 static struct target_waitstatus *
6953 thread_pending_fork_status (struct thread_info *thread)
6954 {
6955   if (thread->suspend.waitstatus_pending_p)
6956     return &thread->suspend.waitstatus;
6957   else
6958     return &thread->pending_follow;
6959 }
6960
6961 /* Determine if THREAD is a pending fork parent thread.  */
6962
6963 static int
6964 is_pending_fork_parent_thread (struct thread_info *thread)
6965 {
6966   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6967   int pid = -1;
6968
6969   return is_pending_fork_parent (ws, pid, thread->ptid);
6970 }
6971
6972 /* If CONTEXT contains any fork child threads that have not been
6973    reported yet, remove them from the CONTEXT list.  If such a
6974    thread exists it is because we are stopped at a fork catchpoint
6975    and have not yet called follow_fork, which will set up the
6976    host-side data structures for the new process.  */
6977
6978 void
6979 remote_target::remove_new_fork_children (threads_listing_context *context)
6980 {
6981   struct thread_info * thread;
6982   int pid = -1;
6983   struct notif_client *notif = &notif_client_stop;
6984
6985   /* For any threads stopped at a fork event, remove the corresponding
6986      fork child threads from the CONTEXT list.  */
6987   ALL_NON_EXITED_THREADS (thread)
6988     {
6989       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6990
6991       if (is_pending_fork_parent (ws, pid, thread->ptid))
6992         context->remove_thread (ws->value.related_pid);
6993     }
6994
6995   /* Check for any pending fork events (not reported or processed yet)
6996      in process PID and remove those fork child threads from the
6997      CONTEXT list as well.  */
6998   remote_notif_get_pending_events (notif);
6999   for (auto &event : get_remote_state ()->stop_reply_queue)
7000     if (event->ws.kind == TARGET_WAITKIND_FORKED
7001         || event->ws.kind == TARGET_WAITKIND_VFORKED
7002         || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7003       context->remove_thread (event->ws.value.related_pid);
7004 }
7005
7006 /* Check whether any event pending in the vStopped queue would prevent
7007    a global or process wildcard vCont action.  Clear
7008    *may_global_wildcard if we can't do a global wildcard (vCont;c),
7009    and clear the event inferior's may_wildcard_vcont flag if we can't
7010    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
7011
7012 void
7013 remote_target::check_pending_events_prevent_wildcard_vcont
7014   (int *may_global_wildcard)
7015 {
7016   struct notif_client *notif = &notif_client_stop;
7017
7018   remote_notif_get_pending_events (notif);
7019   for (auto &event : get_remote_state ()->stop_reply_queue)
7020     {
7021       if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7022           || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7023         continue;
7024
7025       if (event->ws.kind == TARGET_WAITKIND_FORKED
7026           || event->ws.kind == TARGET_WAITKIND_VFORKED)
7027         *may_global_wildcard = 0;
7028
7029       struct inferior *inf = find_inferior_ptid (event->ptid);
7030
7031       /* This may be the first time we heard about this process.
7032          Regardless, we must not do a global wildcard resume, otherwise
7033          we'd resume this process too.  */
7034       *may_global_wildcard = 0;
7035       if (inf != NULL)
7036         get_remote_inferior (inf)->may_wildcard_vcont = false;
7037     }
7038 }
7039
7040 /* Discard all pending stop replies of inferior INF.  */
7041
7042 void
7043 remote_target::discard_pending_stop_replies (struct inferior *inf)
7044 {
7045   struct stop_reply *reply;
7046   struct remote_state *rs = get_remote_state ();
7047   struct remote_notif_state *rns = rs->notif_state;
7048
7049   /* This function can be notified when an inferior exists.  When the
7050      target is not remote, the notification state is NULL.  */
7051   if (rs->remote_desc == NULL)
7052     return;
7053
7054   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7055
7056   /* Discard the in-flight notification.  */
7057   if (reply != NULL && reply->ptid.pid () == inf->pid)
7058     {
7059       stop_reply_xfree (reply);
7060       rns->pending_event[notif_client_stop.id] = NULL;
7061     }
7062
7063   /* Discard the stop replies we have already pulled with
7064      vStopped.  */
7065   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7066                               rs->stop_reply_queue.end (),
7067                               [=] (const stop_reply_up &event)
7068                               {
7069                                 return event->ptid.pid () == inf->pid;
7070                               });
7071   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7072 }
7073
7074 /* Discard the stop replies for RS in stop_reply_queue.  */
7075
7076 void
7077 remote_target::discard_pending_stop_replies_in_queue ()
7078 {
7079   remote_state *rs = get_remote_state ();
7080
7081   /* Discard the stop replies we have already pulled with
7082      vStopped.  */
7083   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7084                               rs->stop_reply_queue.end (),
7085                               [=] (const stop_reply_up &event)
7086                               {
7087                                 return event->rs == rs;
7088                               });
7089   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7090 }
7091
7092 /* Remove the first reply in 'stop_reply_queue' which matches
7093    PTID.  */
7094
7095 struct stop_reply *
7096 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7097 {
7098   remote_state *rs = get_remote_state ();
7099
7100   auto iter = std::find_if (rs->stop_reply_queue.begin (),
7101                             rs->stop_reply_queue.end (),
7102                             [=] (const stop_reply_up &event)
7103                             {
7104                               return event->ptid.matches (ptid);
7105                             });
7106   struct stop_reply *result;
7107   if (iter == rs->stop_reply_queue.end ())
7108     result = nullptr;
7109   else
7110     {
7111       result = iter->release ();
7112       rs->stop_reply_queue.erase (iter);
7113     }
7114
7115   if (notif_debug)
7116     fprintf_unfiltered (gdb_stdlog,
7117                         "notif: discard queued event: 'Stop' in %s\n",
7118                         target_pid_to_str (ptid));
7119
7120   return result;
7121 }
7122
7123 /* Look for a queued stop reply belonging to PTID.  If one is found,
7124    remove it from the queue, and return it.  Returns NULL if none is
7125    found.  If there are still queued events left to process, tell the
7126    event loop to get back to target_wait soon.  */
7127
7128 struct stop_reply *
7129 remote_target::queued_stop_reply (ptid_t ptid)
7130 {
7131   remote_state *rs = get_remote_state ();
7132   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7133
7134   if (!rs->stop_reply_queue.empty ())
7135     {
7136       /* There's still at least an event left.  */
7137       mark_async_event_handler (rs->remote_async_inferior_event_token);
7138     }
7139
7140   return r;
7141 }
7142
7143 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7144    know that we now have at least one queued event left to pass to the
7145    core side, tell the event loop to get back to target_wait soon.  */
7146
7147 void
7148 remote_target::push_stop_reply (struct stop_reply *new_event)
7149 {
7150   remote_state *rs = get_remote_state ();
7151   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7152
7153   if (notif_debug)
7154     fprintf_unfiltered (gdb_stdlog,
7155                         "notif: push 'Stop' %s to queue %d\n",
7156                         target_pid_to_str (new_event->ptid),
7157                         int (rs->stop_reply_queue.size ()));
7158
7159   mark_async_event_handler (rs->remote_async_inferior_event_token);
7160 }
7161
7162 /* Returns true if we have a stop reply for PTID.  */
7163
7164 int
7165 remote_target::peek_stop_reply (ptid_t ptid)
7166 {
7167   remote_state *rs = get_remote_state ();
7168   for (auto &event : rs->stop_reply_queue)
7169     if (ptid == event->ptid
7170         && event->ws.kind == TARGET_WAITKIND_STOPPED)
7171       return 1;
7172   return 0;
7173 }
7174
7175 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7176    starting with P and ending with PEND matches PREFIX.  */
7177
7178 static int
7179 strprefix (const char *p, const char *pend, const char *prefix)
7180 {
7181   for ( ; p < pend; p++, prefix++)
7182     if (*p != *prefix)
7183       return 0;
7184   return *prefix == '\0';
7185 }
7186
7187 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7188    result is stored in EVENT, or throws an error.  */
7189
7190 void
7191 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7192 {
7193   remote_arch_state *rsa = NULL;
7194   ULONGEST addr;
7195   const char *p;
7196   int skipregs = 0;
7197
7198   event->ptid = null_ptid;
7199   event->rs = get_remote_state ();
7200   event->ws.kind = TARGET_WAITKIND_IGNORE;
7201   event->ws.value.integer = 0;
7202   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7203   event->regcache = NULL;
7204   event->core = -1;
7205
7206   switch (buf[0])
7207     {
7208     case 'T':           /* Status with PC, SP, FP, ...  */
7209       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7210       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7211             ss = signal number
7212             n... = register number
7213             r... = register contents
7214       */
7215
7216       p = &buf[3];      /* after Txx */
7217       while (*p)
7218         {
7219           const char *p1;
7220           int fieldsize;
7221
7222           p1 = strchr (p, ':');
7223           if (p1 == NULL)
7224             error (_("Malformed packet(a) (missing colon): %s\n\
7225 Packet: '%s'\n"),
7226                    p, buf);
7227           if (p == p1)
7228             error (_("Malformed packet(a) (missing register number): %s\n\
7229 Packet: '%s'\n"),
7230                    p, buf);
7231
7232           /* Some "registers" are actually extended stop information.
7233              Note if you're adding a new entry here: GDB 7.9 and
7234              earlier assume that all register "numbers" that start
7235              with an hex digit are real register numbers.  Make sure
7236              the server only sends such a packet if it knows the
7237              client understands it.  */
7238
7239           if (strprefix (p, p1, "thread"))
7240             event->ptid = read_ptid (++p1, &p);
7241           else if (strprefix (p, p1, "syscall_entry"))
7242             {
7243               ULONGEST sysno;
7244
7245               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7246               p = unpack_varlen_hex (++p1, &sysno);
7247               event->ws.value.syscall_number = (int) sysno;
7248             }
7249           else if (strprefix (p, p1, "syscall_return"))
7250             {
7251               ULONGEST sysno;
7252
7253               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7254               p = unpack_varlen_hex (++p1, &sysno);
7255               event->ws.value.syscall_number = (int) sysno;
7256             }
7257           else if (strprefix (p, p1, "watch")
7258                    || strprefix (p, p1, "rwatch")
7259                    || strprefix (p, p1, "awatch"))
7260             {
7261               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7262               p = unpack_varlen_hex (++p1, &addr);
7263               event->watch_data_address = (CORE_ADDR) addr;
7264             }
7265           else if (strprefix (p, p1, "swbreak"))
7266             {
7267               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7268
7269               /* Make sure the stub doesn't forget to indicate support
7270                  with qSupported.  */
7271               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7272                 error (_("Unexpected swbreak stop reason"));
7273
7274               /* The value part is documented as "must be empty",
7275                  though we ignore it, in case we ever decide to make
7276                  use of it in a backward compatible way.  */
7277               p = strchrnul (p1 + 1, ';');
7278             }
7279           else if (strprefix (p, p1, "hwbreak"))
7280             {
7281               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7282
7283               /* Make sure the stub doesn't forget to indicate support
7284                  with qSupported.  */
7285               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7286                 error (_("Unexpected hwbreak stop reason"));
7287
7288               /* See above.  */
7289               p = strchrnul (p1 + 1, ';');
7290             }
7291           else if (strprefix (p, p1, "library"))
7292             {
7293               event->ws.kind = TARGET_WAITKIND_LOADED;
7294               p = strchrnul (p1 + 1, ';');
7295             }
7296           else if (strprefix (p, p1, "replaylog"))
7297             {
7298               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7299               /* p1 will indicate "begin" or "end", but it makes
7300                  no difference for now, so ignore it.  */
7301               p = strchrnul (p1 + 1, ';');
7302             }
7303           else if (strprefix (p, p1, "core"))
7304             {
7305               ULONGEST c;
7306
7307               p = unpack_varlen_hex (++p1, &c);
7308               event->core = c;
7309             }
7310           else if (strprefix (p, p1, "fork"))
7311             {
7312               event->ws.value.related_pid = read_ptid (++p1, &p);
7313               event->ws.kind = TARGET_WAITKIND_FORKED;
7314             }
7315           else if (strprefix (p, p1, "vfork"))
7316             {
7317               event->ws.value.related_pid = read_ptid (++p1, &p);
7318               event->ws.kind = TARGET_WAITKIND_VFORKED;
7319             }
7320           else if (strprefix (p, p1, "vforkdone"))
7321             {
7322               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7323               p = strchrnul (p1 + 1, ';');
7324             }
7325           else if (strprefix (p, p1, "exec"))
7326             {
7327               ULONGEST ignored;
7328               char pathname[PATH_MAX];
7329               int pathlen;
7330
7331               /* Determine the length of the execd pathname.  */
7332               p = unpack_varlen_hex (++p1, &ignored);
7333               pathlen = (p - p1) / 2;
7334
7335               /* Save the pathname for event reporting and for
7336                  the next run command.  */
7337               hex2bin (p1, (gdb_byte *) pathname, pathlen);
7338               pathname[pathlen] = '\0';
7339
7340               /* This is freed during event handling.  */
7341               event->ws.value.execd_pathname = xstrdup (pathname);
7342               event->ws.kind = TARGET_WAITKIND_EXECD;
7343
7344               /* Skip the registers included in this packet, since
7345                  they may be for an architecture different from the
7346                  one used by the original program.  */
7347               skipregs = 1;
7348             }
7349           else if (strprefix (p, p1, "create"))
7350             {
7351               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7352               p = strchrnul (p1 + 1, ';');
7353             }
7354           else
7355             {
7356               ULONGEST pnum;
7357               const char *p_temp;
7358
7359               if (skipregs)
7360                 {
7361                   p = strchrnul (p1 + 1, ';');
7362                   p++;
7363                   continue;
7364                 }
7365
7366               /* Maybe a real ``P'' register number.  */
7367               p_temp = unpack_varlen_hex (p, &pnum);
7368               /* If the first invalid character is the colon, we got a
7369                  register number.  Otherwise, it's an unknown stop
7370                  reason.  */
7371               if (p_temp == p1)
7372                 {
7373                   /* If we haven't parsed the event's thread yet, find
7374                      it now, in order to find the architecture of the
7375                      reported expedited registers.  */
7376                   if (event->ptid == null_ptid)
7377                     {
7378                       const char *thr = strstr (p1 + 1, ";thread:");
7379                       if (thr != NULL)
7380                         event->ptid = read_ptid (thr + strlen (";thread:"),
7381                                                  NULL);
7382                       else
7383                         {
7384                           /* Either the current thread hasn't changed,
7385                              or the inferior is not multi-threaded.
7386                              The event must be for the thread we last
7387                              set as (or learned as being) current.  */
7388                           event->ptid = event->rs->general_thread;
7389                         }
7390                     }
7391
7392                   if (rsa == NULL)
7393                     {
7394                       inferior *inf = (event->ptid == null_ptid
7395                                        ? NULL
7396                                        : find_inferior_ptid (event->ptid));
7397                       /* If this is the first time we learn anything
7398                          about this process, skip the registers
7399                          included in this packet, since we don't yet
7400                          know which architecture to use to parse them.
7401                          We'll determine the architecture later when
7402                          we process the stop reply and retrieve the
7403                          target description, via
7404                          remote_notice_new_inferior ->
7405                          post_create_inferior.  */
7406                       if (inf == NULL)
7407                         {
7408                           p = strchrnul (p1 + 1, ';');
7409                           p++;
7410                           continue;
7411                         }
7412
7413                       event->arch = inf->gdbarch;
7414                       rsa = event->rs->get_remote_arch_state (event->arch);
7415                     }
7416
7417                   packet_reg *reg
7418                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7419                   cached_reg_t cached_reg;
7420
7421                   if (reg == NULL)
7422                     error (_("Remote sent bad register number %s: %s\n\
7423 Packet: '%s'\n"),
7424                            hex_string (pnum), p, buf);
7425
7426                   cached_reg.num = reg->regnum;
7427                   cached_reg.data = (gdb_byte *)
7428                     xmalloc (register_size (event->arch, reg->regnum));
7429
7430                   p = p1 + 1;
7431                   fieldsize = hex2bin (p, cached_reg.data,
7432                                        register_size (event->arch, reg->regnum));
7433                   p += 2 * fieldsize;
7434                   if (fieldsize < register_size (event->arch, reg->regnum))
7435                     warning (_("Remote reply is too short: %s"), buf);
7436
7437                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7438                 }
7439               else
7440                 {
7441                   /* Not a number.  Silently skip unknown optional
7442                      info.  */
7443                   p = strchrnul (p1 + 1, ';');
7444                 }
7445             }
7446
7447           if (*p != ';')
7448             error (_("Remote register badly formatted: %s\nhere: %s"),
7449                    buf, p);
7450           ++p;
7451         }
7452
7453       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7454         break;
7455
7456       /* fall through */
7457     case 'S':           /* Old style status, just signal only.  */
7458       {
7459         int sig;
7460
7461         event->ws.kind = TARGET_WAITKIND_STOPPED;
7462         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7463         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7464           event->ws.value.sig = (enum gdb_signal) sig;
7465         else
7466           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7467       }
7468       break;
7469     case 'w':           /* Thread exited.  */
7470       {
7471         const char *p;
7472         ULONGEST value;
7473
7474         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7475         p = unpack_varlen_hex (&buf[1], &value);
7476         event->ws.value.integer = value;
7477         if (*p != ';')
7478           error (_("stop reply packet badly formatted: %s"), buf);
7479         event->ptid = read_ptid (++p, NULL);
7480         break;
7481       }
7482     case 'W':           /* Target exited.  */
7483     case 'X':
7484       {
7485         const char *p;
7486         int pid;
7487         ULONGEST value;
7488
7489         /* GDB used to accept only 2 hex chars here.  Stubs should
7490            only send more if they detect GDB supports multi-process
7491            support.  */
7492         p = unpack_varlen_hex (&buf[1], &value);
7493
7494         if (buf[0] == 'W')
7495           {
7496             /* The remote process exited.  */
7497             event->ws.kind = TARGET_WAITKIND_EXITED;
7498             event->ws.value.integer = value;
7499           }
7500         else
7501           {
7502             /* The remote process exited with a signal.  */
7503             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7504             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7505               event->ws.value.sig = (enum gdb_signal) value;
7506             else
7507               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7508           }
7509
7510         /* If no process is specified, assume inferior_ptid.  */
7511         pid = inferior_ptid.pid ();
7512         if (*p == '\0')
7513           ;
7514         else if (*p == ';')
7515           {
7516             p++;
7517
7518             if (*p == '\0')
7519               ;
7520             else if (startswith (p, "process:"))
7521               {
7522                 ULONGEST upid;
7523
7524                 p += sizeof ("process:") - 1;
7525                 unpack_varlen_hex (p, &upid);
7526                 pid = upid;
7527               }
7528             else
7529               error (_("unknown stop reply packet: %s"), buf);
7530           }
7531         else
7532           error (_("unknown stop reply packet: %s"), buf);
7533         event->ptid = ptid_t (pid);
7534       }
7535       break;
7536     case 'N':
7537       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7538       event->ptid = minus_one_ptid;
7539       break;
7540     }
7541
7542   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7543     error (_("No process or thread specified in stop reply: %s"), buf);
7544 }
7545
7546 /* When the stub wants to tell GDB about a new notification reply, it
7547    sends a notification (%Stop, for example).  Those can come it at
7548    any time, hence, we have to make sure that any pending
7549    putpkt/getpkt sequence we're making is finished, before querying
7550    the stub for more events with the corresponding ack command
7551    (vStopped, for example).  E.g., if we started a vStopped sequence
7552    immediately upon receiving the notification, something like this
7553    could happen:
7554
7555     1.1) --> Hg 1
7556     1.2) <-- OK
7557     1.3) --> g
7558     1.4) <-- %Stop
7559     1.5) --> vStopped
7560     1.6) <-- (registers reply to step #1.3)
7561
7562    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7563    query.
7564
7565    To solve this, whenever we parse a %Stop notification successfully,
7566    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7567    doing whatever we were doing:
7568
7569     2.1) --> Hg 1
7570     2.2) <-- OK
7571     2.3) --> g
7572     2.4) <-- %Stop
7573       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7574     2.5) <-- (registers reply to step #2.3)
7575
7576    Eventualy after step #2.5, we return to the event loop, which
7577    notices there's an event on the
7578    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7579    associated callback --- the function below.  At this point, we're
7580    always safe to start a vStopped sequence. :
7581
7582     2.6) --> vStopped
7583     2.7) <-- T05 thread:2
7584     2.8) --> vStopped
7585     2.9) --> OK
7586 */
7587
7588 void
7589 remote_target::remote_notif_get_pending_events (notif_client *nc)
7590 {
7591   struct remote_state *rs = get_remote_state ();
7592
7593   if (rs->notif_state->pending_event[nc->id] != NULL)
7594     {
7595       if (notif_debug)
7596         fprintf_unfiltered (gdb_stdlog,
7597                             "notif: process: '%s' ack pending event\n",
7598                             nc->name);
7599
7600       /* acknowledge */
7601       nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7602       rs->notif_state->pending_event[nc->id] = NULL;
7603
7604       while (1)
7605         {
7606           getpkt (&rs->buf, &rs->buf_size, 0);
7607           if (strcmp (rs->buf, "OK") == 0)
7608             break;
7609           else
7610             remote_notif_ack (this, nc, rs->buf);
7611         }
7612     }
7613   else
7614     {
7615       if (notif_debug)
7616         fprintf_unfiltered (gdb_stdlog,
7617                             "notif: process: '%s' no pending reply\n",
7618                             nc->name);
7619     }
7620 }
7621
7622 /* Wrapper around remote_target::remote_notif_get_pending_events to
7623    avoid having to export the whole remote_target class.  */
7624
7625 void
7626 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7627 {
7628   remote->remote_notif_get_pending_events (nc);
7629 }
7630
7631 /* Called when it is decided that STOP_REPLY holds the info of the
7632    event that is to be returned to the core.  This function always
7633    destroys STOP_REPLY.  */
7634
7635 ptid_t
7636 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7637                                    struct target_waitstatus *status)
7638 {
7639   ptid_t ptid;
7640
7641   *status = stop_reply->ws;
7642   ptid = stop_reply->ptid;
7643
7644   /* If no thread/process was reported by the stub, assume the current
7645      inferior.  */
7646   if (ptid_equal (ptid, null_ptid))
7647     ptid = inferior_ptid;
7648
7649   if (status->kind != TARGET_WAITKIND_EXITED
7650       && status->kind != TARGET_WAITKIND_SIGNALLED
7651       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7652     {
7653       /* Expedited registers.  */
7654       if (stop_reply->regcache)
7655         {
7656           struct regcache *regcache
7657             = get_thread_arch_regcache (ptid, stop_reply->arch);
7658           cached_reg_t *reg;
7659           int ix;
7660
7661           for (ix = 0;
7662                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7663                ix++)
7664           {
7665             regcache->raw_supply (reg->num, reg->data);
7666             xfree (reg->data);
7667           }
7668
7669           VEC_free (cached_reg_t, stop_reply->regcache);
7670         }
7671
7672       remote_notice_new_inferior (ptid, 0);
7673       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7674       remote_thr->core = stop_reply->core;
7675       remote_thr->stop_reason = stop_reply->stop_reason;
7676       remote_thr->watch_data_address = stop_reply->watch_data_address;
7677       remote_thr->vcont_resumed = 0;
7678     }
7679
7680   stop_reply_xfree (stop_reply);
7681   return ptid;
7682 }
7683
7684 /* The non-stop mode version of target_wait.  */
7685
7686 ptid_t
7687 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7688 {
7689   struct remote_state *rs = get_remote_state ();
7690   struct stop_reply *stop_reply;
7691   int ret;
7692   int is_notif = 0;
7693
7694   /* If in non-stop mode, get out of getpkt even if a
7695      notification is received.  */
7696
7697   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7698                               0 /* forever */, &is_notif);
7699   while (1)
7700     {
7701       if (ret != -1 && !is_notif)
7702         switch (rs->buf[0])
7703           {
7704           case 'E':             /* Error of some sort.  */
7705             /* We're out of sync with the target now.  Did it continue
7706                or not?  We can't tell which thread it was in non-stop,
7707                so just ignore this.  */
7708             warning (_("Remote failure reply: %s"), rs->buf);
7709             break;
7710           case 'O':             /* Console output.  */
7711             remote_console_output (rs->buf + 1);
7712             break;
7713           default:
7714             warning (_("Invalid remote reply: %s"), rs->buf);
7715             break;
7716           }
7717
7718       /* Acknowledge a pending stop reply that may have arrived in the
7719          mean time.  */
7720       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7721         remote_notif_get_pending_events (&notif_client_stop);
7722
7723       /* If indeed we noticed a stop reply, we're done.  */
7724       stop_reply = queued_stop_reply (ptid);
7725       if (stop_reply != NULL)
7726         return process_stop_reply (stop_reply, status);
7727
7728       /* Still no event.  If we're just polling for an event, then
7729          return to the event loop.  */
7730       if (options & TARGET_WNOHANG)
7731         {
7732           status->kind = TARGET_WAITKIND_IGNORE;
7733           return minus_one_ptid;
7734         }
7735
7736       /* Otherwise do a blocking wait.  */
7737       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7738                                   1 /* forever */, &is_notif);
7739     }
7740 }
7741
7742 /* Wait until the remote machine stops, then return, storing status in
7743    STATUS just as `wait' would.  */
7744
7745 ptid_t
7746 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7747 {
7748   struct remote_state *rs = get_remote_state ();
7749   ptid_t event_ptid = null_ptid;
7750   char *buf;
7751   struct stop_reply *stop_reply;
7752
7753  again:
7754
7755   status->kind = TARGET_WAITKIND_IGNORE;
7756   status->value.integer = 0;
7757
7758   stop_reply = queued_stop_reply (ptid);
7759   if (stop_reply != NULL)
7760     return process_stop_reply (stop_reply, status);
7761
7762   if (rs->cached_wait_status)
7763     /* Use the cached wait status, but only once.  */
7764     rs->cached_wait_status = 0;
7765   else
7766     {
7767       int ret;
7768       int is_notif;
7769       int forever = ((options & TARGET_WNOHANG) == 0
7770                      && rs->wait_forever_enabled_p);
7771
7772       if (!rs->waiting_for_stop_reply)
7773         {
7774           status->kind = TARGET_WAITKIND_NO_RESUMED;
7775           return minus_one_ptid;
7776         }
7777
7778       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7779          _never_ wait for ever -> test on target_is_async_p().
7780          However, before we do that we need to ensure that the caller
7781          knows how to take the target into/out of async mode.  */
7782       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7783                                   forever, &is_notif);
7784
7785       /* GDB gets a notification.  Return to core as this event is
7786          not interesting.  */
7787       if (ret != -1 && is_notif)
7788         return minus_one_ptid;
7789
7790       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7791         return minus_one_ptid;
7792     }
7793
7794   buf = rs->buf;
7795
7796   /* Assume that the target has acknowledged Ctrl-C unless we receive
7797      an 'F' or 'O' packet.  */
7798   if (buf[0] != 'F' && buf[0] != 'O')
7799     rs->ctrlc_pending_p = 0;
7800
7801   switch (buf[0])
7802     {
7803     case 'E':           /* Error of some sort.  */
7804       /* We're out of sync with the target now.  Did it continue or
7805          not?  Not is more likely, so report a stop.  */
7806       rs->waiting_for_stop_reply = 0;
7807
7808       warning (_("Remote failure reply: %s"), buf);
7809       status->kind = TARGET_WAITKIND_STOPPED;
7810       status->value.sig = GDB_SIGNAL_0;
7811       break;
7812     case 'F':           /* File-I/O request.  */
7813       /* GDB may access the inferior memory while handling the File-I/O
7814          request, but we don't want GDB accessing memory while waiting
7815          for a stop reply.  See the comments in putpkt_binary.  Set
7816          waiting_for_stop_reply to 0 temporarily.  */
7817       rs->waiting_for_stop_reply = 0;
7818       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7819       rs->ctrlc_pending_p = 0;
7820       /* GDB handled the File-I/O request, and the target is running
7821          again.  Keep waiting for events.  */
7822       rs->waiting_for_stop_reply = 1;
7823       break;
7824     case 'N': case 'T': case 'S': case 'X': case 'W':
7825       {
7826         struct stop_reply *stop_reply;
7827
7828         /* There is a stop reply to handle.  */
7829         rs->waiting_for_stop_reply = 0;
7830
7831         stop_reply
7832           = (struct stop_reply *) remote_notif_parse (this,
7833                                                       &notif_client_stop,
7834                                                       rs->buf);
7835
7836         event_ptid = process_stop_reply (stop_reply, status);
7837         break;
7838       }
7839     case 'O':           /* Console output.  */
7840       remote_console_output (buf + 1);
7841       break;
7842     case '\0':
7843       if (rs->last_sent_signal != GDB_SIGNAL_0)
7844         {
7845           /* Zero length reply means that we tried 'S' or 'C' and the
7846              remote system doesn't support it.  */
7847           target_terminal::ours_for_output ();
7848           printf_filtered
7849             ("Can't send signals to this remote system.  %s not sent.\n",
7850              gdb_signal_to_name (rs->last_sent_signal));
7851           rs->last_sent_signal = GDB_SIGNAL_0;
7852           target_terminal::inferior ();
7853
7854           strcpy (buf, rs->last_sent_step ? "s" : "c");
7855           putpkt (buf);
7856           break;
7857         }
7858       /* fallthrough */
7859     default:
7860       warning (_("Invalid remote reply: %s"), buf);
7861       break;
7862     }
7863
7864   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7865     return minus_one_ptid;
7866   else if (status->kind == TARGET_WAITKIND_IGNORE)
7867     {
7868       /* Nothing interesting happened.  If we're doing a non-blocking
7869          poll, we're done.  Otherwise, go back to waiting.  */
7870       if (options & TARGET_WNOHANG)
7871         return minus_one_ptid;
7872       else
7873         goto again;
7874     }
7875   else if (status->kind != TARGET_WAITKIND_EXITED
7876            && status->kind != TARGET_WAITKIND_SIGNALLED)
7877     {
7878       if (!ptid_equal (event_ptid, null_ptid))
7879         record_currthread (rs, event_ptid);
7880       else
7881         event_ptid = inferior_ptid;
7882     }
7883   else
7884     /* A process exit.  Invalidate our notion of current thread.  */
7885     record_currthread (rs, minus_one_ptid);
7886
7887   return event_ptid;
7888 }
7889
7890 /* Wait until the remote machine stops, then return, storing status in
7891    STATUS just as `wait' would.  */
7892
7893 ptid_t
7894 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7895 {
7896   ptid_t event_ptid;
7897
7898   if (target_is_non_stop_p ())
7899     event_ptid = wait_ns (ptid, status, options);
7900   else
7901     event_ptid = wait_as (ptid, status, options);
7902
7903   if (target_is_async_p ())
7904     {
7905       remote_state *rs = get_remote_state ();
7906
7907       /* If there are are events left in the queue tell the event loop
7908          to return here.  */
7909       if (!rs->stop_reply_queue.empty ())
7910         mark_async_event_handler (rs->remote_async_inferior_event_token);
7911     }
7912
7913   return event_ptid;
7914 }
7915
7916 /* Fetch a single register using a 'p' packet.  */
7917
7918 int
7919 remote_target::fetch_register_using_p (struct regcache *regcache,
7920                                        packet_reg *reg)
7921 {
7922   struct gdbarch *gdbarch = regcache->arch ();
7923   struct remote_state *rs = get_remote_state ();
7924   char *buf, *p;
7925   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7926   int i;
7927
7928   if (packet_support (PACKET_p) == PACKET_DISABLE)
7929     return 0;
7930
7931   if (reg->pnum == -1)
7932     return 0;
7933
7934   p = rs->buf;
7935   *p++ = 'p';
7936   p += hexnumstr (p, reg->pnum);
7937   *p++ = '\0';
7938   putpkt (rs->buf);
7939   getpkt (&rs->buf, &rs->buf_size, 0);
7940
7941   buf = rs->buf;
7942
7943   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7944     {
7945     case PACKET_OK:
7946       break;
7947     case PACKET_UNKNOWN:
7948       return 0;
7949     case PACKET_ERROR:
7950       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7951              gdbarch_register_name (regcache->arch (), 
7952                                     reg->regnum), 
7953              buf);
7954     }
7955
7956   /* If this register is unfetchable, tell the regcache.  */
7957   if (buf[0] == 'x')
7958     {
7959       regcache->raw_supply (reg->regnum, NULL);
7960       return 1;
7961     }
7962
7963   /* Otherwise, parse and supply the value.  */
7964   p = buf;
7965   i = 0;
7966   while (p[0] != 0)
7967     {
7968       if (p[1] == 0)
7969         error (_("fetch_register_using_p: early buf termination"));
7970
7971       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7972       p += 2;
7973     }
7974   regcache->raw_supply (reg->regnum, regp);
7975   return 1;
7976 }
7977
7978 /* Fetch the registers included in the target's 'g' packet.  */
7979
7980 int
7981 remote_target::send_g_packet ()
7982 {
7983   struct remote_state *rs = get_remote_state ();
7984   int buf_len;
7985
7986   xsnprintf (rs->buf, get_remote_packet_size (), "g");
7987   putpkt (rs->buf);
7988   getpkt (&rs->buf, &rs->buf_size, 0);
7989   if (packet_check_result (rs->buf) == PACKET_ERROR)
7990     error (_("Could not read registers; remote failure reply '%s'"),
7991            rs->buf);
7992
7993   /* We can get out of synch in various cases.  If the first character
7994      in the buffer is not a hex character, assume that has happened
7995      and try to fetch another packet to read.  */
7996   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7997          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7998          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7999          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
8000     {
8001       if (remote_debug)
8002         fprintf_unfiltered (gdb_stdlog,
8003                             "Bad register packet; fetching a new packet\n");
8004       getpkt (&rs->buf, &rs->buf_size, 0);
8005     }
8006
8007   buf_len = strlen (rs->buf);
8008
8009   /* Sanity check the received packet.  */
8010   if (buf_len % 2 != 0)
8011     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8012
8013   return buf_len / 2;
8014 }
8015
8016 void
8017 remote_target::process_g_packet (struct regcache *regcache)
8018 {
8019   struct gdbarch *gdbarch = regcache->arch ();
8020   struct remote_state *rs = get_remote_state ();
8021   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8022   int i, buf_len;
8023   char *p;
8024   char *regs;
8025
8026   buf_len = strlen (rs->buf);
8027
8028   /* Further sanity checks, with knowledge of the architecture.  */
8029   if (buf_len > 2 * rsa->sizeof_g_packet)
8030     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8031              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8032
8033   /* Save the size of the packet sent to us by the target.  It is used
8034      as a heuristic when determining the max size of packets that the
8035      target can safely receive.  */
8036   if (rsa->actual_register_packet_size == 0)
8037     rsa->actual_register_packet_size = buf_len;
8038
8039   /* If this is smaller than we guessed the 'g' packet would be,
8040      update our records.  A 'g' reply that doesn't include a register's
8041      value implies either that the register is not available, or that
8042      the 'p' packet must be used.  */
8043   if (buf_len < 2 * rsa->sizeof_g_packet)
8044     {
8045       long sizeof_g_packet = buf_len / 2;
8046
8047       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8048         {
8049           long offset = rsa->regs[i].offset;
8050           long reg_size = register_size (gdbarch, i);
8051
8052           if (rsa->regs[i].pnum == -1)
8053             continue;
8054
8055           if (offset >= sizeof_g_packet)
8056             rsa->regs[i].in_g_packet = 0;
8057           else if (offset + reg_size > sizeof_g_packet)
8058             error (_("Truncated register %d in remote 'g' packet"), i);
8059           else
8060             rsa->regs[i].in_g_packet = 1;
8061         }
8062
8063       /* Looks valid enough, we can assume this is the correct length
8064          for a 'g' packet.  It's important not to adjust
8065          rsa->sizeof_g_packet if we have truncated registers otherwise
8066          this "if" won't be run the next time the method is called
8067          with a packet of the same size and one of the internal errors
8068          below will trigger instead.  */
8069       rsa->sizeof_g_packet = sizeof_g_packet;
8070     }
8071
8072   regs = (char *) alloca (rsa->sizeof_g_packet);
8073
8074   /* Unimplemented registers read as all bits zero.  */
8075   memset (regs, 0, rsa->sizeof_g_packet);
8076
8077   /* Reply describes registers byte by byte, each byte encoded as two
8078      hex characters.  Suck them all up, then supply them to the
8079      register cacheing/storage mechanism.  */
8080
8081   p = rs->buf;
8082   for (i = 0; i < rsa->sizeof_g_packet; i++)
8083     {
8084       if (p[0] == 0 || p[1] == 0)
8085         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
8086         internal_error (__FILE__, __LINE__,
8087                         _("unexpected end of 'g' packet reply"));
8088
8089       if (p[0] == 'x' && p[1] == 'x')
8090         regs[i] = 0;            /* 'x' */
8091       else
8092         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8093       p += 2;
8094     }
8095
8096   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8097     {
8098       struct packet_reg *r = &rsa->regs[i];
8099       long reg_size = register_size (gdbarch, i);
8100
8101       if (r->in_g_packet)
8102         {
8103           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8104             /* This shouldn't happen - we adjusted in_g_packet above.  */
8105             internal_error (__FILE__, __LINE__,
8106                             _("unexpected end of 'g' packet reply"));
8107           else if (rs->buf[r->offset * 2] == 'x')
8108             {
8109               gdb_assert (r->offset * 2 < strlen (rs->buf));
8110               /* The register isn't available, mark it as such (at
8111                  the same time setting the value to zero).  */
8112               regcache->raw_supply (r->regnum, NULL);
8113             }
8114           else
8115             regcache->raw_supply (r->regnum, regs + r->offset);
8116         }
8117     }
8118 }
8119
8120 void
8121 remote_target::fetch_registers_using_g (struct regcache *regcache)
8122 {
8123   send_g_packet ();
8124   process_g_packet (regcache);
8125 }
8126
8127 /* Make the remote selected traceframe match GDB's selected
8128    traceframe.  */
8129
8130 void
8131 remote_target::set_remote_traceframe ()
8132 {
8133   int newnum;
8134   struct remote_state *rs = get_remote_state ();
8135
8136   if (rs->remote_traceframe_number == get_traceframe_number ())
8137     return;
8138
8139   /* Avoid recursion, remote_trace_find calls us again.  */
8140   rs->remote_traceframe_number = get_traceframe_number ();
8141
8142   newnum = target_trace_find (tfind_number,
8143                               get_traceframe_number (), 0, 0, NULL);
8144
8145   /* Should not happen.  If it does, all bets are off.  */
8146   if (newnum != get_traceframe_number ())
8147     warning (_("could not set remote traceframe"));
8148 }
8149
8150 void
8151 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8152 {
8153   struct gdbarch *gdbarch = regcache->arch ();
8154   struct remote_state *rs = get_remote_state ();
8155   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8156   int i;
8157
8158   set_remote_traceframe ();
8159   set_general_thread (regcache->ptid ());
8160
8161   if (regnum >= 0)
8162     {
8163       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8164
8165       gdb_assert (reg != NULL);
8166
8167       /* If this register might be in the 'g' packet, try that first -
8168          we are likely to read more than one register.  If this is the
8169          first 'g' packet, we might be overly optimistic about its
8170          contents, so fall back to 'p'.  */
8171       if (reg->in_g_packet)
8172         {
8173           fetch_registers_using_g (regcache);
8174           if (reg->in_g_packet)
8175             return;
8176         }
8177
8178       if (fetch_register_using_p (regcache, reg))
8179         return;
8180
8181       /* This register is not available.  */
8182       regcache->raw_supply (reg->regnum, NULL);
8183
8184       return;
8185     }
8186
8187   fetch_registers_using_g (regcache);
8188
8189   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8190     if (!rsa->regs[i].in_g_packet)
8191       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8192         {
8193           /* This register is not available.  */
8194           regcache->raw_supply (i, NULL);
8195         }
8196 }
8197
8198 /* Prepare to store registers.  Since we may send them all (using a
8199    'G' request), we have to read out the ones we don't want to change
8200    first.  */
8201
8202 void
8203 remote_target::prepare_to_store (struct regcache *regcache)
8204 {
8205   struct remote_state *rs = get_remote_state ();
8206   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8207   int i;
8208
8209   /* Make sure the entire registers array is valid.  */
8210   switch (packet_support (PACKET_P))
8211     {
8212     case PACKET_DISABLE:
8213     case PACKET_SUPPORT_UNKNOWN:
8214       /* Make sure all the necessary registers are cached.  */
8215       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8216         if (rsa->regs[i].in_g_packet)
8217           regcache->raw_update (rsa->regs[i].regnum);
8218       break;
8219     case PACKET_ENABLE:
8220       break;
8221     }
8222 }
8223
8224 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8225    packet was not recognized.  */
8226
8227 int
8228 remote_target::store_register_using_P (const struct regcache *regcache,
8229                                        packet_reg *reg)
8230 {
8231   struct gdbarch *gdbarch = regcache->arch ();
8232   struct remote_state *rs = get_remote_state ();
8233   /* Try storing a single register.  */
8234   char *buf = rs->buf;
8235   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8236   char *p;
8237
8238   if (packet_support (PACKET_P) == PACKET_DISABLE)
8239     return 0;
8240
8241   if (reg->pnum == -1)
8242     return 0;
8243
8244   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8245   p = buf + strlen (buf);
8246   regcache->raw_collect (reg->regnum, regp);
8247   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8248   putpkt (rs->buf);
8249   getpkt (&rs->buf, &rs->buf_size, 0);
8250
8251   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8252     {
8253     case PACKET_OK:
8254       return 1;
8255     case PACKET_ERROR:
8256       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8257              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8258     case PACKET_UNKNOWN:
8259       return 0;
8260     default:
8261       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8262     }
8263 }
8264
8265 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8266    contents of the register cache buffer.  FIXME: ignores errors.  */
8267
8268 void
8269 remote_target::store_registers_using_G (const struct regcache *regcache)
8270 {
8271   struct remote_state *rs = get_remote_state ();
8272   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8273   gdb_byte *regs;
8274   char *p;
8275
8276   /* Extract all the registers in the regcache copying them into a
8277      local buffer.  */
8278   {
8279     int i;
8280
8281     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8282     memset (regs, 0, rsa->sizeof_g_packet);
8283     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8284       {
8285         struct packet_reg *r = &rsa->regs[i];
8286
8287         if (r->in_g_packet)
8288           regcache->raw_collect (r->regnum, regs + r->offset);
8289       }
8290   }
8291
8292   /* Command describes registers byte by byte,
8293      each byte encoded as two hex characters.  */
8294   p = rs->buf;
8295   *p++ = 'G';
8296   bin2hex (regs, p, rsa->sizeof_g_packet);
8297   putpkt (rs->buf);
8298   getpkt (&rs->buf, &rs->buf_size, 0);
8299   if (packet_check_result (rs->buf) == PACKET_ERROR)
8300     error (_("Could not write registers; remote failure reply '%s'"), 
8301            rs->buf);
8302 }
8303
8304 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8305    of the register cache buffer.  FIXME: ignores errors.  */
8306
8307 void
8308 remote_target::store_registers (struct regcache *regcache, int regnum)
8309 {
8310   struct gdbarch *gdbarch = regcache->arch ();
8311   struct remote_state *rs = get_remote_state ();
8312   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8313   int i;
8314
8315   set_remote_traceframe ();
8316   set_general_thread (regcache->ptid ());
8317
8318   if (regnum >= 0)
8319     {
8320       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8321
8322       gdb_assert (reg != NULL);
8323
8324       /* Always prefer to store registers using the 'P' packet if
8325          possible; we often change only a small number of registers.
8326          Sometimes we change a larger number; we'd need help from a
8327          higher layer to know to use 'G'.  */
8328       if (store_register_using_P (regcache, reg))
8329         return;
8330
8331       /* For now, don't complain if we have no way to write the
8332          register.  GDB loses track of unavailable registers too
8333          easily.  Some day, this may be an error.  We don't have
8334          any way to read the register, either...  */
8335       if (!reg->in_g_packet)
8336         return;
8337
8338       store_registers_using_G (regcache);
8339       return;
8340     }
8341
8342   store_registers_using_G (regcache);
8343
8344   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8345     if (!rsa->regs[i].in_g_packet)
8346       if (!store_register_using_P (regcache, &rsa->regs[i]))
8347         /* See above for why we do not issue an error here.  */
8348         continue;
8349 }
8350 \f
8351
8352 /* Return the number of hex digits in num.  */
8353
8354 static int
8355 hexnumlen (ULONGEST num)
8356 {
8357   int i;
8358
8359   for (i = 0; num != 0; i++)
8360     num >>= 4;
8361
8362   return std::max (i, 1);
8363 }
8364
8365 /* Set BUF to the minimum number of hex digits representing NUM.  */
8366
8367 static int
8368 hexnumstr (char *buf, ULONGEST num)
8369 {
8370   int len = hexnumlen (num);
8371
8372   return hexnumnstr (buf, num, len);
8373 }
8374
8375
8376 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8377
8378 static int
8379 hexnumnstr (char *buf, ULONGEST num, int width)
8380 {
8381   int i;
8382
8383   buf[width] = '\0';
8384
8385   for (i = width - 1; i >= 0; i--)
8386     {
8387       buf[i] = "0123456789abcdef"[(num & 0xf)];
8388       num >>= 4;
8389     }
8390
8391   return width;
8392 }
8393
8394 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8395
8396 static CORE_ADDR
8397 remote_address_masked (CORE_ADDR addr)
8398 {
8399   unsigned int address_size = remote_address_size;
8400
8401   /* If "remoteaddresssize" was not set, default to target address size.  */
8402   if (!address_size)
8403     address_size = gdbarch_addr_bit (target_gdbarch ());
8404
8405   if (address_size > 0
8406       && address_size < (sizeof (ULONGEST) * 8))
8407     {
8408       /* Only create a mask when that mask can safely be constructed
8409          in a ULONGEST variable.  */
8410       ULONGEST mask = 1;
8411
8412       mask = (mask << address_size) - 1;
8413       addr &= mask;
8414     }
8415   return addr;
8416 }
8417
8418 /* Determine whether the remote target supports binary downloading.
8419    This is accomplished by sending a no-op memory write of zero length
8420    to the target at the specified address. It does not suffice to send
8421    the whole packet, since many stubs strip the eighth bit and
8422    subsequently compute a wrong checksum, which causes real havoc with
8423    remote_write_bytes.
8424
8425    NOTE: This can still lose if the serial line is not eight-bit
8426    clean.  In cases like this, the user should clear "remote
8427    X-packet".  */
8428
8429 void
8430 remote_target::check_binary_download (CORE_ADDR addr)
8431 {
8432   struct remote_state *rs = get_remote_state ();
8433
8434   switch (packet_support (PACKET_X))
8435     {
8436     case PACKET_DISABLE:
8437       break;
8438     case PACKET_ENABLE:
8439       break;
8440     case PACKET_SUPPORT_UNKNOWN:
8441       {
8442         char *p;
8443
8444         p = rs->buf;
8445         *p++ = 'X';
8446         p += hexnumstr (p, (ULONGEST) addr);
8447         *p++ = ',';
8448         p += hexnumstr (p, (ULONGEST) 0);
8449         *p++ = ':';
8450         *p = '\0';
8451
8452         putpkt_binary (rs->buf, (int) (p - rs->buf));
8453         getpkt (&rs->buf, &rs->buf_size, 0);
8454
8455         if (rs->buf[0] == '\0')
8456           {
8457             if (remote_debug)
8458               fprintf_unfiltered (gdb_stdlog,
8459                                   "binary downloading NOT "
8460                                   "supported by target\n");
8461             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8462           }
8463         else
8464           {
8465             if (remote_debug)
8466               fprintf_unfiltered (gdb_stdlog,
8467                                   "binary downloading supported by target\n");
8468             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8469           }
8470         break;
8471       }
8472     }
8473 }
8474
8475 /* Helper function to resize the payload in order to try to get a good
8476    alignment.  We try to write an amount of data such that the next write will
8477    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8478
8479 static int
8480 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8481 {
8482   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8483 }
8484
8485 /* Write memory data directly to the remote machine.
8486    This does not inform the data cache; the data cache uses this.
8487    HEADER is the starting part of the packet.
8488    MEMADDR is the address in the remote memory space.
8489    MYADDR is the address of the buffer in our space.
8490    LEN_UNITS is the number of addressable units to write.
8491    UNIT_SIZE is the length in bytes of an addressable unit.
8492    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8493    should send data as binary ('X'), or hex-encoded ('M').
8494
8495    The function creates packet of the form
8496        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8497
8498    where encoding of <DATA> is terminated by PACKET_FORMAT.
8499
8500    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8501    are omitted.
8502
8503    Return the transferred status, error or OK (an
8504    'enum target_xfer_status' value).  Save the number of addressable units
8505    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8506
8507    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8508    exchange between gdb and the stub could look like (?? in place of the
8509    checksum):
8510
8511    -> $m1000,4#??
8512    <- aaaabbbbccccdddd
8513
8514    -> $M1000,3:eeeeffffeeee#??
8515    <- OK
8516
8517    -> $m1000,4#??
8518    <- eeeeffffeeeedddd  */
8519
8520 target_xfer_status
8521 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8522                                        const gdb_byte *myaddr,
8523                                        ULONGEST len_units,
8524                                        int unit_size,
8525                                        ULONGEST *xfered_len_units,
8526                                        char packet_format, int use_length)
8527 {
8528   struct remote_state *rs = get_remote_state ();
8529   char *p;
8530   char *plen = NULL;
8531   int plenlen = 0;
8532   int todo_units;
8533   int units_written;
8534   int payload_capacity_bytes;
8535   int payload_length_bytes;
8536
8537   if (packet_format != 'X' && packet_format != 'M')
8538     internal_error (__FILE__, __LINE__,
8539                     _("remote_write_bytes_aux: bad packet format"));
8540
8541   if (len_units == 0)
8542     return TARGET_XFER_EOF;
8543
8544   payload_capacity_bytes = get_memory_write_packet_size ();
8545
8546   /* The packet buffer will be large enough for the payload;
8547      get_memory_packet_size ensures this.  */
8548   rs->buf[0] = '\0';
8549
8550   /* Compute the size of the actual payload by subtracting out the
8551      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8552
8553   payload_capacity_bytes -= strlen ("$,:#NN");
8554   if (!use_length)
8555     /* The comma won't be used.  */
8556     payload_capacity_bytes += 1;
8557   payload_capacity_bytes -= strlen (header);
8558   payload_capacity_bytes -= hexnumlen (memaddr);
8559
8560   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8561
8562   strcat (rs->buf, header);
8563   p = rs->buf + strlen (header);
8564
8565   /* Compute a best guess of the number of bytes actually transfered.  */
8566   if (packet_format == 'X')
8567     {
8568       /* Best guess at number of bytes that will fit.  */
8569       todo_units = std::min (len_units,
8570                              (ULONGEST) payload_capacity_bytes / unit_size);
8571       if (use_length)
8572         payload_capacity_bytes -= hexnumlen (todo_units);
8573       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8574     }
8575   else
8576     {
8577       /* Number of bytes that will fit.  */
8578       todo_units
8579         = std::min (len_units,
8580                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8581       if (use_length)
8582         payload_capacity_bytes -= hexnumlen (todo_units);
8583       todo_units = std::min (todo_units,
8584                              (payload_capacity_bytes / unit_size) / 2);
8585     }
8586
8587   if (todo_units <= 0)
8588     internal_error (__FILE__, __LINE__,
8589                     _("minimum packet size too small to write data"));
8590
8591   /* If we already need another packet, then try to align the end
8592      of this packet to a useful boundary.  */
8593   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8594     todo_units = align_for_efficient_write (todo_units, memaddr);
8595
8596   /* Append "<memaddr>".  */
8597   memaddr = remote_address_masked (memaddr);
8598   p += hexnumstr (p, (ULONGEST) memaddr);
8599
8600   if (use_length)
8601     {
8602       /* Append ",".  */
8603       *p++ = ',';
8604
8605       /* Append the length and retain its location and size.  It may need to be
8606          adjusted once the packet body has been created.  */
8607       plen = p;
8608       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8609       p += plenlen;
8610     }
8611
8612   /* Append ":".  */
8613   *p++ = ':';
8614   *p = '\0';
8615
8616   /* Append the packet body.  */
8617   if (packet_format == 'X')
8618     {
8619       /* Binary mode.  Send target system values byte by byte, in
8620          increasing byte addresses.  Only escape certain critical
8621          characters.  */
8622       payload_length_bytes =
8623           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8624                                 &units_written, payload_capacity_bytes);
8625
8626       /* If not all TODO units fit, then we'll need another packet.  Make
8627          a second try to keep the end of the packet aligned.  Don't do
8628          this if the packet is tiny.  */
8629       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8630         {
8631           int new_todo_units;
8632
8633           new_todo_units = align_for_efficient_write (units_written, memaddr);
8634
8635           if (new_todo_units != units_written)
8636             payload_length_bytes =
8637                 remote_escape_output (myaddr, new_todo_units, unit_size,
8638                                       (gdb_byte *) p, &units_written,
8639                                       payload_capacity_bytes);
8640         }
8641
8642       p += payload_length_bytes;
8643       if (use_length && units_written < todo_units)
8644         {
8645           /* Escape chars have filled up the buffer prematurely,
8646              and we have actually sent fewer units than planned.
8647              Fix-up the length field of the packet.  Use the same
8648              number of characters as before.  */
8649           plen += hexnumnstr (plen, (ULONGEST) units_written,
8650                               plenlen);
8651           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8652         }
8653     }
8654   else
8655     {
8656       /* Normal mode: Send target system values byte by byte, in
8657          increasing byte addresses.  Each byte is encoded as a two hex
8658          value.  */
8659       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8660       units_written = todo_units;
8661     }
8662
8663   putpkt_binary (rs->buf, (int) (p - rs->buf));
8664   getpkt (&rs->buf, &rs->buf_size, 0);
8665
8666   if (rs->buf[0] == 'E')
8667     return TARGET_XFER_E_IO;
8668
8669   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8670      send fewer units than we'd planned.  */
8671   *xfered_len_units = (ULONGEST) units_written;
8672   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8673 }
8674
8675 /* Write memory data directly to the remote machine.
8676    This does not inform the data cache; the data cache uses this.
8677    MEMADDR is the address in the remote memory space.
8678    MYADDR is the address of the buffer in our space.
8679    LEN is the number of bytes.
8680
8681    Return the transferred status, error or OK (an
8682    'enum target_xfer_status' value).  Save the number of bytes
8683    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8684
8685 target_xfer_status
8686 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8687                                    ULONGEST len, int unit_size,
8688                                    ULONGEST *xfered_len)
8689 {
8690   const char *packet_format = NULL;
8691
8692   /* Check whether the target supports binary download.  */
8693   check_binary_download (memaddr);
8694
8695   switch (packet_support (PACKET_X))
8696     {
8697     case PACKET_ENABLE:
8698       packet_format = "X";
8699       break;
8700     case PACKET_DISABLE:
8701       packet_format = "M";
8702       break;
8703     case PACKET_SUPPORT_UNKNOWN:
8704       internal_error (__FILE__, __LINE__,
8705                       _("remote_write_bytes: bad internal state"));
8706     default:
8707       internal_error (__FILE__, __LINE__, _("bad switch"));
8708     }
8709
8710   return remote_write_bytes_aux (packet_format,
8711                                  memaddr, myaddr, len, unit_size, xfered_len,
8712                                  packet_format[0], 1);
8713 }
8714
8715 /* Read memory data directly from the remote machine.
8716    This does not use the data cache; the data cache uses this.
8717    MEMADDR is the address in the remote memory space.
8718    MYADDR is the address of the buffer in our space.
8719    LEN_UNITS is the number of addressable memory units to read..
8720    UNIT_SIZE is the length in bytes of an addressable unit.
8721
8722    Return the transferred status, error or OK (an
8723    'enum target_xfer_status' value).  Save the number of bytes
8724    transferred in *XFERED_LEN_UNITS.
8725
8726    See the comment of remote_write_bytes_aux for an example of
8727    memory read/write exchange between gdb and the stub.  */
8728
8729 target_xfer_status
8730 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8731                                     ULONGEST len_units,
8732                                     int unit_size, ULONGEST *xfered_len_units)
8733 {
8734   struct remote_state *rs = get_remote_state ();
8735   int buf_size_bytes;           /* Max size of packet output buffer.  */
8736   char *p;
8737   int todo_units;
8738   int decoded_bytes;
8739
8740   buf_size_bytes = get_memory_read_packet_size ();
8741   /* The packet buffer will be large enough for the payload;
8742      get_memory_packet_size ensures this.  */
8743
8744   /* Number of units that will fit.  */
8745   todo_units = std::min (len_units,
8746                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8747
8748   /* Construct "m"<memaddr>","<len>".  */
8749   memaddr = remote_address_masked (memaddr);
8750   p = rs->buf;
8751   *p++ = 'm';
8752   p += hexnumstr (p, (ULONGEST) memaddr);
8753   *p++ = ',';
8754   p += hexnumstr (p, (ULONGEST) todo_units);
8755   *p = '\0';
8756   putpkt (rs->buf);
8757   getpkt (&rs->buf, &rs->buf_size, 0);
8758   if (rs->buf[0] == 'E'
8759       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8760       && rs->buf[3] == '\0')
8761     return TARGET_XFER_E_IO;
8762   /* Reply describes memory byte by byte, each byte encoded as two hex
8763      characters.  */
8764   p = rs->buf;
8765   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8766   /* Return what we have.  Let higher layers handle partial reads.  */
8767   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8768   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8769 }
8770
8771 /* Using the set of read-only target sections of remote, read live
8772    read-only memory.
8773
8774    For interface/parameters/return description see target.h,
8775    to_xfer_partial.  */
8776
8777 target_xfer_status
8778 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8779                                                   ULONGEST memaddr,
8780                                                   ULONGEST len,
8781                                                   int unit_size,
8782                                                   ULONGEST *xfered_len)
8783 {
8784   struct target_section *secp;
8785   struct target_section_table *table;
8786
8787   secp = target_section_by_addr (this, memaddr);
8788   if (secp != NULL
8789       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8790                                  secp->the_bfd_section)
8791           & SEC_READONLY))
8792     {
8793       struct target_section *p;
8794       ULONGEST memend = memaddr + len;
8795
8796       table = target_get_section_table (this);
8797
8798       for (p = table->sections; p < table->sections_end; p++)
8799         {
8800           if (memaddr >= p->addr)
8801             {
8802               if (memend <= p->endaddr)
8803                 {
8804                   /* Entire transfer is within this section.  */
8805                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8806                                               xfered_len);
8807                 }
8808               else if (memaddr >= p->endaddr)
8809                 {
8810                   /* This section ends before the transfer starts.  */
8811                   continue;
8812                 }
8813               else
8814                 {
8815                   /* This section overlaps the transfer.  Just do half.  */
8816                   len = p->endaddr - memaddr;
8817                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8818                                               xfered_len);
8819                 }
8820             }
8821         }
8822     }
8823
8824   return TARGET_XFER_EOF;
8825 }
8826
8827 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8828    first if the requested memory is unavailable in traceframe.
8829    Otherwise, fall back to remote_read_bytes_1.  */
8830
8831 target_xfer_status
8832 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8833                                   gdb_byte *myaddr, ULONGEST len, int unit_size,
8834                                   ULONGEST *xfered_len)
8835 {
8836   if (len == 0)
8837     return TARGET_XFER_EOF;
8838
8839   if (get_traceframe_number () != -1)
8840     {
8841       std::vector<mem_range> available;
8842
8843       /* If we fail to get the set of available memory, then the
8844          target does not support querying traceframe info, and so we
8845          attempt reading from the traceframe anyway (assuming the
8846          target implements the old QTro packet then).  */
8847       if (traceframe_available_memory (&available, memaddr, len))
8848         {
8849           if (available.empty () || available[0].start != memaddr)
8850             {
8851               enum target_xfer_status res;
8852
8853               /* Don't read into the traceframe's available
8854                  memory.  */
8855               if (!available.empty ())
8856                 {
8857                   LONGEST oldlen = len;
8858
8859                   len = available[0].start - memaddr;
8860                   gdb_assert (len <= oldlen);
8861                 }
8862
8863               /* This goes through the topmost target again.  */
8864               res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8865                                                        len, unit_size, xfered_len);
8866               if (res == TARGET_XFER_OK)
8867                 return TARGET_XFER_OK;
8868               else
8869                 {
8870                   /* No use trying further, we know some memory starting
8871                      at MEMADDR isn't available.  */
8872                   *xfered_len = len;
8873                   return (*xfered_len != 0) ?
8874                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8875                 }
8876             }
8877
8878           /* Don't try to read more than how much is available, in
8879              case the target implements the deprecated QTro packet to
8880              cater for older GDBs (the target's knowledge of read-only
8881              sections may be outdated by now).  */
8882           len = available[0].length;
8883         }
8884     }
8885
8886   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8887 }
8888
8889 \f
8890
8891 /* Sends a packet with content determined by the printf format string
8892    FORMAT and the remaining arguments, then gets the reply.  Returns
8893    whether the packet was a success, a failure, or unknown.  */
8894
8895 packet_result
8896 remote_target::remote_send_printf (const char *format, ...)
8897 {
8898   struct remote_state *rs = get_remote_state ();
8899   int max_size = get_remote_packet_size ();
8900   va_list ap;
8901
8902   va_start (ap, format);
8903
8904   rs->buf[0] = '\0';
8905   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8906     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8907
8908   if (putpkt (rs->buf) < 0)
8909     error (_("Communication problem with target."));
8910
8911   rs->buf[0] = '\0';
8912   getpkt (&rs->buf, &rs->buf_size, 0);
8913
8914   return packet_check_result (rs->buf);
8915 }
8916
8917 /* Flash writing can take quite some time.  We'll set
8918    effectively infinite timeout for flash operations.
8919    In future, we'll need to decide on a better approach.  */
8920 static const int remote_flash_timeout = 1000;
8921
8922 void
8923 remote_target::flash_erase (ULONGEST address, LONGEST length)
8924 {
8925   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8926   enum packet_result ret;
8927   scoped_restore restore_timeout
8928     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8929
8930   ret = remote_send_printf ("vFlashErase:%s,%s",
8931                             phex (address, addr_size),
8932                             phex (length, 4));
8933   switch (ret)
8934     {
8935     case PACKET_UNKNOWN:
8936       error (_("Remote target does not support flash erase"));
8937     case PACKET_ERROR:
8938       error (_("Error erasing flash with vFlashErase packet"));
8939     default:
8940       break;
8941     }
8942 }
8943
8944 target_xfer_status
8945 remote_target::remote_flash_write (ULONGEST address,
8946                                    ULONGEST length, ULONGEST *xfered_len,
8947                                    const gdb_byte *data)
8948 {
8949   scoped_restore restore_timeout
8950     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8951   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8952                                  xfered_len,'X', 0);
8953 }
8954
8955 void
8956 remote_target::flash_done ()
8957 {
8958   int ret;
8959
8960   scoped_restore restore_timeout
8961     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8962
8963   ret = remote_send_printf ("vFlashDone");
8964
8965   switch (ret)
8966     {
8967     case PACKET_UNKNOWN:
8968       error (_("Remote target does not support vFlashDone"));
8969     case PACKET_ERROR:
8970       error (_("Error finishing flash operation"));
8971     default:
8972       break;
8973     }
8974 }
8975
8976 void
8977 remote_target::files_info ()
8978 {
8979   puts_filtered ("Debugging a target over a serial line.\n");
8980 }
8981 \f
8982 /* Stuff for dealing with the packets which are part of this protocol.
8983    See comment at top of file for details.  */
8984
8985 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8986    error to higher layers.  Called when a serial error is detected.
8987    The exception message is STRING, followed by a colon and a blank,
8988    the system error message for errno at function entry and final dot
8989    for output compatibility with throw_perror_with_name.  */
8990
8991 static void
8992 unpush_and_perror (const char *string)
8993 {
8994   int saved_errno = errno;
8995
8996   remote_unpush_target ();
8997   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8998                safe_strerror (saved_errno));
8999 }
9000
9001 /* Read a single character from the remote end.  The current quit
9002    handler is overridden to avoid quitting in the middle of packet
9003    sequence, as that would break communication with the remote server.
9004    See remote_serial_quit_handler for more detail.  */
9005
9006 int
9007 remote_target::readchar (int timeout)
9008 {
9009   int ch;
9010   struct remote_state *rs = get_remote_state ();
9011
9012   {
9013     scoped_restore restore_quit_target
9014       = make_scoped_restore (&curr_quit_handler_target, this);
9015     scoped_restore restore_quit
9016       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9017
9018     rs->got_ctrlc_during_io = 0;
9019
9020     ch = serial_readchar (rs->remote_desc, timeout);
9021
9022     if (rs->got_ctrlc_during_io)
9023       set_quit_flag ();
9024   }
9025
9026   if (ch >= 0)
9027     return ch;
9028
9029   switch ((enum serial_rc) ch)
9030     {
9031     case SERIAL_EOF:
9032       remote_unpush_target ();
9033       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9034       /* no return */
9035     case SERIAL_ERROR:
9036       unpush_and_perror (_("Remote communication error.  "
9037                            "Target disconnected."));
9038       /* no return */
9039     case SERIAL_TIMEOUT:
9040       break;
9041     }
9042   return ch;
9043 }
9044
9045 /* Wrapper for serial_write that closes the target and throws if
9046    writing fails.  The current quit handler is overridden to avoid
9047    quitting in the middle of packet sequence, as that would break
9048    communication with the remote server.  See
9049    remote_serial_quit_handler for more detail.  */
9050
9051 void
9052 remote_target::remote_serial_write (const char *str, int len)
9053 {
9054   struct remote_state *rs = get_remote_state ();
9055
9056   scoped_restore restore_quit_target
9057     = make_scoped_restore (&curr_quit_handler_target, this);
9058   scoped_restore restore_quit
9059     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9060
9061   rs->got_ctrlc_during_io = 0;
9062
9063   if (serial_write (rs->remote_desc, str, len))
9064     {
9065       unpush_and_perror (_("Remote communication error.  "
9066                            "Target disconnected."));
9067     }
9068
9069   if (rs->got_ctrlc_during_io)
9070     set_quit_flag ();
9071 }
9072
9073 /* Return a string representing an escaped version of BUF, of len N.
9074    E.g. \n is converted to \\n, \t to \\t, etc.  */
9075
9076 static std::string
9077 escape_buffer (const char *buf, int n)
9078 {
9079   string_file stb;
9080
9081   stb.putstrn (buf, n, '\\');
9082   return std::move (stb.string ());
9083 }
9084
9085 /* Display a null-terminated packet on stdout, for debugging, using C
9086    string notation.  */
9087
9088 static void
9089 print_packet (const char *buf)
9090 {
9091   puts_filtered ("\"");
9092   fputstr_filtered (buf, '"', gdb_stdout);
9093   puts_filtered ("\"");
9094 }
9095
9096 int
9097 remote_target::putpkt (const char *buf)
9098 {
9099   return putpkt_binary (buf, strlen (buf));
9100 }
9101
9102 /* Wrapper around remote_target::putpkt to avoid exporting
9103    remote_target.  */
9104
9105 int
9106 putpkt (remote_target *remote, const char *buf)
9107 {
9108   return remote->putpkt (buf);
9109 }
9110
9111 /* Send a packet to the remote machine, with error checking.  The data
9112    of the packet is in BUF.  The string in BUF can be at most
9113    get_remote_packet_size () - 5 to account for the $, # and checksum,
9114    and for a possible /0 if we are debugging (remote_debug) and want
9115    to print the sent packet as a string.  */
9116
9117 int
9118 remote_target::putpkt_binary (const char *buf, int cnt)
9119 {
9120   struct remote_state *rs = get_remote_state ();
9121   int i;
9122   unsigned char csum = 0;
9123   gdb::def_vector<char> data (cnt + 6);
9124   char *buf2 = data.data ();
9125
9126   int ch;
9127   int tcount = 0;
9128   char *p;
9129
9130   /* Catch cases like trying to read memory or listing threads while
9131      we're waiting for a stop reply.  The remote server wouldn't be
9132      ready to handle this request, so we'd hang and timeout.  We don't
9133      have to worry about this in synchronous mode, because in that
9134      case it's not possible to issue a command while the target is
9135      running.  This is not a problem in non-stop mode, because in that
9136      case, the stub is always ready to process serial input.  */
9137   if (!target_is_non_stop_p ()
9138       && target_is_async_p ()
9139       && rs->waiting_for_stop_reply)
9140     {
9141       error (_("Cannot execute this command while the target is running.\n"
9142                "Use the \"interrupt\" command to stop the target\n"
9143                "and then try again."));
9144     }
9145
9146   /* We're sending out a new packet.  Make sure we don't look at a
9147      stale cached response.  */
9148   rs->cached_wait_status = 0;
9149
9150   /* Copy the packet into buffer BUF2, encapsulating it
9151      and giving it a checksum.  */
9152
9153   p = buf2;
9154   *p++ = '$';
9155
9156   for (i = 0; i < cnt; i++)
9157     {
9158       csum += buf[i];
9159       *p++ = buf[i];
9160     }
9161   *p++ = '#';
9162   *p++ = tohex ((csum >> 4) & 0xf);
9163   *p++ = tohex (csum & 0xf);
9164
9165   /* Send it over and over until we get a positive ack.  */
9166
9167   while (1)
9168     {
9169       int started_error_output = 0;
9170
9171       if (remote_debug)
9172         {
9173           *p = '\0';
9174
9175           int len = (int) (p - buf2);
9176
9177           std::string str
9178             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9179
9180           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9181
9182           if (len > REMOTE_DEBUG_MAX_CHAR)
9183             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9184                                 len - REMOTE_DEBUG_MAX_CHAR);
9185
9186           fprintf_unfiltered (gdb_stdlog, "...");
9187
9188           gdb_flush (gdb_stdlog);
9189         }
9190       remote_serial_write (buf2, p - buf2);
9191
9192       /* If this is a no acks version of the remote protocol, send the
9193          packet and move on.  */
9194       if (rs->noack_mode)
9195         break;
9196
9197       /* Read until either a timeout occurs (-2) or '+' is read.
9198          Handle any notification that arrives in the mean time.  */
9199       while (1)
9200         {
9201           ch = readchar (remote_timeout);
9202
9203           if (remote_debug)
9204             {
9205               switch (ch)
9206                 {
9207                 case '+':
9208                 case '-':
9209                 case SERIAL_TIMEOUT:
9210                 case '$':
9211                 case '%':
9212                   if (started_error_output)
9213                     {
9214                       putchar_unfiltered ('\n');
9215                       started_error_output = 0;
9216                     }
9217                 }
9218             }
9219
9220           switch (ch)
9221             {
9222             case '+':
9223               if (remote_debug)
9224                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9225               return 1;
9226             case '-':
9227               if (remote_debug)
9228                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9229               /* FALLTHROUGH */
9230             case SERIAL_TIMEOUT:
9231               tcount++;
9232               if (tcount > 3)
9233                 return 0;
9234               break;            /* Retransmit buffer.  */
9235             case '$':
9236               {
9237                 if (remote_debug)
9238                   fprintf_unfiltered (gdb_stdlog,
9239                                       "Packet instead of Ack, ignoring it\n");
9240                 /* It's probably an old response sent because an ACK
9241                    was lost.  Gobble up the packet and ack it so it
9242                    doesn't get retransmitted when we resend this
9243                    packet.  */
9244                 skip_frame ();
9245                 remote_serial_write ("+", 1);
9246                 continue;       /* Now, go look for +.  */
9247               }
9248
9249             case '%':
9250               {
9251                 int val;
9252
9253                 /* If we got a notification, handle it, and go back to looking
9254                    for an ack.  */
9255                 /* We've found the start of a notification.  Now
9256                    collect the data.  */
9257                 val = read_frame (&rs->buf, &rs->buf_size);
9258                 if (val >= 0)
9259                   {
9260                     if (remote_debug)
9261                       {
9262                         std::string str = escape_buffer (rs->buf, val);
9263
9264                         fprintf_unfiltered (gdb_stdlog,
9265                                             "  Notification received: %s\n",
9266                                             str.c_str ());
9267                       }
9268                     handle_notification (rs->notif_state, rs->buf);
9269                     /* We're in sync now, rewait for the ack.  */
9270                     tcount = 0;
9271                   }
9272                 else
9273                   {
9274                     if (remote_debug)
9275                       {
9276                         if (!started_error_output)
9277                           {
9278                             started_error_output = 1;
9279                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9280                           }
9281                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9282                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9283                       }
9284                   }
9285                 continue;
9286               }
9287               /* fall-through */
9288             default:
9289               if (remote_debug)
9290                 {
9291                   if (!started_error_output)
9292                     {
9293                       started_error_output = 1;
9294                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9295                     }
9296                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9297                 }
9298               continue;
9299             }
9300           break;                /* Here to retransmit.  */
9301         }
9302
9303 #if 0
9304       /* This is wrong.  If doing a long backtrace, the user should be
9305          able to get out next time we call QUIT, without anything as
9306          violent as interrupt_query.  If we want to provide a way out of
9307          here without getting to the next QUIT, it should be based on
9308          hitting ^C twice as in remote_wait.  */
9309       if (quit_flag)
9310         {
9311           quit_flag = 0;
9312           interrupt_query ();
9313         }
9314 #endif
9315     }
9316
9317   return 0;
9318 }
9319
9320 /* Come here after finding the start of a frame when we expected an
9321    ack.  Do our best to discard the rest of this packet.  */
9322
9323 void
9324 remote_target::skip_frame ()
9325 {
9326   int c;
9327
9328   while (1)
9329     {
9330       c = readchar (remote_timeout);
9331       switch (c)
9332         {
9333         case SERIAL_TIMEOUT:
9334           /* Nothing we can do.  */
9335           return;
9336         case '#':
9337           /* Discard the two bytes of checksum and stop.  */
9338           c = readchar (remote_timeout);
9339           if (c >= 0)
9340             c = readchar (remote_timeout);
9341
9342           return;
9343         case '*':               /* Run length encoding.  */
9344           /* Discard the repeat count.  */
9345           c = readchar (remote_timeout);
9346           if (c < 0)
9347             return;
9348           break;
9349         default:
9350           /* A regular character.  */
9351           break;
9352         }
9353     }
9354 }
9355
9356 /* Come here after finding the start of the frame.  Collect the rest
9357    into *BUF, verifying the checksum, length, and handling run-length
9358    compression.  NUL terminate the buffer.  If there is not enough room,
9359    expand *BUF using xrealloc.
9360
9361    Returns -1 on error, number of characters in buffer (ignoring the
9362    trailing NULL) on success. (could be extended to return one of the
9363    SERIAL status indications).  */
9364
9365 long
9366 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9367 {
9368   unsigned char csum;
9369   long bc;
9370   int c;
9371   char *buf = *buf_p;
9372   struct remote_state *rs = get_remote_state ();
9373
9374   csum = 0;
9375   bc = 0;
9376
9377   while (1)
9378     {
9379       c = readchar (remote_timeout);
9380       switch (c)
9381         {
9382         case SERIAL_TIMEOUT:
9383           if (remote_debug)
9384             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9385           return -1;
9386         case '$':
9387           if (remote_debug)
9388             fputs_filtered ("Saw new packet start in middle of old one\n",
9389                             gdb_stdlog);
9390           return -1;            /* Start a new packet, count retries.  */
9391         case '#':
9392           {
9393             unsigned char pktcsum;
9394             int check_0 = 0;
9395             int check_1 = 0;
9396
9397             buf[bc] = '\0';
9398
9399             check_0 = readchar (remote_timeout);
9400             if (check_0 >= 0)
9401               check_1 = readchar (remote_timeout);
9402
9403             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9404               {
9405                 if (remote_debug)
9406                   fputs_filtered ("Timeout in checksum, retrying\n",
9407                                   gdb_stdlog);
9408                 return -1;
9409               }
9410             else if (check_0 < 0 || check_1 < 0)
9411               {
9412                 if (remote_debug)
9413                   fputs_filtered ("Communication error in checksum\n",
9414                                   gdb_stdlog);
9415                 return -1;
9416               }
9417
9418             /* Don't recompute the checksum; with no ack packets we
9419                don't have any way to indicate a packet retransmission
9420                is necessary.  */
9421             if (rs->noack_mode)
9422               return bc;
9423
9424             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9425             if (csum == pktcsum)
9426               return bc;
9427
9428             if (remote_debug)
9429               {
9430                 std::string str = escape_buffer (buf, bc);
9431
9432                 fprintf_unfiltered (gdb_stdlog,
9433                                     "Bad checksum, sentsum=0x%x, "
9434                                     "csum=0x%x, buf=%s\n",
9435                                     pktcsum, csum, str.c_str ());
9436               }
9437             /* Number of characters in buffer ignoring trailing
9438                NULL.  */
9439             return -1;
9440           }
9441         case '*':               /* Run length encoding.  */
9442           {
9443             int repeat;
9444
9445             csum += c;
9446             c = readchar (remote_timeout);
9447             csum += c;
9448             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9449
9450             /* The character before ``*'' is repeated.  */
9451
9452             if (repeat > 0 && repeat <= 255 && bc > 0)
9453               {
9454                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9455                   {
9456                     /* Make some more room in the buffer.  */
9457                     *sizeof_buf += repeat;
9458                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9459                     buf = *buf_p;
9460                   }
9461
9462                 memset (&buf[bc], buf[bc - 1], repeat);
9463                 bc += repeat;
9464                 continue;
9465               }
9466
9467             buf[bc] = '\0';
9468             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9469             return -1;
9470           }
9471         default:
9472           if (bc >= *sizeof_buf - 1)
9473             {
9474               /* Make some more room in the buffer.  */
9475               *sizeof_buf *= 2;
9476               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9477               buf = *buf_p;
9478             }
9479
9480           buf[bc++] = c;
9481           csum += c;
9482           continue;
9483         }
9484     }
9485 }
9486
9487 /* Read a packet from the remote machine, with error checking, and
9488    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9489    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9490    rather than timing out; this is used (in synchronous mode) to wait
9491    for a target that is is executing user code to stop.  */
9492 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9493    don't have to change all the calls to getpkt to deal with the
9494    return value, because at the moment I don't know what the right
9495    thing to do it for those.  */
9496
9497 void
9498 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9499 {
9500   getpkt_sane (buf, sizeof_buf, forever);
9501 }
9502
9503
9504 /* Read a packet from the remote machine, with error checking, and
9505    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9506    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9507    rather than timing out; this is used (in synchronous mode) to wait
9508    for a target that is is executing user code to stop.  If FOREVER ==
9509    0, this function is allowed to time out gracefully and return an
9510    indication of this to the caller.  Otherwise return the number of
9511    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9512    enough reason to return to the caller.  *IS_NOTIF is an output
9513    boolean that indicates whether *BUF holds a notification or not
9514    (a regular packet).  */
9515
9516 int
9517 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9518                                        int forever, int expecting_notif,
9519                                        int *is_notif)
9520 {
9521   struct remote_state *rs = get_remote_state ();
9522   int c;
9523   int tries;
9524   int timeout;
9525   int val = -1;
9526
9527   /* We're reading a new response.  Make sure we don't look at a
9528      previously cached response.  */
9529   rs->cached_wait_status = 0;
9530
9531   strcpy (*buf, "timeout");
9532
9533   if (forever)
9534     timeout = watchdog > 0 ? watchdog : -1;
9535   else if (expecting_notif)
9536     timeout = 0; /* There should already be a char in the buffer.  If
9537                     not, bail out.  */
9538   else
9539     timeout = remote_timeout;
9540
9541 #define MAX_TRIES 3
9542
9543   /* Process any number of notifications, and then return when
9544      we get a packet.  */
9545   for (;;)
9546     {
9547       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9548          times.  */
9549       for (tries = 1; tries <= MAX_TRIES; tries++)
9550         {
9551           /* This can loop forever if the remote side sends us
9552              characters continuously, but if it pauses, we'll get
9553              SERIAL_TIMEOUT from readchar because of timeout.  Then
9554              we'll count that as a retry.
9555
9556              Note that even when forever is set, we will only wait
9557              forever prior to the start of a packet.  After that, we
9558              expect characters to arrive at a brisk pace.  They should
9559              show up within remote_timeout intervals.  */
9560           do
9561             c = readchar (timeout);
9562           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9563
9564           if (c == SERIAL_TIMEOUT)
9565             {
9566               if (expecting_notif)
9567                 return -1; /* Don't complain, it's normal to not get
9568                               anything in this case.  */
9569
9570               if (forever)      /* Watchdog went off?  Kill the target.  */
9571                 {
9572                   remote_unpush_target ();
9573                   throw_error (TARGET_CLOSE_ERROR,
9574                                _("Watchdog timeout has expired.  "
9575                                  "Target detached."));
9576                 }
9577               if (remote_debug)
9578                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9579             }
9580           else
9581             {
9582               /* We've found the start of a packet or notification.
9583                  Now collect the data.  */
9584               val = read_frame (buf, sizeof_buf);
9585               if (val >= 0)
9586                 break;
9587             }
9588
9589           remote_serial_write ("-", 1);
9590         }
9591
9592       if (tries > MAX_TRIES)
9593         {
9594           /* We have tried hard enough, and just can't receive the
9595              packet/notification.  Give up.  */
9596           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9597
9598           /* Skip the ack char if we're in no-ack mode.  */
9599           if (!rs->noack_mode)
9600             remote_serial_write ("+", 1);
9601           return -1;
9602         }
9603
9604       /* If we got an ordinary packet, return that to our caller.  */
9605       if (c == '$')
9606         {
9607           if (remote_debug)
9608             {
9609               std::string str
9610                 = escape_buffer (*buf,
9611                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9612
9613               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9614                                   str.c_str ());
9615
9616               if (val > REMOTE_DEBUG_MAX_CHAR)
9617                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9618                                     val - REMOTE_DEBUG_MAX_CHAR);
9619
9620               fprintf_unfiltered (gdb_stdlog, "\n");
9621             }
9622
9623           /* Skip the ack char if we're in no-ack mode.  */
9624           if (!rs->noack_mode)
9625             remote_serial_write ("+", 1);
9626           if (is_notif != NULL)
9627             *is_notif = 0;
9628           return val;
9629         }
9630
9631        /* If we got a notification, handle it, and go back to looking
9632          for a packet.  */
9633       else
9634         {
9635           gdb_assert (c == '%');
9636
9637           if (remote_debug)
9638             {
9639               std::string str = escape_buffer (*buf, val);
9640
9641               fprintf_unfiltered (gdb_stdlog,
9642                                   "  Notification received: %s\n",
9643                                   str.c_str ());
9644             }
9645           if (is_notif != NULL)
9646             *is_notif = 1;
9647
9648           handle_notification (rs->notif_state, *buf);
9649
9650           /* Notifications require no acknowledgement.  */
9651
9652           if (expecting_notif)
9653             return val;
9654         }
9655     }
9656 }
9657
9658 int
9659 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9660 {
9661   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9662 }
9663
9664 int
9665 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9666                                      int *is_notif)
9667 {
9668   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9669                                  is_notif);
9670 }
9671
9672 /* Kill any new fork children of process PID that haven't been
9673    processed by follow_fork.  */
9674
9675 void
9676 remote_target::kill_new_fork_children (int pid)
9677 {
9678   remote_state *rs = get_remote_state ();
9679   struct thread_info *thread;
9680   struct notif_client *notif = &notif_client_stop;
9681
9682   /* Kill the fork child threads of any threads in process PID
9683      that are stopped at a fork event.  */
9684   ALL_NON_EXITED_THREADS (thread)
9685     {
9686       struct target_waitstatus *ws = &thread->pending_follow;
9687
9688       if (is_pending_fork_parent (ws, pid, thread->ptid))
9689         {
9690           int child_pid = ws->value.related_pid.pid ();
9691           int res;
9692
9693           res = remote_vkill (child_pid);
9694           if (res != 0)
9695             error (_("Can't kill fork child process %d"), child_pid);
9696         }
9697     }
9698
9699   /* Check for any pending fork events (not reported or processed yet)
9700      in process PID and kill those fork child threads as well.  */
9701   remote_notif_get_pending_events (notif);
9702   for (auto &event : rs->stop_reply_queue)
9703     if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9704       {
9705         int child_pid = event->ws.value.related_pid.pid ();
9706         int res;
9707
9708         res = remote_vkill (child_pid);
9709         if (res != 0)
9710           error (_("Can't kill fork child process %d"), child_pid);
9711       }
9712 }
9713
9714 \f
9715 /* Target hook to kill the current inferior.  */
9716
9717 void
9718 remote_target::kill ()
9719 {
9720   int res = -1;
9721   int pid = inferior_ptid.pid ();
9722   struct remote_state *rs = get_remote_state ();
9723
9724   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9725     {
9726       /* If we're stopped while forking and we haven't followed yet,
9727          kill the child task.  We need to do this before killing the
9728          parent task because if this is a vfork then the parent will
9729          be sleeping.  */
9730       kill_new_fork_children (pid);
9731
9732       res = remote_vkill (pid);
9733       if (res == 0)
9734         {
9735           target_mourn_inferior (inferior_ptid);
9736           return;
9737         }
9738     }
9739
9740   /* If we are in 'target remote' mode and we are killing the only
9741      inferior, then we will tell gdbserver to exit and unpush the
9742      target.  */
9743   if (res == -1 && !remote_multi_process_p (rs)
9744       && number_of_live_inferiors () == 1)
9745     {
9746       remote_kill_k ();
9747
9748       /* We've killed the remote end, we get to mourn it.  If we are
9749          not in extended mode, mourning the inferior also unpushes
9750          remote_ops from the target stack, which closes the remote
9751          connection.  */
9752       target_mourn_inferior (inferior_ptid);
9753
9754       return;
9755     }
9756
9757   error (_("Can't kill process"));
9758 }
9759
9760 /* Send a kill request to the target using the 'vKill' packet.  */
9761
9762 int
9763 remote_target::remote_vkill (int pid)
9764 {
9765   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9766     return -1;
9767
9768   remote_state *rs = get_remote_state ();
9769
9770   /* Tell the remote target to detach.  */
9771   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9772   putpkt (rs->buf);
9773   getpkt (&rs->buf, &rs->buf_size, 0);
9774
9775   switch (packet_ok (rs->buf,
9776                      &remote_protocol_packets[PACKET_vKill]))
9777     {
9778     case PACKET_OK:
9779       return 0;
9780     case PACKET_ERROR:
9781       return 1;
9782     case PACKET_UNKNOWN:
9783       return -1;
9784     default:
9785       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9786     }
9787 }
9788
9789 /* Send a kill request to the target using the 'k' packet.  */
9790
9791 void
9792 remote_target::remote_kill_k ()
9793 {
9794   /* Catch errors so the user can quit from gdb even when we
9795      aren't on speaking terms with the remote system.  */
9796   TRY
9797     {
9798       putpkt ("k");
9799     }
9800   CATCH (ex, RETURN_MASK_ERROR)
9801     {
9802       if (ex.error == TARGET_CLOSE_ERROR)
9803         {
9804           /* If we got an (EOF) error that caused the target
9805              to go away, then we're done, that's what we wanted.
9806              "k" is susceptible to cause a premature EOF, given
9807              that the remote server isn't actually required to
9808              reply to "k", and it can happen that it doesn't
9809              even get to reply ACK to the "k".  */
9810           return;
9811         }
9812
9813       /* Otherwise, something went wrong.  We didn't actually kill
9814          the target.  Just propagate the exception, and let the
9815          user or higher layers decide what to do.  */
9816       throw_exception (ex);
9817     }
9818   END_CATCH
9819 }
9820
9821 void
9822 remote_target::mourn_inferior ()
9823 {
9824   struct remote_state *rs = get_remote_state ();
9825
9826   /* We're no longer interested in notification events of an inferior
9827      that exited or was killed/detached.  */
9828   discard_pending_stop_replies (current_inferior ());
9829
9830   /* In 'target remote' mode with one inferior, we close the connection.  */
9831   if (!rs->extended && number_of_live_inferiors () <= 1)
9832     {
9833       unpush_target (this);
9834
9835       /* remote_close takes care of doing most of the clean up.  */
9836       generic_mourn_inferior ();
9837       return;
9838     }
9839
9840   /* In case we got here due to an error, but we're going to stay
9841      connected.  */
9842   rs->waiting_for_stop_reply = 0;
9843
9844   /* If the current general thread belonged to the process we just
9845      detached from or has exited, the remote side current general
9846      thread becomes undefined.  Considering a case like this:
9847
9848      - We just got here due to a detach.
9849      - The process that we're detaching from happens to immediately
9850        report a global breakpoint being hit in non-stop mode, in the
9851        same thread we had selected before.
9852      - GDB attaches to this process again.
9853      - This event happens to be the next event we handle.
9854
9855      GDB would consider that the current general thread didn't need to
9856      be set on the stub side (with Hg), since for all it knew,
9857      GENERAL_THREAD hadn't changed.
9858
9859      Notice that although in all-stop mode, the remote server always
9860      sets the current thread to the thread reporting the stop event,
9861      that doesn't happen in non-stop mode; in non-stop, the stub *must
9862      not* change the current thread when reporting a breakpoint hit,
9863      due to the decoupling of event reporting and event handling.
9864
9865      To keep things simple, we always invalidate our notion of the
9866      current thread.  */
9867   record_currthread (rs, minus_one_ptid);
9868
9869   /* Call common code to mark the inferior as not running.  */
9870   generic_mourn_inferior ();
9871
9872   if (!have_inferiors ())
9873     {
9874       if (!remote_multi_process_p (rs))
9875         {
9876           /* Check whether the target is running now - some remote stubs
9877              automatically restart after kill.  */
9878           putpkt ("?");
9879           getpkt (&rs->buf, &rs->buf_size, 0);
9880
9881           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9882             {
9883               /* Assume that the target has been restarted.  Set
9884                  inferior_ptid so that bits of core GDB realizes
9885                  there's something here, e.g., so that the user can
9886                  say "kill" again.  */
9887               inferior_ptid = magic_null_ptid;
9888             }
9889         }
9890     }
9891 }
9892
9893 bool
9894 extended_remote_target::supports_disable_randomization ()
9895 {
9896   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9897 }
9898
9899 void
9900 remote_target::extended_remote_disable_randomization (int val)
9901 {
9902   struct remote_state *rs = get_remote_state ();
9903   char *reply;
9904
9905   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9906              val);
9907   putpkt (rs->buf);
9908   reply = remote_get_noisy_reply ();
9909   if (*reply == '\0')
9910     error (_("Target does not support QDisableRandomization."));
9911   if (strcmp (reply, "OK") != 0)
9912     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9913 }
9914
9915 int
9916 remote_target::extended_remote_run (const std::string &args)
9917 {
9918   struct remote_state *rs = get_remote_state ();
9919   int len;
9920   const char *remote_exec_file = get_remote_exec_file ();
9921
9922   /* If the user has disabled vRun support, or we have detected that
9923      support is not available, do not try it.  */
9924   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9925     return -1;
9926
9927   strcpy (rs->buf, "vRun;");
9928   len = strlen (rs->buf);
9929
9930   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9931     error (_("Remote file name too long for run packet"));
9932   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9933                       strlen (remote_exec_file));
9934
9935   if (!args.empty ())
9936     {
9937       int i;
9938
9939       gdb_argv argv (args.c_str ());
9940       for (i = 0; argv[i] != NULL; i++)
9941         {
9942           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9943             error (_("Argument list too long for run packet"));
9944           rs->buf[len++] = ';';
9945           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9946                               strlen (argv[i]));
9947         }
9948     }
9949
9950   rs->buf[len++] = '\0';
9951
9952   putpkt (rs->buf);
9953   getpkt (&rs->buf, &rs->buf_size, 0);
9954
9955   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9956     {
9957     case PACKET_OK:
9958       /* We have a wait response.  All is well.  */
9959       return 0;
9960     case PACKET_UNKNOWN:
9961       return -1;
9962     case PACKET_ERROR:
9963       if (remote_exec_file[0] == '\0')
9964         error (_("Running the default executable on the remote target failed; "
9965                  "try \"set remote exec-file\"?"));
9966       else
9967         error (_("Running \"%s\" on the remote target failed"),
9968                remote_exec_file);
9969     default:
9970       gdb_assert_not_reached (_("bad switch"));
9971     }
9972 }
9973
9974 /* Helper function to send set/unset environment packets.  ACTION is
9975    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
9976    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
9977    sent.  */
9978
9979 void
9980 remote_target::send_environment_packet (const char *action,
9981                                         const char *packet,
9982                                         const char *value)
9983 {
9984   remote_state *rs = get_remote_state ();
9985
9986   /* Convert the environment variable to an hex string, which
9987      is the best format to be transmitted over the wire.  */
9988   std::string encoded_value = bin2hex ((const gdb_byte *) value,
9989                                          strlen (value));
9990
9991   xsnprintf (rs->buf, get_remote_packet_size (),
9992              "%s:%s", packet, encoded_value.c_str ());
9993
9994   putpkt (rs->buf);
9995   getpkt (&rs->buf, &rs->buf_size, 0);
9996   if (strcmp (rs->buf, "OK") != 0)
9997     warning (_("Unable to %s environment variable '%s' on remote."),
9998              action, value);
9999 }
10000
10001 /* Helper function to handle the QEnvironment* packets.  */
10002
10003 void
10004 remote_target::extended_remote_environment_support ()
10005 {
10006   remote_state *rs = get_remote_state ();
10007
10008   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10009     {
10010       putpkt ("QEnvironmentReset");
10011       getpkt (&rs->buf, &rs->buf_size, 0);
10012       if (strcmp (rs->buf, "OK") != 0)
10013         warning (_("Unable to reset environment on remote."));
10014     }
10015
10016   gdb_environ *e = &current_inferior ()->environment;
10017
10018   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10019     for (const std::string &el : e->user_set_env ())
10020       send_environment_packet ("set", "QEnvironmentHexEncoded",
10021                                el.c_str ());
10022
10023   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10024     for (const std::string &el : e->user_unset_env ())
10025       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10026 }
10027
10028 /* Helper function to set the current working directory for the
10029    inferior in the remote target.  */
10030
10031 void
10032 remote_target::extended_remote_set_inferior_cwd ()
10033 {
10034   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10035     {
10036       const char *inferior_cwd = get_inferior_cwd ();
10037       remote_state *rs = get_remote_state ();
10038
10039       if (inferior_cwd != NULL)
10040         {
10041           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10042                                          strlen (inferior_cwd));
10043
10044           xsnprintf (rs->buf, get_remote_packet_size (),
10045                      "QSetWorkingDir:%s", hexpath.c_str ());
10046         }
10047       else
10048         {
10049           /* An empty inferior_cwd means that the user wants us to
10050              reset the remote server's inferior's cwd.  */
10051           xsnprintf (rs->buf, get_remote_packet_size (),
10052                      "QSetWorkingDir:");
10053         }
10054
10055       putpkt (rs->buf);
10056       getpkt (&rs->buf, &rs->buf_size, 0);
10057       if (packet_ok (rs->buf,
10058                      &remote_protocol_packets[PACKET_QSetWorkingDir])
10059           != PACKET_OK)
10060         error (_("\
10061 Remote replied unexpectedly while setting the inferior's working\n\
10062 directory: %s"),
10063                rs->buf);
10064
10065     }
10066 }
10067
10068 /* In the extended protocol we want to be able to do things like
10069    "run" and have them basically work as expected.  So we need
10070    a special create_inferior function.  We support changing the
10071    executable file and the command line arguments, but not the
10072    environment.  */
10073
10074 void
10075 extended_remote_target::create_inferior (const char *exec_file,
10076                                          const std::string &args,
10077                                          char **env, int from_tty)
10078 {
10079   int run_worked;
10080   char *stop_reply;
10081   struct remote_state *rs = get_remote_state ();
10082   const char *remote_exec_file = get_remote_exec_file ();
10083
10084   /* If running asynchronously, register the target file descriptor
10085      with the event loop.  */
10086   if (target_can_async_p ())
10087     target_async (1);
10088
10089   /* Disable address space randomization if requested (and supported).  */
10090   if (supports_disable_randomization ())
10091     extended_remote_disable_randomization (disable_randomization);
10092
10093   /* If startup-with-shell is on, we inform gdbserver to start the
10094      remote inferior using a shell.  */
10095   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10096     {
10097       xsnprintf (rs->buf, get_remote_packet_size (),
10098                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10099       putpkt (rs->buf);
10100       getpkt (&rs->buf, &rs->buf_size, 0);
10101       if (strcmp (rs->buf, "OK") != 0)
10102         error (_("\
10103 Remote replied unexpectedly while setting startup-with-shell: %s"),
10104                rs->buf);
10105     }
10106
10107   extended_remote_environment_support ();
10108
10109   extended_remote_set_inferior_cwd ();
10110
10111   /* Now restart the remote server.  */
10112   run_worked = extended_remote_run (args) != -1;
10113   if (!run_worked)
10114     {
10115       /* vRun was not supported.  Fail if we need it to do what the
10116          user requested.  */
10117       if (remote_exec_file[0])
10118         error (_("Remote target does not support \"set remote exec-file\""));
10119       if (!args.empty ())
10120         error (_("Remote target does not support \"set args\" or run <ARGS>"));
10121
10122       /* Fall back to "R".  */
10123       extended_remote_restart ();
10124     }
10125
10126   if (!have_inferiors ())
10127     {
10128       /* Clean up from the last time we ran, before we mark the target
10129          running again.  This will mark breakpoints uninserted, and
10130          get_offsets may insert breakpoints.  */
10131       init_thread_list ();
10132       init_wait_for_inferior ();
10133     }
10134
10135   /* vRun's success return is a stop reply.  */
10136   stop_reply = run_worked ? rs->buf : NULL;
10137   add_current_inferior_and_thread (stop_reply);
10138
10139   /* Get updated offsets, if the stub uses qOffsets.  */
10140   get_offsets ();
10141 }
10142 \f
10143
10144 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10145    the list of conditions (in agent expression bytecode format), if any, the
10146    target needs to evaluate.  The output is placed into the packet buffer
10147    started from BUF and ended at BUF_END.  */
10148
10149 static int
10150 remote_add_target_side_condition (struct gdbarch *gdbarch,
10151                                   struct bp_target_info *bp_tgt, char *buf,
10152                                   char *buf_end)
10153 {
10154   if (bp_tgt->conditions.empty ())
10155     return 0;
10156
10157   buf += strlen (buf);
10158   xsnprintf (buf, buf_end - buf, "%s", ";");
10159   buf++;
10160
10161   /* Send conditions to the target.  */
10162   for (agent_expr *aexpr : bp_tgt->conditions)
10163     {
10164       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10165       buf += strlen (buf);
10166       for (int i = 0; i < aexpr->len; ++i)
10167         buf = pack_hex_byte (buf, aexpr->buf[i]);
10168       *buf = '\0';
10169     }
10170   return 0;
10171 }
10172
10173 static void
10174 remote_add_target_side_commands (struct gdbarch *gdbarch,
10175                                  struct bp_target_info *bp_tgt, char *buf)
10176 {
10177   if (bp_tgt->tcommands.empty ())
10178     return;
10179
10180   buf += strlen (buf);
10181
10182   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10183   buf += strlen (buf);
10184
10185   /* Concatenate all the agent expressions that are commands into the
10186      cmds parameter.  */
10187   for (agent_expr *aexpr : bp_tgt->tcommands)
10188     {
10189       sprintf (buf, "X%x,", aexpr->len);
10190       buf += strlen (buf);
10191       for (int i = 0; i < aexpr->len; ++i)
10192         buf = pack_hex_byte (buf, aexpr->buf[i]);
10193       *buf = '\0';
10194     }
10195 }
10196
10197 /* Insert a breakpoint.  On targets that have software breakpoint
10198    support, we ask the remote target to do the work; on targets
10199    which don't, we insert a traditional memory breakpoint.  */
10200
10201 int
10202 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10203                                   struct bp_target_info *bp_tgt)
10204 {
10205   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10206      If it succeeds, then set the support to PACKET_ENABLE.  If it
10207      fails, and the user has explicitly requested the Z support then
10208      report an error, otherwise, mark it disabled and go on.  */
10209
10210   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10211     {
10212       CORE_ADDR addr = bp_tgt->reqstd_address;
10213       struct remote_state *rs;
10214       char *p, *endbuf;
10215
10216       /* Make sure the remote is pointing at the right process, if
10217          necessary.  */
10218       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10219         set_general_process ();
10220
10221       rs = get_remote_state ();
10222       p = rs->buf;
10223       endbuf = rs->buf + get_remote_packet_size ();
10224
10225       *(p++) = 'Z';
10226       *(p++) = '0';
10227       *(p++) = ',';
10228       addr = (ULONGEST) remote_address_masked (addr);
10229       p += hexnumstr (p, addr);
10230       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10231
10232       if (supports_evaluation_of_breakpoint_conditions ())
10233         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10234
10235       if (can_run_breakpoint_commands ())
10236         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10237
10238       putpkt (rs->buf);
10239       getpkt (&rs->buf, &rs->buf_size, 0);
10240
10241       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10242         {
10243         case PACKET_ERROR:
10244           return -1;
10245         case PACKET_OK:
10246           return 0;
10247         case PACKET_UNKNOWN:
10248           break;
10249         }
10250     }
10251
10252   /* If this breakpoint has target-side commands but this stub doesn't
10253      support Z0 packets, throw error.  */
10254   if (!bp_tgt->tcommands.empty ())
10255     throw_error (NOT_SUPPORTED_ERROR, _("\
10256 Target doesn't support breakpoints that have target side commands."));
10257
10258   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10259 }
10260
10261 int
10262 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10263                                   struct bp_target_info *bp_tgt,
10264                                   enum remove_bp_reason reason)
10265 {
10266   CORE_ADDR addr = bp_tgt->placed_address;
10267   struct remote_state *rs = get_remote_state ();
10268
10269   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10270     {
10271       char *p = rs->buf;
10272       char *endbuf = rs->buf + get_remote_packet_size ();
10273
10274       /* Make sure the remote is pointing at the right process, if
10275          necessary.  */
10276       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10277         set_general_process ();
10278
10279       *(p++) = 'z';
10280       *(p++) = '0';
10281       *(p++) = ',';
10282
10283       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10284       p += hexnumstr (p, addr);
10285       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10286
10287       putpkt (rs->buf);
10288       getpkt (&rs->buf, &rs->buf_size, 0);
10289
10290       return (rs->buf[0] == 'E');
10291     }
10292
10293   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10294 }
10295
10296 static enum Z_packet_type
10297 watchpoint_to_Z_packet (int type)
10298 {
10299   switch (type)
10300     {
10301     case hw_write:
10302       return Z_PACKET_WRITE_WP;
10303       break;
10304     case hw_read:
10305       return Z_PACKET_READ_WP;
10306       break;
10307     case hw_access:
10308       return Z_PACKET_ACCESS_WP;
10309       break;
10310     default:
10311       internal_error (__FILE__, __LINE__,
10312                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10313     }
10314 }
10315
10316 int
10317 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10318                                   enum target_hw_bp_type type, struct expression *cond)
10319 {
10320   struct remote_state *rs = get_remote_state ();
10321   char *endbuf = rs->buf + get_remote_packet_size ();
10322   char *p;
10323   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10324
10325   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10326     return 1;
10327
10328   /* Make sure the remote is pointing at the right process, if
10329      necessary.  */
10330   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10331     set_general_process ();
10332
10333   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10334   p = strchr (rs->buf, '\0');
10335   addr = remote_address_masked (addr);
10336   p += hexnumstr (p, (ULONGEST) addr);
10337   xsnprintf (p, endbuf - p, ",%x", len);
10338
10339   putpkt (rs->buf);
10340   getpkt (&rs->buf, &rs->buf_size, 0);
10341
10342   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10343     {
10344     case PACKET_ERROR:
10345       return -1;
10346     case PACKET_UNKNOWN:
10347       return 1;
10348     case PACKET_OK:
10349       return 0;
10350     }
10351   internal_error (__FILE__, __LINE__,
10352                   _("remote_insert_watchpoint: reached end of function"));
10353 }
10354
10355 bool
10356 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10357                                              CORE_ADDR start, int length)
10358 {
10359   CORE_ADDR diff = remote_address_masked (addr - start);
10360
10361   return diff < length;
10362 }
10363
10364
10365 int
10366 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10367                                   enum target_hw_bp_type type, struct expression *cond)
10368 {
10369   struct remote_state *rs = get_remote_state ();
10370   char *endbuf = rs->buf + get_remote_packet_size ();
10371   char *p;
10372   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10373
10374   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10375     return -1;
10376
10377   /* Make sure the remote is pointing at the right process, if
10378      necessary.  */
10379   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10380     set_general_process ();
10381
10382   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10383   p = strchr (rs->buf, '\0');
10384   addr = remote_address_masked (addr);
10385   p += hexnumstr (p, (ULONGEST) addr);
10386   xsnprintf (p, endbuf - p, ",%x", len);
10387   putpkt (rs->buf);
10388   getpkt (&rs->buf, &rs->buf_size, 0);
10389
10390   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10391     {
10392     case PACKET_ERROR:
10393     case PACKET_UNKNOWN:
10394       return -1;
10395     case PACKET_OK:
10396       return 0;
10397     }
10398   internal_error (__FILE__, __LINE__,
10399                   _("remote_remove_watchpoint: reached end of function"));
10400 }
10401
10402
10403 int remote_hw_watchpoint_limit = -1;
10404 int remote_hw_watchpoint_length_limit = -1;
10405 int remote_hw_breakpoint_limit = -1;
10406
10407 int
10408 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10409 {
10410   if (remote_hw_watchpoint_length_limit == 0)
10411     return 0;
10412   else if (remote_hw_watchpoint_length_limit < 0)
10413     return 1;
10414   else if (len <= remote_hw_watchpoint_length_limit)
10415     return 1;
10416   else
10417     return 0;
10418 }
10419
10420 int
10421 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10422 {
10423   if (type == bp_hardware_breakpoint)
10424     {
10425       if (remote_hw_breakpoint_limit == 0)
10426         return 0;
10427       else if (remote_hw_breakpoint_limit < 0)
10428         return 1;
10429       else if (cnt <= remote_hw_breakpoint_limit)
10430         return 1;
10431     }
10432   else
10433     {
10434       if (remote_hw_watchpoint_limit == 0)
10435         return 0;
10436       else if (remote_hw_watchpoint_limit < 0)
10437         return 1;
10438       else if (ot)
10439         return -1;
10440       else if (cnt <= remote_hw_watchpoint_limit)
10441         return 1;
10442     }
10443   return -1;
10444 }
10445
10446 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10447
10448 bool
10449 remote_target::stopped_by_sw_breakpoint ()
10450 {
10451   struct thread_info *thread = inferior_thread ();
10452
10453   return (thread->priv != NULL
10454           && (get_remote_thread_info (thread)->stop_reason
10455               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10456 }
10457
10458 /* The to_supports_stopped_by_sw_breakpoint method of target
10459    remote.  */
10460
10461 bool
10462 remote_target::supports_stopped_by_sw_breakpoint ()
10463 {
10464   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10465 }
10466
10467 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10468
10469 bool
10470 remote_target::stopped_by_hw_breakpoint ()
10471 {
10472   struct thread_info *thread = inferior_thread ();
10473
10474   return (thread->priv != NULL
10475           && (get_remote_thread_info (thread)->stop_reason
10476               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10477 }
10478
10479 /* The to_supports_stopped_by_hw_breakpoint method of target
10480    remote.  */
10481
10482 bool
10483 remote_target::supports_stopped_by_hw_breakpoint ()
10484 {
10485   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10486 }
10487
10488 bool
10489 remote_target::stopped_by_watchpoint ()
10490 {
10491   struct thread_info *thread = inferior_thread ();
10492
10493   return (thread->priv != NULL
10494           && (get_remote_thread_info (thread)->stop_reason
10495               == TARGET_STOPPED_BY_WATCHPOINT));
10496 }
10497
10498 bool
10499 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10500 {
10501   struct thread_info *thread = inferior_thread ();
10502
10503   if (thread->priv != NULL
10504       && (get_remote_thread_info (thread)->stop_reason
10505           == TARGET_STOPPED_BY_WATCHPOINT))
10506     {
10507       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10508       return true;
10509     }
10510
10511   return false;
10512 }
10513
10514
10515 int
10516 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10517                                      struct bp_target_info *bp_tgt)
10518 {
10519   CORE_ADDR addr = bp_tgt->reqstd_address;
10520   struct remote_state *rs;
10521   char *p, *endbuf;
10522   char *message;
10523
10524   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10525     return -1;
10526
10527   /* Make sure the remote is pointing at the right process, if
10528      necessary.  */
10529   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10530     set_general_process ();
10531
10532   rs = get_remote_state ();
10533   p = rs->buf;
10534   endbuf = rs->buf + get_remote_packet_size ();
10535
10536   *(p++) = 'Z';
10537   *(p++) = '1';
10538   *(p++) = ',';
10539
10540   addr = remote_address_masked (addr);
10541   p += hexnumstr (p, (ULONGEST) addr);
10542   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10543
10544   if (supports_evaluation_of_breakpoint_conditions ())
10545     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10546
10547   if (can_run_breakpoint_commands ())
10548     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10549
10550   putpkt (rs->buf);
10551   getpkt (&rs->buf, &rs->buf_size, 0);
10552
10553   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10554     {
10555     case PACKET_ERROR:
10556       if (rs->buf[1] == '.')
10557         {
10558           message = strchr (rs->buf + 2, '.');
10559           if (message)
10560             error (_("Remote failure reply: %s"), message + 1);
10561         }
10562       return -1;
10563     case PACKET_UNKNOWN:
10564       return -1;
10565     case PACKET_OK:
10566       return 0;
10567     }
10568   internal_error (__FILE__, __LINE__,
10569                   _("remote_insert_hw_breakpoint: reached end of function"));
10570 }
10571
10572
10573 int
10574 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10575                                      struct bp_target_info *bp_tgt)
10576 {
10577   CORE_ADDR addr;
10578   struct remote_state *rs = get_remote_state ();
10579   char *p = rs->buf;
10580   char *endbuf = rs->buf + get_remote_packet_size ();
10581
10582   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10583     return -1;
10584
10585   /* Make sure the remote is pointing at the right process, if
10586      necessary.  */
10587   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10588     set_general_process ();
10589
10590   *(p++) = 'z';
10591   *(p++) = '1';
10592   *(p++) = ',';
10593
10594   addr = remote_address_masked (bp_tgt->placed_address);
10595   p += hexnumstr (p, (ULONGEST) addr);
10596   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10597
10598   putpkt (rs->buf);
10599   getpkt (&rs->buf, &rs->buf_size, 0);
10600
10601   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10602     {
10603     case PACKET_ERROR:
10604     case PACKET_UNKNOWN:
10605       return -1;
10606     case PACKET_OK:
10607       return 0;
10608     }
10609   internal_error (__FILE__, __LINE__,
10610                   _("remote_remove_hw_breakpoint: reached end of function"));
10611 }
10612
10613 /* Verify memory using the "qCRC:" request.  */
10614
10615 int
10616 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10617 {
10618   struct remote_state *rs = get_remote_state ();
10619   unsigned long host_crc, target_crc;
10620   char *tmp;
10621
10622   /* It doesn't make sense to use qCRC if the remote target is
10623      connected but not running.  */
10624   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10625     {
10626       enum packet_result result;
10627
10628       /* Make sure the remote is pointing at the right process.  */
10629       set_general_process ();
10630
10631       /* FIXME: assumes lma can fit into long.  */
10632       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10633                  (long) lma, (long) size);
10634       putpkt (rs->buf);
10635
10636       /* Be clever; compute the host_crc before waiting for target
10637          reply.  */
10638       host_crc = xcrc32 (data, size, 0xffffffff);
10639
10640       getpkt (&rs->buf, &rs->buf_size, 0);
10641
10642       result = packet_ok (rs->buf,
10643                           &remote_protocol_packets[PACKET_qCRC]);
10644       if (result == PACKET_ERROR)
10645         return -1;
10646       else if (result == PACKET_OK)
10647         {
10648           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10649             target_crc = target_crc * 16 + fromhex (*tmp);
10650
10651           return (host_crc == target_crc);
10652         }
10653     }
10654
10655   return simple_verify_memory (this, data, lma, size);
10656 }
10657
10658 /* compare-sections command
10659
10660    With no arguments, compares each loadable section in the exec bfd
10661    with the same memory range on the target, and reports mismatches.
10662    Useful for verifying the image on the target against the exec file.  */
10663
10664 static void
10665 compare_sections_command (const char *args, int from_tty)
10666 {
10667   asection *s;
10668   const char *sectname;
10669   bfd_size_type size;
10670   bfd_vma lma;
10671   int matched = 0;
10672   int mismatched = 0;
10673   int res;
10674   int read_only = 0;
10675
10676   if (!exec_bfd)
10677     error (_("command cannot be used without an exec file"));
10678
10679   if (args != NULL && strcmp (args, "-r") == 0)
10680     {
10681       read_only = 1;
10682       args = NULL;
10683     }
10684
10685   for (s = exec_bfd->sections; s; s = s->next)
10686     {
10687       if (!(s->flags & SEC_LOAD))
10688         continue;               /* Skip non-loadable section.  */
10689
10690       if (read_only && (s->flags & SEC_READONLY) == 0)
10691         continue;               /* Skip writeable sections */
10692
10693       size = bfd_get_section_size (s);
10694       if (size == 0)
10695         continue;               /* Skip zero-length section.  */
10696
10697       sectname = bfd_get_section_name (exec_bfd, s);
10698       if (args && strcmp (args, sectname) != 0)
10699         continue;               /* Not the section selected by user.  */
10700
10701       matched = 1;              /* Do this section.  */
10702       lma = s->lma;
10703
10704       gdb::byte_vector sectdata (size);
10705       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10706
10707       res = target_verify_memory (sectdata.data (), lma, size);
10708
10709       if (res == -1)
10710         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10711                paddress (target_gdbarch (), lma),
10712                paddress (target_gdbarch (), lma + size));
10713
10714       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10715                        paddress (target_gdbarch (), lma),
10716                        paddress (target_gdbarch (), lma + size));
10717       if (res)
10718         printf_filtered ("matched.\n");
10719       else
10720         {
10721           printf_filtered ("MIS-MATCHED!\n");
10722           mismatched++;
10723         }
10724     }
10725   if (mismatched > 0)
10726     warning (_("One or more sections of the target image does not match\n\
10727 the loaded file\n"));
10728   if (args && !matched)
10729     printf_filtered (_("No loaded section named '%s'.\n"), args);
10730 }
10731
10732 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10733    into remote target.  The number of bytes written to the remote
10734    target is returned, or -1 for error.  */
10735
10736 target_xfer_status
10737 remote_target::remote_write_qxfer (const char *object_name,
10738                                    const char *annex, const gdb_byte *writebuf,
10739                                    ULONGEST offset, LONGEST len,
10740                                    ULONGEST *xfered_len,
10741                                    struct packet_config *packet)
10742 {
10743   int i, buf_len;
10744   ULONGEST n;
10745   struct remote_state *rs = get_remote_state ();
10746   int max_size = get_memory_write_packet_size (); 
10747
10748   if (packet_config_support (packet) == PACKET_DISABLE)
10749     return TARGET_XFER_E_IO;
10750
10751   /* Insert header.  */
10752   i = snprintf (rs->buf, max_size, 
10753                 "qXfer:%s:write:%s:%s:",
10754                 object_name, annex ? annex : "",
10755                 phex_nz (offset, sizeof offset));
10756   max_size -= (i + 1);
10757
10758   /* Escape as much data as fits into rs->buf.  */
10759   buf_len = remote_escape_output 
10760     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10761
10762   if (putpkt_binary (rs->buf, i + buf_len) < 0
10763       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10764       || packet_ok (rs->buf, packet) != PACKET_OK)
10765     return TARGET_XFER_E_IO;
10766
10767   unpack_varlen_hex (rs->buf, &n);
10768
10769   *xfered_len = n;
10770   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10771 }
10772
10773 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10774    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10775    number of bytes read is returned, or 0 for EOF, or -1 for error.
10776    The number of bytes read may be less than LEN without indicating an
10777    EOF.  PACKET is checked and updated to indicate whether the remote
10778    target supports this object.  */
10779
10780 target_xfer_status
10781 remote_target::remote_read_qxfer (const char *object_name,
10782                                   const char *annex,
10783                                   gdb_byte *readbuf, ULONGEST offset,
10784                                   LONGEST len,
10785                                   ULONGEST *xfered_len,
10786                                   struct packet_config *packet)
10787 {
10788   struct remote_state *rs = get_remote_state ();
10789   LONGEST i, n, packet_len;
10790
10791   if (packet_config_support (packet) == PACKET_DISABLE)
10792     return TARGET_XFER_E_IO;
10793
10794   /* Check whether we've cached an end-of-object packet that matches
10795      this request.  */
10796   if (rs->finished_object)
10797     {
10798       if (strcmp (object_name, rs->finished_object) == 0
10799           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10800           && offset == rs->finished_offset)
10801         return TARGET_XFER_EOF;
10802
10803
10804       /* Otherwise, we're now reading something different.  Discard
10805          the cache.  */
10806       xfree (rs->finished_object);
10807       xfree (rs->finished_annex);
10808       rs->finished_object = NULL;
10809       rs->finished_annex = NULL;
10810     }
10811
10812   /* Request only enough to fit in a single packet.  The actual data
10813      may not, since we don't know how much of it will need to be escaped;
10814      the target is free to respond with slightly less data.  We subtract
10815      five to account for the response type and the protocol frame.  */
10816   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10817   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10818             object_name, annex ? annex : "",
10819             phex_nz (offset, sizeof offset),
10820             phex_nz (n, sizeof n));
10821   i = putpkt (rs->buf);
10822   if (i < 0)
10823     return TARGET_XFER_E_IO;
10824
10825   rs->buf[0] = '\0';
10826   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10827   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10828     return TARGET_XFER_E_IO;
10829
10830   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10831     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10832
10833   /* 'm' means there is (or at least might be) more data after this
10834      batch.  That does not make sense unless there's at least one byte
10835      of data in this reply.  */
10836   if (rs->buf[0] == 'm' && packet_len == 1)
10837     error (_("Remote qXfer reply contained no data."));
10838
10839   /* Got some data.  */
10840   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10841                              packet_len - 1, readbuf, n);
10842
10843   /* 'l' is an EOF marker, possibly including a final block of data,
10844      or possibly empty.  If we have the final block of a non-empty
10845      object, record this fact to bypass a subsequent partial read.  */
10846   if (rs->buf[0] == 'l' && offset + i > 0)
10847     {
10848       rs->finished_object = xstrdup (object_name);
10849       rs->finished_annex = xstrdup (annex ? annex : "");
10850       rs->finished_offset = offset + i;
10851     }
10852
10853   if (i == 0)
10854     return TARGET_XFER_EOF;
10855   else
10856     {
10857       *xfered_len = i;
10858       return TARGET_XFER_OK;
10859     }
10860 }
10861
10862 enum target_xfer_status
10863 remote_target::xfer_partial (enum target_object object,
10864                              const char *annex, gdb_byte *readbuf,
10865                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10866                              ULONGEST *xfered_len)
10867 {
10868   struct remote_state *rs;
10869   int i;
10870   char *p2;
10871   char query_type;
10872   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10873
10874   set_remote_traceframe ();
10875   set_general_thread (inferior_ptid);
10876
10877   rs = get_remote_state ();
10878
10879   /* Handle memory using the standard memory routines.  */
10880   if (object == TARGET_OBJECT_MEMORY)
10881     {
10882       /* If the remote target is connected but not running, we should
10883          pass this request down to a lower stratum (e.g. the executable
10884          file).  */
10885       if (!target_has_execution)
10886         return TARGET_XFER_EOF;
10887
10888       if (writebuf != NULL)
10889         return remote_write_bytes (offset, writebuf, len, unit_size,
10890                                    xfered_len);
10891       else
10892         return remote_read_bytes (offset, readbuf, len, unit_size,
10893                                   xfered_len);
10894     }
10895
10896   /* Handle SPU memory using qxfer packets.  */
10897   if (object == TARGET_OBJECT_SPU)
10898     {
10899       if (readbuf)
10900         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10901                                   xfered_len, &remote_protocol_packets
10902                                   [PACKET_qXfer_spu_read]);
10903       else
10904         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10905                                    xfered_len, &remote_protocol_packets
10906                                    [PACKET_qXfer_spu_write]);
10907     }
10908
10909   /* Handle extra signal info using qxfer packets.  */
10910   if (object == TARGET_OBJECT_SIGNAL_INFO)
10911     {
10912       if (readbuf)
10913         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10914                                   xfered_len, &remote_protocol_packets
10915                                   [PACKET_qXfer_siginfo_read]);
10916       else
10917         return remote_write_qxfer ("siginfo", annex,
10918                                    writebuf, offset, len, xfered_len,
10919                                    &remote_protocol_packets
10920                                    [PACKET_qXfer_siginfo_write]);
10921     }
10922
10923   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10924     {
10925       if (readbuf)
10926         return remote_read_qxfer ("statictrace", annex,
10927                                   readbuf, offset, len, xfered_len,
10928                                   &remote_protocol_packets
10929                                   [PACKET_qXfer_statictrace_read]);
10930       else
10931         return TARGET_XFER_E_IO;
10932     }
10933
10934   /* Only handle flash writes.  */
10935   if (writebuf != NULL)
10936     {
10937       switch (object)
10938         {
10939         case TARGET_OBJECT_FLASH:
10940           return remote_flash_write (offset, len, xfered_len,
10941                                      writebuf);
10942
10943         default:
10944           return TARGET_XFER_E_IO;
10945         }
10946     }
10947
10948   /* Map pre-existing objects onto letters.  DO NOT do this for new
10949      objects!!!  Instead specify new query packets.  */
10950   switch (object)
10951     {
10952     case TARGET_OBJECT_AVR:
10953       query_type = 'R';
10954       break;
10955
10956     case TARGET_OBJECT_AUXV:
10957       gdb_assert (annex == NULL);
10958       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10959                                 xfered_len,
10960                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10961
10962     case TARGET_OBJECT_AVAILABLE_FEATURES:
10963       return remote_read_qxfer
10964         ("features", annex, readbuf, offset, len, xfered_len,
10965          &remote_protocol_packets[PACKET_qXfer_features]);
10966
10967     case TARGET_OBJECT_LIBRARIES:
10968       return remote_read_qxfer
10969         ("libraries", annex, readbuf, offset, len, xfered_len,
10970          &remote_protocol_packets[PACKET_qXfer_libraries]);
10971
10972     case TARGET_OBJECT_LIBRARIES_SVR4:
10973       return remote_read_qxfer
10974         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10975          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10976
10977     case TARGET_OBJECT_MEMORY_MAP:
10978       gdb_assert (annex == NULL);
10979       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10980                                  xfered_len,
10981                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10982
10983     case TARGET_OBJECT_OSDATA:
10984       /* Should only get here if we're connected.  */
10985       gdb_assert (rs->remote_desc);
10986       return remote_read_qxfer
10987         ("osdata", annex, readbuf, offset, len, xfered_len,
10988         &remote_protocol_packets[PACKET_qXfer_osdata]);
10989
10990     case TARGET_OBJECT_THREADS:
10991       gdb_assert (annex == NULL);
10992       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10993                                 xfered_len,
10994                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10995
10996     case TARGET_OBJECT_TRACEFRAME_INFO:
10997       gdb_assert (annex == NULL);
10998       return remote_read_qxfer
10999         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11000          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11001
11002     case TARGET_OBJECT_FDPIC:
11003       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11004                                 xfered_len,
11005                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11006
11007     case TARGET_OBJECT_OPENVMS_UIB:
11008       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11009                                 xfered_len,
11010                                 &remote_protocol_packets[PACKET_qXfer_uib]);
11011
11012     case TARGET_OBJECT_BTRACE:
11013       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11014                                 xfered_len,
11015         &remote_protocol_packets[PACKET_qXfer_btrace]);
11016
11017     case TARGET_OBJECT_BTRACE_CONF:
11018       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11019                                 len, xfered_len,
11020         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11021
11022     case TARGET_OBJECT_EXEC_FILE:
11023       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11024                                 len, xfered_len,
11025         &remote_protocol_packets[PACKET_qXfer_exec_file]);
11026
11027     default:
11028       return TARGET_XFER_E_IO;
11029     }
11030
11031   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
11032      large enough let the caller deal with it.  */
11033   if (len < get_remote_packet_size ())
11034     return TARGET_XFER_E_IO;
11035   len = get_remote_packet_size ();
11036
11037   /* Except for querying the minimum buffer size, target must be open.  */
11038   if (!rs->remote_desc)
11039     error (_("remote query is only available after target open"));
11040
11041   gdb_assert (annex != NULL);
11042   gdb_assert (readbuf != NULL);
11043
11044   p2 = rs->buf;
11045   *p2++ = 'q';
11046   *p2++ = query_type;
11047
11048   /* We used one buffer char for the remote protocol q command and
11049      another for the query type.  As the remote protocol encapsulation
11050      uses 4 chars plus one extra in case we are debugging
11051      (remote_debug), we have PBUFZIZ - 7 left to pack the query
11052      string.  */
11053   i = 0;
11054   while (annex[i] && (i < (get_remote_packet_size () - 8)))
11055     {
11056       /* Bad caller may have sent forbidden characters.  */
11057       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11058       *p2++ = annex[i];
11059       i++;
11060     }
11061   *p2 = '\0';
11062   gdb_assert (annex[i] == '\0');
11063
11064   i = putpkt (rs->buf);
11065   if (i < 0)
11066     return TARGET_XFER_E_IO;
11067
11068   getpkt (&rs->buf, &rs->buf_size, 0);
11069   strcpy ((char *) readbuf, rs->buf);
11070
11071   *xfered_len = strlen ((char *) readbuf);
11072   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11073 }
11074
11075 /* Implementation of to_get_memory_xfer_limit.  */
11076
11077 ULONGEST
11078 remote_target::get_memory_xfer_limit ()
11079 {
11080   return get_memory_write_packet_size ();
11081 }
11082
11083 int
11084 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11085                               const gdb_byte *pattern, ULONGEST pattern_len,
11086                               CORE_ADDR *found_addrp)
11087 {
11088   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11089   struct remote_state *rs = get_remote_state ();
11090   int max_size = get_memory_write_packet_size ();
11091   struct packet_config *packet =
11092     &remote_protocol_packets[PACKET_qSearch_memory];
11093   /* Number of packet bytes used to encode the pattern;
11094      this could be more than PATTERN_LEN due to escape characters.  */
11095   int escaped_pattern_len;
11096   /* Amount of pattern that was encodable in the packet.  */
11097   int used_pattern_len;
11098   int i;
11099   int found;
11100   ULONGEST found_addr;
11101
11102   /* Don't go to the target if we don't have to.  This is done before
11103      checking packet_config_support to avoid the possibility that a
11104      success for this edge case means the facility works in
11105      general.  */
11106   if (pattern_len > search_space_len)
11107     return 0;
11108   if (pattern_len == 0)
11109     {
11110       *found_addrp = start_addr;
11111       return 1;
11112     }
11113
11114   /* If we already know the packet isn't supported, fall back to the simple
11115      way of searching memory.  */
11116
11117   if (packet_config_support (packet) == PACKET_DISABLE)
11118     {
11119       /* Target doesn't provided special support, fall back and use the
11120          standard support (copy memory and do the search here).  */
11121       return simple_search_memory (this, start_addr, search_space_len,
11122                                    pattern, pattern_len, found_addrp);
11123     }
11124
11125   /* Make sure the remote is pointing at the right process.  */
11126   set_general_process ();
11127
11128   /* Insert header.  */
11129   i = snprintf (rs->buf, max_size, 
11130                 "qSearch:memory:%s;%s;",
11131                 phex_nz (start_addr, addr_size),
11132                 phex_nz (search_space_len, sizeof (search_space_len)));
11133   max_size -= (i + 1);
11134
11135   /* Escape as much data as fits into rs->buf.  */
11136   escaped_pattern_len =
11137     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11138                           &used_pattern_len, max_size);
11139
11140   /* Bail if the pattern is too large.  */
11141   if (used_pattern_len != pattern_len)
11142     error (_("Pattern is too large to transmit to remote target."));
11143
11144   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11145       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11146       || packet_ok (rs->buf, packet) != PACKET_OK)
11147     {
11148       /* The request may not have worked because the command is not
11149          supported.  If so, fall back to the simple way.  */
11150       if (packet_config_support (packet) == PACKET_DISABLE)
11151         {
11152           return simple_search_memory (this, start_addr, search_space_len,
11153                                        pattern, pattern_len, found_addrp);
11154         }
11155       return -1;
11156     }
11157
11158   if (rs->buf[0] == '0')
11159     found = 0;
11160   else if (rs->buf[0] == '1')
11161     {
11162       found = 1;
11163       if (rs->buf[1] != ',')
11164         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11165       unpack_varlen_hex (rs->buf + 2, &found_addr);
11166       *found_addrp = found_addr;
11167     }
11168   else
11169     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11170
11171   return found;
11172 }
11173
11174 void
11175 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11176 {
11177   struct remote_state *rs = get_remote_state ();
11178   char *p = rs->buf;
11179
11180   if (!rs->remote_desc)
11181     error (_("remote rcmd is only available after target open"));
11182
11183   /* Send a NULL command across as an empty command.  */
11184   if (command == NULL)
11185     command = "";
11186
11187   /* The query prefix.  */
11188   strcpy (rs->buf, "qRcmd,");
11189   p = strchr (rs->buf, '\0');
11190
11191   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11192       > get_remote_packet_size ())
11193     error (_("\"monitor\" command ``%s'' is too long."), command);
11194
11195   /* Encode the actual command.  */
11196   bin2hex ((const gdb_byte *) command, p, strlen (command));
11197
11198   if (putpkt (rs->buf) < 0)
11199     error (_("Communication problem with target."));
11200
11201   /* get/display the response */
11202   while (1)
11203     {
11204       char *buf;
11205
11206       /* XXX - see also remote_get_noisy_reply().  */
11207       QUIT;                     /* Allow user to bail out with ^C.  */
11208       rs->buf[0] = '\0';
11209       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11210         { 
11211           /* Timeout.  Continue to (try to) read responses.
11212              This is better than stopping with an error, assuming the stub
11213              is still executing the (long) monitor command.
11214              If needed, the user can interrupt gdb using C-c, obtaining
11215              an effect similar to stop on timeout.  */
11216           continue;
11217         }
11218       buf = rs->buf;
11219       if (buf[0] == '\0')
11220         error (_("Target does not support this command."));
11221       if (buf[0] == 'O' && buf[1] != 'K')
11222         {
11223           remote_console_output (buf + 1); /* 'O' message from stub.  */
11224           continue;
11225         }
11226       if (strcmp (buf, "OK") == 0)
11227         break;
11228       if (strlen (buf) == 3 && buf[0] == 'E'
11229           && isdigit (buf[1]) && isdigit (buf[2]))
11230         {
11231           error (_("Protocol error with Rcmd"));
11232         }
11233       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11234         {
11235           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11236
11237           fputc_unfiltered (c, outbuf);
11238         }
11239       break;
11240     }
11241 }
11242
11243 std::vector<mem_region>
11244 remote_target::memory_map ()
11245 {
11246   std::vector<mem_region> result;
11247   gdb::optional<gdb::char_vector> text
11248     = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11249
11250   if (text)
11251     result = parse_memory_map (text->data ());
11252
11253   return result;
11254 }
11255
11256 static void
11257 packet_command (const char *args, int from_tty)
11258 {
11259   remote_target *remote = get_current_remote_target ();
11260
11261   if (remote == nullptr)
11262     error (_("command can only be used with remote target"));
11263
11264   remote->packet_command (args, from_tty);
11265 }
11266
11267 void
11268 remote_target::packet_command (const char *args, int from_tty)
11269 {
11270   if (!args)
11271     error (_("remote-packet command requires packet text as argument"));
11272
11273   puts_filtered ("sending: ");
11274   print_packet (args);
11275   puts_filtered ("\n");
11276   putpkt (args);
11277
11278   remote_state *rs = get_remote_state ();
11279
11280   getpkt (&rs->buf, &rs->buf_size, 0);
11281   puts_filtered ("received: ");
11282   print_packet (rs->buf);
11283   puts_filtered ("\n");
11284 }
11285
11286 #if 0
11287 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11288
11289 static void display_thread_info (struct gdb_ext_thread_info *info);
11290
11291 static void threadset_test_cmd (char *cmd, int tty);
11292
11293 static void threadalive_test (char *cmd, int tty);
11294
11295 static void threadlist_test_cmd (char *cmd, int tty);
11296
11297 int get_and_display_threadinfo (threadref *ref);
11298
11299 static void threadinfo_test_cmd (char *cmd, int tty);
11300
11301 static int thread_display_step (threadref *ref, void *context);
11302
11303 static void threadlist_update_test_cmd (char *cmd, int tty);
11304
11305 static void init_remote_threadtests (void);
11306
11307 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11308
11309 static void
11310 threadset_test_cmd (const char *cmd, int tty)
11311 {
11312   int sample_thread = SAMPLE_THREAD;
11313
11314   printf_filtered (_("Remote threadset test\n"));
11315   set_general_thread (sample_thread);
11316 }
11317
11318
11319 static void
11320 threadalive_test (const char *cmd, int tty)
11321 {
11322   int sample_thread = SAMPLE_THREAD;
11323   int pid = inferior_ptid.pid ();
11324   ptid_t ptid = ptid_t (pid, sample_thread, 0);
11325
11326   if (remote_thread_alive (ptid))
11327     printf_filtered ("PASS: Thread alive test\n");
11328   else
11329     printf_filtered ("FAIL: Thread alive test\n");
11330 }
11331
11332 void output_threadid (char *title, threadref *ref);
11333
11334 void
11335 output_threadid (char *title, threadref *ref)
11336 {
11337   char hexid[20];
11338
11339   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11340   hexid[16] = 0;
11341   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11342 }
11343
11344 static void
11345 threadlist_test_cmd (const char *cmd, int tty)
11346 {
11347   int startflag = 1;
11348   threadref nextthread;
11349   int done, result_count;
11350   threadref threadlist[3];
11351
11352   printf_filtered ("Remote Threadlist test\n");
11353   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11354                               &result_count, &threadlist[0]))
11355     printf_filtered ("FAIL: threadlist test\n");
11356   else
11357     {
11358       threadref *scan = threadlist;
11359       threadref *limit = scan + result_count;
11360
11361       while (scan < limit)
11362         output_threadid (" thread ", scan++);
11363     }
11364 }
11365
11366 void
11367 display_thread_info (struct gdb_ext_thread_info *info)
11368 {
11369   output_threadid ("Threadid: ", &info->threadid);
11370   printf_filtered ("Name: %s\n ", info->shortname);
11371   printf_filtered ("State: %s\n", info->display);
11372   printf_filtered ("other: %s\n\n", info->more_display);
11373 }
11374
11375 int
11376 get_and_display_threadinfo (threadref *ref)
11377 {
11378   int result;
11379   int set;
11380   struct gdb_ext_thread_info threadinfo;
11381
11382   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11383     | TAG_MOREDISPLAY | TAG_DISPLAY;
11384   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11385     display_thread_info (&threadinfo);
11386   return result;
11387 }
11388
11389 static void
11390 threadinfo_test_cmd (const char *cmd, int tty)
11391 {
11392   int athread = SAMPLE_THREAD;
11393   threadref thread;
11394   int set;
11395
11396   int_to_threadref (&thread, athread);
11397   printf_filtered ("Remote Threadinfo test\n");
11398   if (!get_and_display_threadinfo (&thread))
11399     printf_filtered ("FAIL cannot get thread info\n");
11400 }
11401
11402 static int
11403 thread_display_step (threadref *ref, void *context)
11404 {
11405   /* output_threadid(" threadstep ",ref); *//* simple test */
11406   return get_and_display_threadinfo (ref);
11407 }
11408
11409 static void
11410 threadlist_update_test_cmd (const char *cmd, int tty)
11411 {
11412   printf_filtered ("Remote Threadlist update test\n");
11413   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11414 }
11415
11416 static void
11417 init_remote_threadtests (void)
11418 {
11419   add_com ("tlist", class_obscure, threadlist_test_cmd,
11420            _("Fetch and print the remote list of "
11421              "thread identifiers, one pkt only"));
11422   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11423            _("Fetch and display info about one thread"));
11424   add_com ("tset", class_obscure, threadset_test_cmd,
11425            _("Test setting to a different thread"));
11426   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11427            _("Iterate through updating all remote thread info"));
11428   add_com ("talive", class_obscure, threadalive_test,
11429            _(" Remote thread alive test "));
11430 }
11431
11432 #endif /* 0 */
11433
11434 /* Convert a thread ID to a string.  Returns the string in a static
11435    buffer.  */
11436
11437 const char *
11438 remote_target::pid_to_str (ptid_t ptid)
11439 {
11440   static char buf[64];
11441   struct remote_state *rs = get_remote_state ();
11442
11443   if (ptid_equal (ptid, null_ptid))
11444     return normal_pid_to_str (ptid);
11445   else if (ptid_is_pid (ptid))
11446     {
11447       /* Printing an inferior target id.  */
11448
11449       /* When multi-process extensions are off, there's no way in the
11450          remote protocol to know the remote process id, if there's any
11451          at all.  There's one exception --- when we're connected with
11452          target extended-remote, and we manually attached to a process
11453          with "attach PID".  We don't record anywhere a flag that
11454          allows us to distinguish that case from the case of
11455          connecting with extended-remote and the stub already being
11456          attached to a process, and reporting yes to qAttached, hence
11457          no smart special casing here.  */
11458       if (!remote_multi_process_p (rs))
11459         {
11460           xsnprintf (buf, sizeof buf, "Remote target");
11461           return buf;
11462         }
11463
11464       return normal_pid_to_str (ptid);
11465     }
11466   else
11467     {
11468       if (ptid_equal (magic_null_ptid, ptid))
11469         xsnprintf (buf, sizeof buf, "Thread <main>");
11470       else if (remote_multi_process_p (rs))
11471         if (ptid_get_lwp (ptid) == 0)
11472           return normal_pid_to_str (ptid);
11473         else
11474           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11475                      ptid.pid (), ptid_get_lwp (ptid));
11476       else
11477         xsnprintf (buf, sizeof buf, "Thread %ld",
11478                    ptid_get_lwp (ptid));
11479       return buf;
11480     }
11481 }
11482
11483 /* Get the address of the thread local variable in OBJFILE which is
11484    stored at OFFSET within the thread local storage for thread PTID.  */
11485
11486 CORE_ADDR
11487 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11488                                          CORE_ADDR offset)
11489 {
11490   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11491     {
11492       struct remote_state *rs = get_remote_state ();
11493       char *p = rs->buf;
11494       char *endp = rs->buf + get_remote_packet_size ();
11495       enum packet_result result;
11496
11497       strcpy (p, "qGetTLSAddr:");
11498       p += strlen (p);
11499       p = write_ptid (p, endp, ptid);
11500       *p++ = ',';
11501       p += hexnumstr (p, offset);
11502       *p++ = ',';
11503       p += hexnumstr (p, lm);
11504       *p++ = '\0';
11505
11506       putpkt (rs->buf);
11507       getpkt (&rs->buf, &rs->buf_size, 0);
11508       result = packet_ok (rs->buf,
11509                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11510       if (result == PACKET_OK)
11511         {
11512           ULONGEST result;
11513
11514           unpack_varlen_hex (rs->buf, &result);
11515           return result;
11516         }
11517       else if (result == PACKET_UNKNOWN)
11518         throw_error (TLS_GENERIC_ERROR,
11519                      _("Remote target doesn't support qGetTLSAddr packet"));
11520       else
11521         throw_error (TLS_GENERIC_ERROR,
11522                      _("Remote target failed to process qGetTLSAddr request"));
11523     }
11524   else
11525     throw_error (TLS_GENERIC_ERROR,
11526                  _("TLS not supported or disabled on this target"));
11527   /* Not reached.  */
11528   return 0;
11529 }
11530
11531 /* Provide thread local base, i.e. Thread Information Block address.
11532    Returns 1 if ptid is found and thread_local_base is non zero.  */
11533
11534 bool
11535 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11536 {
11537   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11538     {
11539       struct remote_state *rs = get_remote_state ();
11540       char *p = rs->buf;
11541       char *endp = rs->buf + get_remote_packet_size ();
11542       enum packet_result result;
11543
11544       strcpy (p, "qGetTIBAddr:");
11545       p += strlen (p);
11546       p = write_ptid (p, endp, ptid);
11547       *p++ = '\0';
11548
11549       putpkt (rs->buf);
11550       getpkt (&rs->buf, &rs->buf_size, 0);
11551       result = packet_ok (rs->buf,
11552                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11553       if (result == PACKET_OK)
11554         {
11555           ULONGEST result;
11556
11557           unpack_varlen_hex (rs->buf, &result);
11558           if (addr)
11559             *addr = (CORE_ADDR) result;
11560           return true;
11561         }
11562       else if (result == PACKET_UNKNOWN)
11563         error (_("Remote target doesn't support qGetTIBAddr packet"));
11564       else
11565         error (_("Remote target failed to process qGetTIBAddr request"));
11566     }
11567   else
11568     error (_("qGetTIBAddr not supported or disabled on this target"));
11569   /* Not reached.  */
11570   return false;
11571 }
11572
11573 /* Support for inferring a target description based on the current
11574    architecture and the size of a 'g' packet.  While the 'g' packet
11575    can have any size (since optional registers can be left off the
11576    end), some sizes are easily recognizable given knowledge of the
11577    approximate architecture.  */
11578
11579 struct remote_g_packet_guess
11580 {
11581   int bytes;
11582   const struct target_desc *tdesc;
11583 };
11584 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11585 DEF_VEC_O(remote_g_packet_guess_s);
11586
11587 struct remote_g_packet_data
11588 {
11589   VEC(remote_g_packet_guess_s) *guesses;
11590 };
11591
11592 static struct gdbarch_data *remote_g_packet_data_handle;
11593
11594 static void *
11595 remote_g_packet_data_init (struct obstack *obstack)
11596 {
11597   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11598 }
11599
11600 void
11601 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11602                                 const struct target_desc *tdesc)
11603 {
11604   struct remote_g_packet_data *data
11605     = ((struct remote_g_packet_data *)
11606        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11607   struct remote_g_packet_guess new_guess, *guess;
11608   int ix;
11609
11610   gdb_assert (tdesc != NULL);
11611
11612   for (ix = 0;
11613        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11614        ix++)
11615     if (guess->bytes == bytes)
11616       internal_error (__FILE__, __LINE__,
11617                       _("Duplicate g packet description added for size %d"),
11618                       bytes);
11619
11620   new_guess.bytes = bytes;
11621   new_guess.tdesc = tdesc;
11622   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11623 }
11624
11625 /* Return 1 if remote_read_description would do anything on this target
11626    and architecture, 0 otherwise.  */
11627
11628 static int
11629 remote_read_description_p (struct target_ops *target)
11630 {
11631   struct remote_g_packet_data *data
11632     = ((struct remote_g_packet_data *)
11633        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11634
11635   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11636     return 1;
11637
11638   return 0;
11639 }
11640
11641 const struct target_desc *
11642 remote_target::read_description ()
11643 {
11644   struct remote_g_packet_data *data
11645     = ((struct remote_g_packet_data *)
11646        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11647
11648   /* Do not try this during initial connection, when we do not know
11649      whether there is a running but stopped thread.  */
11650   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11651     return beneath ()->read_description ();
11652
11653   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11654     {
11655       struct remote_g_packet_guess *guess;
11656       int ix;
11657       int bytes = send_g_packet ();
11658
11659       for (ix = 0;
11660            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11661            ix++)
11662         if (guess->bytes == bytes)
11663           return guess->tdesc;
11664
11665       /* We discard the g packet.  A minor optimization would be to
11666          hold on to it, and fill the register cache once we have selected
11667          an architecture, but it's too tricky to do safely.  */
11668     }
11669
11670   return beneath ()->read_description ();
11671 }
11672
11673 /* Remote file transfer support.  This is host-initiated I/O, not
11674    target-initiated; for target-initiated, see remote-fileio.c.  */
11675
11676 /* If *LEFT is at least the length of STRING, copy STRING to
11677    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11678    decrease *LEFT.  Otherwise raise an error.  */
11679
11680 static void
11681 remote_buffer_add_string (char **buffer, int *left, const char *string)
11682 {
11683   int len = strlen (string);
11684
11685   if (len > *left)
11686     error (_("Packet too long for target."));
11687
11688   memcpy (*buffer, string, len);
11689   *buffer += len;
11690   *left -= len;
11691
11692   /* NUL-terminate the buffer as a convenience, if there is
11693      room.  */
11694   if (*left)
11695     **buffer = '\0';
11696 }
11697
11698 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11699    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11700    decrease *LEFT.  Otherwise raise an error.  */
11701
11702 static void
11703 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11704                          int len)
11705 {
11706   if (2 * len > *left)
11707     error (_("Packet too long for target."));
11708
11709   bin2hex (bytes, *buffer, len);
11710   *buffer += 2 * len;
11711   *left -= 2 * len;
11712
11713   /* NUL-terminate the buffer as a convenience, if there is
11714      room.  */
11715   if (*left)
11716     **buffer = '\0';
11717 }
11718
11719 /* If *LEFT is large enough, convert VALUE to hex and add it to
11720    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11721    decrease *LEFT.  Otherwise raise an error.  */
11722
11723 static void
11724 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11725 {
11726   int len = hexnumlen (value);
11727
11728   if (len > *left)
11729     error (_("Packet too long for target."));
11730
11731   hexnumstr (*buffer, value);
11732   *buffer += len;
11733   *left -= len;
11734
11735   /* NUL-terminate the buffer as a convenience, if there is
11736      room.  */
11737   if (*left)
11738     **buffer = '\0';
11739 }
11740
11741 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11742    value, *REMOTE_ERRNO to the remote error number or zero if none
11743    was included, and *ATTACHMENT to point to the start of the annex
11744    if any.  The length of the packet isn't needed here; there may
11745    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11746
11747    Return 0 if the packet could be parsed, -1 if it could not.  If
11748    -1 is returned, the other variables may not be initialized.  */
11749
11750 static int
11751 remote_hostio_parse_result (char *buffer, int *retcode,
11752                             int *remote_errno, char **attachment)
11753 {
11754   char *p, *p2;
11755
11756   *remote_errno = 0;
11757   *attachment = NULL;
11758
11759   if (buffer[0] != 'F')
11760     return -1;
11761
11762   errno = 0;
11763   *retcode = strtol (&buffer[1], &p, 16);
11764   if (errno != 0 || p == &buffer[1])
11765     return -1;
11766
11767   /* Check for ",errno".  */
11768   if (*p == ',')
11769     {
11770       errno = 0;
11771       *remote_errno = strtol (p + 1, &p2, 16);
11772       if (errno != 0 || p + 1 == p2)
11773         return -1;
11774       p = p2;
11775     }
11776
11777   /* Check for ";attachment".  If there is no attachment, the
11778      packet should end here.  */
11779   if (*p == ';')
11780     {
11781       *attachment = p + 1;
11782       return 0;
11783     }
11784   else if (*p == '\0')
11785     return 0;
11786   else
11787     return -1;
11788 }
11789
11790 /* Send a prepared I/O packet to the target and read its response.
11791    The prepared packet is in the global RS->BUF before this function
11792    is called, and the answer is there when we return.
11793
11794    COMMAND_BYTES is the length of the request to send, which may include
11795    binary data.  WHICH_PACKET is the packet configuration to check
11796    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11797    is set to the error number and -1 is returned.  Otherwise the value
11798    returned by the function is returned.
11799
11800    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11801    attachment is expected; an error will be reported if there's a
11802    mismatch.  If one is found, *ATTACHMENT will be set to point into
11803    the packet buffer and *ATTACHMENT_LEN will be set to the
11804    attachment's length.  */
11805
11806 int
11807 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11808                                            int *remote_errno, char **attachment,
11809                                            int *attachment_len)
11810 {
11811   struct remote_state *rs = get_remote_state ();
11812   int ret, bytes_read;
11813   char *attachment_tmp;
11814
11815   if (packet_support (which_packet) == PACKET_DISABLE)
11816     {
11817       *remote_errno = FILEIO_ENOSYS;
11818       return -1;
11819     }
11820
11821   putpkt_binary (rs->buf, command_bytes);
11822   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11823
11824   /* If it timed out, something is wrong.  Don't try to parse the
11825      buffer.  */
11826   if (bytes_read < 0)
11827     {
11828       *remote_errno = FILEIO_EINVAL;
11829       return -1;
11830     }
11831
11832   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11833     {
11834     case PACKET_ERROR:
11835       *remote_errno = FILEIO_EINVAL;
11836       return -1;
11837     case PACKET_UNKNOWN:
11838       *remote_errno = FILEIO_ENOSYS;
11839       return -1;
11840     case PACKET_OK:
11841       break;
11842     }
11843
11844   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11845                                   &attachment_tmp))
11846     {
11847       *remote_errno = FILEIO_EINVAL;
11848       return -1;
11849     }
11850
11851   /* Make sure we saw an attachment if and only if we expected one.  */
11852   if ((attachment_tmp == NULL && attachment != NULL)
11853       || (attachment_tmp != NULL && attachment == NULL))
11854     {
11855       *remote_errno = FILEIO_EINVAL;
11856       return -1;
11857     }
11858
11859   /* If an attachment was found, it must point into the packet buffer;
11860      work out how many bytes there were.  */
11861   if (attachment_tmp != NULL)
11862     {
11863       *attachment = attachment_tmp;
11864       *attachment_len = bytes_read - (*attachment - rs->buf);
11865     }
11866
11867   return ret;
11868 }
11869
11870 /* See declaration.h.  */
11871
11872 void
11873 readahead_cache::invalidate ()
11874 {
11875   this->fd = -1;
11876 }
11877
11878 /* See declaration.h.  */
11879
11880 void
11881 readahead_cache::invalidate_fd (int fd)
11882 {
11883   if (this->fd == fd)
11884     this->fd = -1;
11885 }
11886
11887 /* Set the filesystem remote_hostio functions that take FILENAME
11888    arguments will use.  Return 0 on success, or -1 if an error
11889    occurs (and set *REMOTE_ERRNO).  */
11890
11891 int
11892 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11893                                              int *remote_errno)
11894 {
11895   struct remote_state *rs = get_remote_state ();
11896   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11897   char *p = rs->buf;
11898   int left = get_remote_packet_size () - 1;
11899   char arg[9];
11900   int ret;
11901
11902   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11903     return 0;
11904
11905   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11906     return 0;
11907
11908   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11909
11910   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11911   remote_buffer_add_string (&p, &left, arg);
11912
11913   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11914                                     remote_errno, NULL, NULL);
11915
11916   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11917     return 0;
11918
11919   if (ret == 0)
11920     rs->fs_pid = required_pid;
11921
11922   return ret;
11923 }
11924
11925 /* Implementation of to_fileio_open.  */
11926
11927 int
11928 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11929                                    int flags, int mode, int warn_if_slow,
11930                                    int *remote_errno)
11931 {
11932   struct remote_state *rs = get_remote_state ();
11933   char *p = rs->buf;
11934   int left = get_remote_packet_size () - 1;
11935
11936   if (warn_if_slow)
11937     {
11938       static int warning_issued = 0;
11939
11940       printf_unfiltered (_("Reading %s from remote target...\n"),
11941                          filename);
11942
11943       if (!warning_issued)
11944         {
11945           warning (_("File transfers from remote targets can be slow."
11946                      " Use \"set sysroot\" to access files locally"
11947                      " instead."));
11948           warning_issued = 1;
11949         }
11950     }
11951
11952   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11953     return -1;
11954
11955   remote_buffer_add_string (&p, &left, "vFile:open:");
11956
11957   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11958                            strlen (filename));
11959   remote_buffer_add_string (&p, &left, ",");
11960
11961   remote_buffer_add_int (&p, &left, flags);
11962   remote_buffer_add_string (&p, &left, ",");
11963
11964   remote_buffer_add_int (&p, &left, mode);
11965
11966   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
11967                                      remote_errno, NULL, NULL);
11968 }
11969
11970 int
11971 remote_target::fileio_open (struct inferior *inf, const char *filename,
11972                             int flags, int mode, int warn_if_slow,
11973                             int *remote_errno)
11974 {
11975   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
11976                              remote_errno);
11977 }
11978
11979 /* Implementation of to_fileio_pwrite.  */
11980
11981 int
11982 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11983                                      ULONGEST offset, int *remote_errno)
11984 {
11985   struct remote_state *rs = get_remote_state ();
11986   char *p = rs->buf;
11987   int left = get_remote_packet_size ();
11988   int out_len;
11989
11990   rs->readahead_cache.invalidate_fd (fd);
11991
11992   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11993
11994   remote_buffer_add_int (&p, &left, fd);
11995   remote_buffer_add_string (&p, &left, ",");
11996
11997   remote_buffer_add_int (&p, &left, offset);
11998   remote_buffer_add_string (&p, &left, ",");
11999
12000   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12001                              get_remote_packet_size () - (p - rs->buf));
12002
12003   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12004                                      remote_errno, NULL, NULL);
12005 }
12006
12007 int
12008 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12009                               ULONGEST offset, int *remote_errno)
12010 {
12011   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12012 }
12013
12014 /* Helper for the implementation of to_fileio_pread.  Read the file
12015    from the remote side with vFile:pread.  */
12016
12017 int
12018 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12019                                           ULONGEST offset, int *remote_errno)
12020 {
12021   struct remote_state *rs = get_remote_state ();
12022   char *p = rs->buf;
12023   char *attachment;
12024   int left = get_remote_packet_size ();
12025   int ret, attachment_len;
12026   int read_len;
12027
12028   remote_buffer_add_string (&p, &left, "vFile:pread:");
12029
12030   remote_buffer_add_int (&p, &left, fd);
12031   remote_buffer_add_string (&p, &left, ",");
12032
12033   remote_buffer_add_int (&p, &left, len);
12034   remote_buffer_add_string (&p, &left, ",");
12035
12036   remote_buffer_add_int (&p, &left, offset);
12037
12038   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12039                                     remote_errno, &attachment,
12040                                     &attachment_len);
12041
12042   if (ret < 0)
12043     return ret;
12044
12045   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12046                                     read_buf, len);
12047   if (read_len != ret)
12048     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12049
12050   return ret;
12051 }
12052
12053 /* See declaration.h.  */
12054
12055 int
12056 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12057                         ULONGEST offset)
12058 {
12059   if (this->fd == fd
12060       && this->offset <= offset
12061       && offset < this->offset + this->bufsize)
12062     {
12063       ULONGEST max = this->offset + this->bufsize;
12064
12065       if (offset + len > max)
12066         len = max - offset;
12067
12068       memcpy (read_buf, this->buf + offset - this->offset, len);
12069       return len;
12070     }
12071
12072   return 0;
12073 }
12074
12075 /* Implementation of to_fileio_pread.  */
12076
12077 int
12078 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12079                                     ULONGEST offset, int *remote_errno)
12080 {
12081   int ret;
12082   struct remote_state *rs = get_remote_state ();
12083   readahead_cache *cache = &rs->readahead_cache;
12084
12085   ret = cache->pread (fd, read_buf, len, offset);
12086   if (ret > 0)
12087     {
12088       cache->hit_count++;
12089
12090       if (remote_debug)
12091         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12092                             pulongest (cache->hit_count));
12093       return ret;
12094     }
12095
12096   cache->miss_count++;
12097   if (remote_debug)
12098     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12099                         pulongest (cache->miss_count));
12100
12101   cache->fd = fd;
12102   cache->offset = offset;
12103   cache->bufsize = get_remote_packet_size ();
12104   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12105
12106   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12107                                    cache->offset, remote_errno);
12108   if (ret <= 0)
12109     {
12110       cache->invalidate_fd (fd);
12111       return ret;
12112     }
12113
12114   cache->bufsize = ret;
12115   return cache->pread (fd, read_buf, len, offset);
12116 }
12117
12118 int
12119 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12120                              ULONGEST offset, int *remote_errno)
12121 {
12122   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12123 }
12124
12125 /* Implementation of to_fileio_close.  */
12126
12127 int
12128 remote_target::remote_hostio_close (int fd, int *remote_errno)
12129 {
12130   struct remote_state *rs = get_remote_state ();
12131   char *p = rs->buf;
12132   int left = get_remote_packet_size () - 1;
12133
12134   rs->readahead_cache.invalidate_fd (fd);
12135
12136   remote_buffer_add_string (&p, &left, "vFile:close:");
12137
12138   remote_buffer_add_int (&p, &left, fd);
12139
12140   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12141                                      remote_errno, NULL, NULL);
12142 }
12143
12144 int
12145 remote_target::fileio_close (int fd, int *remote_errno)
12146 {
12147   return remote_hostio_close (fd, remote_errno);
12148 }
12149
12150 /* Implementation of to_fileio_unlink.  */
12151
12152 int
12153 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12154                                      int *remote_errno)
12155 {
12156   struct remote_state *rs = get_remote_state ();
12157   char *p = rs->buf;
12158   int left = get_remote_packet_size () - 1;
12159
12160   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12161     return -1;
12162
12163   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12164
12165   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12166                            strlen (filename));
12167
12168   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12169                                      remote_errno, NULL, NULL);
12170 }
12171
12172 int
12173 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12174                               int *remote_errno)
12175 {
12176   return remote_hostio_unlink (inf, filename, remote_errno);
12177 }
12178
12179 /* Implementation of to_fileio_readlink.  */
12180
12181 gdb::optional<std::string>
12182 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12183                                 int *remote_errno)
12184 {
12185   struct remote_state *rs = get_remote_state ();
12186   char *p = rs->buf;
12187   char *attachment;
12188   int left = get_remote_packet_size ();
12189   int len, attachment_len;
12190   int read_len;
12191
12192   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12193     return {};
12194
12195   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12196
12197   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12198                            strlen (filename));
12199
12200   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12201                                     remote_errno, &attachment,
12202                                     &attachment_len);
12203
12204   if (len < 0)
12205     return {};
12206
12207   std::string ret (len, '\0');
12208
12209   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12210                                     (gdb_byte *) &ret[0], len);
12211   if (read_len != len)
12212     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12213
12214   return ret;
12215 }
12216
12217 /* Implementation of to_fileio_fstat.  */
12218
12219 int
12220 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12221 {
12222   struct remote_state *rs = get_remote_state ();
12223   char *p = rs->buf;
12224   int left = get_remote_packet_size ();
12225   int attachment_len, ret;
12226   char *attachment;
12227   struct fio_stat fst;
12228   int read_len;
12229
12230   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12231
12232   remote_buffer_add_int (&p, &left, fd);
12233
12234   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12235                                     remote_errno, &attachment,
12236                                     &attachment_len);
12237   if (ret < 0)
12238     {
12239       if (*remote_errno != FILEIO_ENOSYS)
12240         return ret;
12241
12242       /* Strictly we should return -1, ENOSYS here, but when
12243          "set sysroot remote:" was implemented in August 2008
12244          BFD's need for a stat function was sidestepped with
12245          this hack.  This was not remedied until March 2015
12246          so we retain the previous behavior to avoid breaking
12247          compatibility.
12248
12249          Note that the memset is a March 2015 addition; older
12250          GDBs set st_size *and nothing else* so the structure
12251          would have garbage in all other fields.  This might
12252          break something but retaining the previous behavior
12253          here would be just too wrong.  */
12254
12255       memset (st, 0, sizeof (struct stat));
12256       st->st_size = INT_MAX;
12257       return 0;
12258     }
12259
12260   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12261                                     (gdb_byte *) &fst, sizeof (fst));
12262
12263   if (read_len != ret)
12264     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12265
12266   if (read_len != sizeof (fst))
12267     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12268            read_len, (int) sizeof (fst));
12269
12270   remote_fileio_to_host_stat (&fst, st);
12271
12272   return 0;
12273 }
12274
12275 /* Implementation of to_filesystem_is_local.  */
12276
12277 bool
12278 remote_target::filesystem_is_local ()
12279 {
12280   /* Valgrind GDB presents itself as a remote target but works
12281      on the local filesystem: it does not implement remote get
12282      and users are not expected to set a sysroot.  To handle
12283      this case we treat the remote filesystem as local if the
12284      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12285      does not support vFile:open.  */
12286   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12287     {
12288       enum packet_support ps = packet_support (PACKET_vFile_open);
12289
12290       if (ps == PACKET_SUPPORT_UNKNOWN)
12291         {
12292           int fd, remote_errno;
12293
12294           /* Try opening a file to probe support.  The supplied
12295              filename is irrelevant, we only care about whether
12296              the stub recognizes the packet or not.  */
12297           fd = remote_hostio_open (NULL, "just probing",
12298                                    FILEIO_O_RDONLY, 0700, 0,
12299                                    &remote_errno);
12300
12301           if (fd >= 0)
12302             remote_hostio_close (fd, &remote_errno);
12303
12304           ps = packet_support (PACKET_vFile_open);
12305         }
12306
12307       if (ps == PACKET_DISABLE)
12308         {
12309           static int warning_issued = 0;
12310
12311           if (!warning_issued)
12312             {
12313               warning (_("remote target does not support file"
12314                          " transfer, attempting to access files"
12315                          " from local filesystem."));
12316               warning_issued = 1;
12317             }
12318
12319           return true;
12320         }
12321     }
12322
12323   return false;
12324 }
12325
12326 static int
12327 remote_fileio_errno_to_host (int errnum)
12328 {
12329   switch (errnum)
12330     {
12331       case FILEIO_EPERM:
12332         return EPERM;
12333       case FILEIO_ENOENT:
12334         return ENOENT;
12335       case FILEIO_EINTR:
12336         return EINTR;
12337       case FILEIO_EIO:
12338         return EIO;
12339       case FILEIO_EBADF:
12340         return EBADF;
12341       case FILEIO_EACCES:
12342         return EACCES;
12343       case FILEIO_EFAULT:
12344         return EFAULT;
12345       case FILEIO_EBUSY:
12346         return EBUSY;
12347       case FILEIO_EEXIST:
12348         return EEXIST;
12349       case FILEIO_ENODEV:
12350         return ENODEV;
12351       case FILEIO_ENOTDIR:
12352         return ENOTDIR;
12353       case FILEIO_EISDIR:
12354         return EISDIR;
12355       case FILEIO_EINVAL:
12356         return EINVAL;
12357       case FILEIO_ENFILE:
12358         return ENFILE;
12359       case FILEIO_EMFILE:
12360         return EMFILE;
12361       case FILEIO_EFBIG:
12362         return EFBIG;
12363       case FILEIO_ENOSPC:
12364         return ENOSPC;
12365       case FILEIO_ESPIPE:
12366         return ESPIPE;
12367       case FILEIO_EROFS:
12368         return EROFS;
12369       case FILEIO_ENOSYS:
12370         return ENOSYS;
12371       case FILEIO_ENAMETOOLONG:
12372         return ENAMETOOLONG;
12373     }
12374   return -1;
12375 }
12376
12377 static char *
12378 remote_hostio_error (int errnum)
12379 {
12380   int host_error = remote_fileio_errno_to_host (errnum);
12381
12382   if (host_error == -1)
12383     error (_("Unknown remote I/O error %d"), errnum);
12384   else
12385     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12386 }
12387
12388 /* A RAII wrapper around a remote file descriptor.  */
12389
12390 class scoped_remote_fd
12391 {
12392 public:
12393   scoped_remote_fd (remote_target *remote, int fd)
12394     : m_remote (remote), m_fd (fd)
12395   {
12396   }
12397
12398   ~scoped_remote_fd ()
12399   {
12400     if (m_fd != -1)
12401       {
12402         try
12403           {
12404             int remote_errno;
12405             m_remote->remote_hostio_close (m_fd, &remote_errno);
12406           }
12407         catch (...)
12408           {
12409             /* Swallow exception before it escapes the dtor.  If
12410                something goes wrong, likely the connection is gone,
12411                and there's nothing else that can be done.  */
12412           }
12413       }
12414   }
12415
12416   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12417
12418   /* Release ownership of the file descriptor, and return it.  */
12419   int release () noexcept
12420   {
12421     int fd = m_fd;
12422     m_fd = -1;
12423     return fd;
12424   }
12425
12426   /* Return the owned file descriptor.  */
12427   int get () const noexcept
12428   {
12429     return m_fd;
12430   }
12431
12432 private:
12433   /* The remote target.  */
12434   remote_target *m_remote;
12435
12436   /* The owned remote I/O file descriptor.  */
12437   int m_fd;
12438 };
12439
12440 void
12441 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12442 {
12443   remote_target *remote = get_current_remote_target ();
12444
12445   if (remote == nullptr)
12446     error (_("command can only be used with remote target"));
12447
12448   remote->remote_file_put (local_file, remote_file, from_tty);
12449 }
12450
12451 void
12452 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12453                                 int from_tty)
12454 {
12455   int retcode, remote_errno, bytes, io_size;
12456   int bytes_in_buffer;
12457   int saw_eof;
12458   ULONGEST offset;
12459
12460   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12461   if (file == NULL)
12462     perror_with_name (local_file);
12463
12464   scoped_remote_fd fd
12465     (this, remote_hostio_open (NULL,
12466                                remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12467                                              | FILEIO_O_TRUNC),
12468                                0700, 0, &remote_errno));
12469   if (fd.get () == -1)
12470     remote_hostio_error (remote_errno);
12471
12472   /* Send up to this many bytes at once.  They won't all fit in the
12473      remote packet limit, so we'll transfer slightly fewer.  */
12474   io_size = get_remote_packet_size ();
12475   gdb::byte_vector buffer (io_size);
12476
12477   bytes_in_buffer = 0;
12478   saw_eof = 0;
12479   offset = 0;
12480   while (bytes_in_buffer || !saw_eof)
12481     {
12482       if (!saw_eof)
12483         {
12484           bytes = fread (buffer.data () + bytes_in_buffer, 1,
12485                          io_size - bytes_in_buffer,
12486                          file.get ());
12487           if (bytes == 0)
12488             {
12489               if (ferror (file.get ()))
12490                 error (_("Error reading %s."), local_file);
12491               else
12492                 {
12493                   /* EOF.  Unless there is something still in the
12494                      buffer from the last iteration, we are done.  */
12495                   saw_eof = 1;
12496                   if (bytes_in_buffer == 0)
12497                     break;
12498                 }
12499             }
12500         }
12501       else
12502         bytes = 0;
12503
12504       bytes += bytes_in_buffer;
12505       bytes_in_buffer = 0;
12506
12507       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12508                                       offset, &remote_errno);
12509
12510       if (retcode < 0)
12511         remote_hostio_error (remote_errno);
12512       else if (retcode == 0)
12513         error (_("Remote write of %d bytes returned 0!"), bytes);
12514       else if (retcode < bytes)
12515         {
12516           /* Short write.  Save the rest of the read data for the next
12517              write.  */
12518           bytes_in_buffer = bytes - retcode;
12519           memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12520         }
12521
12522       offset += retcode;
12523     }
12524
12525   if (remote_hostio_close (fd.release (), &remote_errno))
12526     remote_hostio_error (remote_errno);
12527
12528   if (from_tty)
12529     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12530 }
12531
12532 void
12533 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12534 {
12535   remote_target *remote = get_current_remote_target ();
12536
12537   if (remote == nullptr)
12538     error (_("command can only be used with remote target"));
12539
12540   remote->remote_file_get (remote_file, local_file, from_tty);
12541 }
12542
12543 void
12544 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12545                                 int from_tty)
12546 {
12547   int remote_errno, bytes, io_size;
12548   ULONGEST offset;
12549
12550   scoped_remote_fd fd
12551     (this, remote_hostio_open (NULL,
12552                                remote_file, FILEIO_O_RDONLY, 0, 0,
12553                                &remote_errno));
12554   if (fd.get () == -1)
12555     remote_hostio_error (remote_errno);
12556
12557   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12558   if (file == NULL)
12559     perror_with_name (local_file);
12560
12561   /* Send up to this many bytes at once.  They won't all fit in the
12562      remote packet limit, so we'll transfer slightly fewer.  */
12563   io_size = get_remote_packet_size ();
12564   gdb::byte_vector buffer (io_size);
12565
12566   offset = 0;
12567   while (1)
12568     {
12569       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12570                                    &remote_errno);
12571       if (bytes == 0)
12572         /* Success, but no bytes, means end-of-file.  */
12573         break;
12574       if (bytes == -1)
12575         remote_hostio_error (remote_errno);
12576
12577       offset += bytes;
12578
12579       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12580       if (bytes == 0)
12581         perror_with_name (local_file);
12582     }
12583
12584   if (remote_hostio_close (fd.release (), &remote_errno))
12585     remote_hostio_error (remote_errno);
12586
12587   if (from_tty)
12588     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12589 }
12590
12591 void
12592 remote_file_delete (const char *remote_file, int from_tty)
12593 {
12594   remote_target *remote = get_current_remote_target ();
12595
12596   if (remote == nullptr)
12597     error (_("command can only be used with remote target"));
12598
12599   remote->remote_file_delete (remote_file, from_tty);
12600 }
12601
12602 void
12603 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12604 {
12605   int retcode, remote_errno;
12606
12607   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12608   if (retcode == -1)
12609     remote_hostio_error (remote_errno);
12610
12611   if (from_tty)
12612     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12613 }
12614
12615 static void
12616 remote_put_command (const char *args, int from_tty)
12617 {
12618   if (args == NULL)
12619     error_no_arg (_("file to put"));
12620
12621   gdb_argv argv (args);
12622   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12623     error (_("Invalid parameters to remote put"));
12624
12625   remote_file_put (argv[0], argv[1], from_tty);
12626 }
12627
12628 static void
12629 remote_get_command (const char *args, int from_tty)
12630 {
12631   if (args == NULL)
12632     error_no_arg (_("file to get"));
12633
12634   gdb_argv argv (args);
12635   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12636     error (_("Invalid parameters to remote get"));
12637
12638   remote_file_get (argv[0], argv[1], from_tty);
12639 }
12640
12641 static void
12642 remote_delete_command (const char *args, int from_tty)
12643 {
12644   if (args == NULL)
12645     error_no_arg (_("file to delete"));
12646
12647   gdb_argv argv (args);
12648   if (argv[0] == NULL || argv[1] != NULL)
12649     error (_("Invalid parameters to remote delete"));
12650
12651   remote_file_delete (argv[0], from_tty);
12652 }
12653
12654 static void
12655 remote_command (const char *args, int from_tty)
12656 {
12657   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12658 }
12659
12660 bool
12661 remote_target::can_execute_reverse ()
12662 {
12663   if (packet_support (PACKET_bs) == PACKET_ENABLE
12664       || packet_support (PACKET_bc) == PACKET_ENABLE)
12665     return true;
12666   else
12667     return false;
12668 }
12669
12670 bool
12671 remote_target::supports_non_stop ()
12672 {
12673   return true;
12674 }
12675
12676 bool
12677 remote_target::supports_disable_randomization ()
12678 {
12679   /* Only supported in extended mode.  */
12680   return false;
12681 }
12682
12683 bool
12684 remote_target::supports_multi_process ()
12685 {
12686   struct remote_state *rs = get_remote_state ();
12687
12688   return remote_multi_process_p (rs);
12689 }
12690
12691 static int
12692 remote_supports_cond_tracepoints ()
12693 {
12694   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12695 }
12696
12697 bool
12698 remote_target::supports_evaluation_of_breakpoint_conditions ()
12699 {
12700   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12701 }
12702
12703 static int
12704 remote_supports_fast_tracepoints ()
12705 {
12706   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12707 }
12708
12709 static int
12710 remote_supports_static_tracepoints ()
12711 {
12712   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12713 }
12714
12715 static int
12716 remote_supports_install_in_trace ()
12717 {
12718   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12719 }
12720
12721 bool
12722 remote_target::supports_enable_disable_tracepoint ()
12723 {
12724   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12725           == PACKET_ENABLE);
12726 }
12727
12728 bool
12729 remote_target::supports_string_tracing ()
12730 {
12731   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12732 }
12733
12734 bool
12735 remote_target::can_run_breakpoint_commands ()
12736 {
12737   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12738 }
12739
12740 void
12741 remote_target::trace_init ()
12742 {
12743   struct remote_state *rs = get_remote_state ();
12744
12745   putpkt ("QTinit");
12746   remote_get_noisy_reply ();
12747   if (strcmp (rs->buf, "OK") != 0)
12748     error (_("Target does not support this command."));
12749 }
12750
12751 /* Recursive routine to walk through command list including loops, and
12752    download packets for each command.  */
12753
12754 void
12755 remote_target::remote_download_command_source (int num, ULONGEST addr,
12756                                                struct command_line *cmds)
12757 {
12758   struct remote_state *rs = get_remote_state ();
12759   struct command_line *cmd;
12760
12761   for (cmd = cmds; cmd; cmd = cmd->next)
12762     {
12763       QUIT;     /* Allow user to bail out with ^C.  */
12764       strcpy (rs->buf, "QTDPsrc:");
12765       encode_source_string (num, addr, "cmd", cmd->line,
12766                             rs->buf + strlen (rs->buf),
12767                             rs->buf_size - strlen (rs->buf));
12768       putpkt (rs->buf);
12769       remote_get_noisy_reply ();
12770       if (strcmp (rs->buf, "OK"))
12771         warning (_("Target does not support source download."));
12772
12773       if (cmd->control_type == while_control
12774           || cmd->control_type == while_stepping_control)
12775         {
12776           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12777
12778           QUIT; /* Allow user to bail out with ^C.  */
12779           strcpy (rs->buf, "QTDPsrc:");
12780           encode_source_string (num, addr, "cmd", "end",
12781                                 rs->buf + strlen (rs->buf),
12782                                 rs->buf_size - strlen (rs->buf));
12783           putpkt (rs->buf);
12784           remote_get_noisy_reply ();
12785           if (strcmp (rs->buf, "OK"))
12786             warning (_("Target does not support source download."));
12787         }
12788     }
12789 }
12790
12791 void
12792 remote_target::download_tracepoint (struct bp_location *loc)
12793 {
12794 #define BUF_SIZE 2048
12795
12796   CORE_ADDR tpaddr;
12797   char addrbuf[40];
12798   char buf[BUF_SIZE];
12799   std::vector<std::string> tdp_actions;
12800   std::vector<std::string> stepping_actions;
12801   char *pkt;
12802   struct breakpoint *b = loc->owner;
12803   struct tracepoint *t = (struct tracepoint *) b;
12804   struct remote_state *rs = get_remote_state ();
12805
12806   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12807
12808   tpaddr = loc->address;
12809   sprintf_vma (addrbuf, tpaddr);
12810   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12811              addrbuf, /* address */
12812              (b->enable_state == bp_enabled ? 'E' : 'D'),
12813              t->step_count, t->pass_count);
12814   /* Fast tracepoints are mostly handled by the target, but we can
12815      tell the target how big of an instruction block should be moved
12816      around.  */
12817   if (b->type == bp_fast_tracepoint)
12818     {
12819       /* Only test for support at download time; we may not know
12820          target capabilities at definition time.  */
12821       if (remote_supports_fast_tracepoints ())
12822         {
12823           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12824                                                 NULL))
12825             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12826                        gdb_insn_length (loc->gdbarch, tpaddr));
12827           else
12828             /* If it passed validation at definition but fails now,
12829                something is very wrong.  */
12830             internal_error (__FILE__, __LINE__,
12831                             _("Fast tracepoint not "
12832                               "valid during download"));
12833         }
12834       else
12835         /* Fast tracepoints are functionally identical to regular
12836            tracepoints, so don't take lack of support as a reason to
12837            give up on the trace run.  */
12838         warning (_("Target does not support fast tracepoints, "
12839                    "downloading %d as regular tracepoint"), b->number);
12840     }
12841   else if (b->type == bp_static_tracepoint)
12842     {
12843       /* Only test for support at download time; we may not know
12844          target capabilities at definition time.  */
12845       if (remote_supports_static_tracepoints ())
12846         {
12847           struct static_tracepoint_marker marker;
12848
12849           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12850             strcat (buf, ":S");
12851           else
12852             error (_("Static tracepoint not valid during download"));
12853         }
12854       else
12855         /* Fast tracepoints are functionally identical to regular
12856            tracepoints, so don't take lack of support as a reason
12857            to give up on the trace run.  */
12858         error (_("Target does not support static tracepoints"));
12859     }
12860   /* If the tracepoint has a conditional, make it into an agent
12861      expression and append to the definition.  */
12862   if (loc->cond)
12863     {
12864       /* Only test support at download time, we may not know target
12865          capabilities at definition time.  */
12866       if (remote_supports_cond_tracepoints ())
12867         {
12868           agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
12869           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
12870                      aexpr->len);
12871           pkt = buf + strlen (buf);
12872           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12873             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12874           *pkt = '\0';
12875         }
12876       else
12877         warning (_("Target does not support conditional tracepoints, "
12878                    "ignoring tp %d cond"), b->number);
12879     }
12880
12881   if (b->commands || *default_collect)
12882     strcat (buf, "-");
12883   putpkt (buf);
12884   remote_get_noisy_reply ();
12885   if (strcmp (rs->buf, "OK"))
12886     error (_("Target does not support tracepoints."));
12887
12888   /* do_single_steps (t); */
12889   for (auto action_it = tdp_actions.begin ();
12890        action_it != tdp_actions.end (); action_it++)
12891     {
12892       QUIT;     /* Allow user to bail out with ^C.  */
12893
12894       bool has_more = (action_it != tdp_actions.end ()
12895                        || !stepping_actions.empty ());
12896
12897       xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
12898                  b->number, addrbuf, /* address */
12899                  action_it->c_str (),
12900                  has_more ? '-' : 0);
12901       putpkt (buf);
12902       remote_get_noisy_reply ();
12903       if (strcmp (rs->buf, "OK"))
12904         error (_("Error on target while setting tracepoints."));
12905     }
12906
12907     for (auto action_it = stepping_actions.begin ();
12908          action_it != stepping_actions.end (); action_it++)
12909       {
12910         QUIT;   /* Allow user to bail out with ^C.  */
12911
12912         bool is_first = action_it == stepping_actions.begin ();
12913         bool has_more = action_it != stepping_actions.end ();
12914
12915         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
12916                    b->number, addrbuf, /* address */
12917                    is_first ? "S" : "",
12918                    action_it->c_str (),
12919                    has_more ? "-" : "");
12920         putpkt (buf);
12921         remote_get_noisy_reply ();
12922         if (strcmp (rs->buf, "OK"))
12923           error (_("Error on target while setting tracepoints."));
12924       }
12925
12926   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12927     {
12928       if (b->location != NULL)
12929         {
12930           strcpy (buf, "QTDPsrc:");
12931           encode_source_string (b->number, loc->address, "at",
12932                                 event_location_to_string (b->location.get ()),
12933                                 buf + strlen (buf), 2048 - strlen (buf));
12934           putpkt (buf);
12935           remote_get_noisy_reply ();
12936           if (strcmp (rs->buf, "OK"))
12937             warning (_("Target does not support source download."));
12938         }
12939       if (b->cond_string)
12940         {
12941           strcpy (buf, "QTDPsrc:");
12942           encode_source_string (b->number, loc->address,
12943                                 "cond", b->cond_string, buf + strlen (buf),
12944                                 2048 - strlen (buf));
12945           putpkt (buf);
12946           remote_get_noisy_reply ();
12947           if (strcmp (rs->buf, "OK"))
12948             warning (_("Target does not support source download."));
12949         }
12950       remote_download_command_source (b->number, loc->address,
12951                                       breakpoint_commands (b));
12952     }
12953 }
12954
12955 bool
12956 remote_target::can_download_tracepoint ()
12957 {
12958   struct remote_state *rs = get_remote_state ();
12959   struct trace_status *ts;
12960   int status;
12961
12962   /* Don't try to install tracepoints until we've relocated our
12963      symbols, and fetched and merged the target's tracepoint list with
12964      ours.  */
12965   if (rs->starting_up)
12966     return false;
12967
12968   ts = current_trace_status ();
12969   status = get_trace_status (ts);
12970
12971   if (status == -1 || !ts->running_known || !ts->running)
12972     return false;
12973
12974   /* If we are in a tracing experiment, but remote stub doesn't support
12975      installing tracepoint in trace, we have to return.  */
12976   if (!remote_supports_install_in_trace ())
12977     return false;
12978
12979   return true;
12980 }
12981
12982
12983 void
12984 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
12985 {
12986   struct remote_state *rs = get_remote_state ();
12987   char *p;
12988
12989   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
12990              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
12991              tsv.builtin);
12992   p = rs->buf + strlen (rs->buf);
12993   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
12994     error (_("Trace state variable name too long for tsv definition packet"));
12995   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
12996   *p++ = '\0';
12997   putpkt (rs->buf);
12998   remote_get_noisy_reply ();
12999   if (*rs->buf == '\0')
13000     error (_("Target does not support this command."));
13001   if (strcmp (rs->buf, "OK") != 0)
13002     error (_("Error on target while downloading trace state variable."));
13003 }
13004
13005 void
13006 remote_target::enable_tracepoint (struct bp_location *location)
13007 {
13008   struct remote_state *rs = get_remote_state ();
13009   char addr_buf[40];
13010
13011   sprintf_vma (addr_buf, location->address);
13012   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13013              location->owner->number, addr_buf);
13014   putpkt (rs->buf);
13015   remote_get_noisy_reply ();
13016   if (*rs->buf == '\0')
13017     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13018   if (strcmp (rs->buf, "OK") != 0)
13019     error (_("Error on target while enabling tracepoint."));
13020 }
13021
13022 void
13023 remote_target::disable_tracepoint (struct bp_location *location)
13024 {
13025   struct remote_state *rs = get_remote_state ();
13026   char addr_buf[40];
13027
13028   sprintf_vma (addr_buf, location->address);
13029   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13030              location->owner->number, addr_buf);
13031   putpkt (rs->buf);
13032   remote_get_noisy_reply ();
13033   if (*rs->buf == '\0')
13034     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13035   if (strcmp (rs->buf, "OK") != 0)
13036     error (_("Error on target while disabling tracepoint."));
13037 }
13038
13039 void
13040 remote_target::trace_set_readonly_regions ()
13041 {
13042   asection *s;
13043   bfd *abfd = NULL;
13044   bfd_size_type size;
13045   bfd_vma vma;
13046   int anysecs = 0;
13047   int offset = 0;
13048
13049   if (!exec_bfd)
13050     return;                     /* No information to give.  */
13051
13052   struct remote_state *rs = get_remote_state ();
13053
13054   strcpy (rs->buf, "QTro");
13055   offset = strlen (rs->buf);
13056   for (s = exec_bfd->sections; s; s = s->next)
13057     {
13058       char tmp1[40], tmp2[40];
13059       int sec_length;
13060
13061       if ((s->flags & SEC_LOAD) == 0 ||
13062       /*  (s->flags & SEC_CODE) == 0 || */
13063           (s->flags & SEC_READONLY) == 0)
13064         continue;
13065
13066       anysecs = 1;
13067       vma = bfd_get_section_vma (abfd, s);
13068       size = bfd_get_section_size (s);
13069       sprintf_vma (tmp1, vma);
13070       sprintf_vma (tmp2, vma + size);
13071       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13072       if (offset + sec_length + 1 > rs->buf_size)
13073         {
13074           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13075             warning (_("\
13076 Too many sections for read-only sections definition packet."));
13077           break;
13078         }
13079       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13080                  tmp1, tmp2);
13081       offset += sec_length;
13082     }
13083   if (anysecs)
13084     {
13085       putpkt (rs->buf);
13086       getpkt (&rs->buf, &rs->buf_size, 0);
13087     }
13088 }
13089
13090 void
13091 remote_target::trace_start ()
13092 {
13093   struct remote_state *rs = get_remote_state ();
13094
13095   putpkt ("QTStart");
13096   remote_get_noisy_reply ();
13097   if (*rs->buf == '\0')
13098     error (_("Target does not support this command."));
13099   if (strcmp (rs->buf, "OK") != 0)
13100     error (_("Bogus reply from target: %s"), rs->buf);
13101 }
13102
13103 int
13104 remote_target::get_trace_status (struct trace_status *ts)
13105 {
13106   /* Initialize it just to avoid a GCC false warning.  */
13107   char *p = NULL;
13108   /* FIXME we need to get register block size some other way.  */
13109   extern int trace_regblock_size;
13110   enum packet_result result;
13111   struct remote_state *rs = get_remote_state ();
13112
13113   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13114     return -1;
13115
13116   trace_regblock_size
13117     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13118
13119   putpkt ("qTStatus");
13120
13121   TRY
13122     {
13123       p = remote_get_noisy_reply ();
13124     }
13125   CATCH (ex, RETURN_MASK_ERROR)
13126     {
13127       if (ex.error != TARGET_CLOSE_ERROR)
13128         {
13129           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13130           return -1;
13131         }
13132       throw_exception (ex);
13133     }
13134   END_CATCH
13135
13136   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13137
13138   /* If the remote target doesn't do tracing, flag it.  */
13139   if (result == PACKET_UNKNOWN)
13140     return -1;
13141
13142   /* We're working with a live target.  */
13143   ts->filename = NULL;
13144
13145   if (*p++ != 'T')
13146     error (_("Bogus trace status reply from target: %s"), rs->buf);
13147
13148   /* Function 'parse_trace_status' sets default value of each field of
13149      'ts' at first, so we don't have to do it here.  */
13150   parse_trace_status (p, ts);
13151
13152   return ts->running;
13153 }
13154
13155 void
13156 remote_target::get_tracepoint_status (struct breakpoint *bp,
13157                                       struct uploaded_tp *utp)
13158 {
13159   struct remote_state *rs = get_remote_state ();
13160   char *reply;
13161   struct bp_location *loc;
13162   struct tracepoint *tp = (struct tracepoint *) bp;
13163   size_t size = get_remote_packet_size ();
13164
13165   if (tp)
13166     {
13167       tp->hit_count = 0;
13168       tp->traceframe_usage = 0;
13169       for (loc = tp->loc; loc; loc = loc->next)
13170         {
13171           /* If the tracepoint was never downloaded, don't go asking for
13172              any status.  */
13173           if (tp->number_on_target == 0)
13174             continue;
13175           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13176                      phex_nz (loc->address, 0));
13177           putpkt (rs->buf);
13178           reply = remote_get_noisy_reply ();
13179           if (reply && *reply)
13180             {
13181               if (*reply == 'V')
13182                 parse_tracepoint_status (reply + 1, bp, utp);
13183             }
13184         }
13185     }
13186   else if (utp)
13187     {
13188       utp->hit_count = 0;
13189       utp->traceframe_usage = 0;
13190       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13191                  phex_nz (utp->addr, 0));
13192       putpkt (rs->buf);
13193       reply = remote_get_noisy_reply ();
13194       if (reply && *reply)
13195         {
13196           if (*reply == 'V')
13197             parse_tracepoint_status (reply + 1, bp, utp);
13198         }
13199     }
13200 }
13201
13202 void
13203 remote_target::trace_stop ()
13204 {
13205   struct remote_state *rs = get_remote_state ();
13206
13207   putpkt ("QTStop");
13208   remote_get_noisy_reply ();
13209   if (*rs->buf == '\0')
13210     error (_("Target does not support this command."));
13211   if (strcmp (rs->buf, "OK") != 0)
13212     error (_("Bogus reply from target: %s"), rs->buf);
13213 }
13214
13215 int
13216 remote_target::trace_find (enum trace_find_type type, int num,
13217                            CORE_ADDR addr1, CORE_ADDR addr2,
13218                            int *tpp)
13219 {
13220   struct remote_state *rs = get_remote_state ();
13221   char *endbuf = rs->buf + get_remote_packet_size ();
13222   char *p, *reply;
13223   int target_frameno = -1, target_tracept = -1;
13224
13225   /* Lookups other than by absolute frame number depend on the current
13226      trace selected, so make sure it is correct on the remote end
13227      first.  */
13228   if (type != tfind_number)
13229     set_remote_traceframe ();
13230
13231   p = rs->buf;
13232   strcpy (p, "QTFrame:");
13233   p = strchr (p, '\0');
13234   switch (type)
13235     {
13236     case tfind_number:
13237       xsnprintf (p, endbuf - p, "%x", num);
13238       break;
13239     case tfind_pc:
13240       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13241       break;
13242     case tfind_tp:
13243       xsnprintf (p, endbuf - p, "tdp:%x", num);
13244       break;
13245     case tfind_range:
13246       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13247                  phex_nz (addr2, 0));
13248       break;
13249     case tfind_outside:
13250       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13251                  phex_nz (addr2, 0));
13252       break;
13253     default:
13254       error (_("Unknown trace find type %d"), type);
13255     }
13256
13257   putpkt (rs->buf);
13258   reply = remote_get_noisy_reply ();
13259   if (*reply == '\0')
13260     error (_("Target does not support this command."));
13261
13262   while (reply && *reply)
13263     switch (*reply)
13264       {
13265       case 'F':
13266         p = ++reply;
13267         target_frameno = (int) strtol (p, &reply, 16);
13268         if (reply == p)
13269           error (_("Unable to parse trace frame number"));
13270         /* Don't update our remote traceframe number cache on failure
13271            to select a remote traceframe.  */
13272         if (target_frameno == -1)
13273           return -1;
13274         break;
13275       case 'T':
13276         p = ++reply;
13277         target_tracept = (int) strtol (p, &reply, 16);
13278         if (reply == p)
13279           error (_("Unable to parse tracepoint number"));
13280         break;
13281       case 'O':         /* "OK"? */
13282         if (reply[1] == 'K' && reply[2] == '\0')
13283           reply += 2;
13284         else
13285           error (_("Bogus reply from target: %s"), reply);
13286         break;
13287       default:
13288         error (_("Bogus reply from target: %s"), reply);
13289       }
13290   if (tpp)
13291     *tpp = target_tracept;
13292
13293   rs->remote_traceframe_number = target_frameno;
13294   return target_frameno;
13295 }
13296
13297 bool
13298 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13299 {
13300   struct remote_state *rs = get_remote_state ();
13301   char *reply;
13302   ULONGEST uval;
13303
13304   set_remote_traceframe ();
13305
13306   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13307   putpkt (rs->buf);
13308   reply = remote_get_noisy_reply ();
13309   if (reply && *reply)
13310     {
13311       if (*reply == 'V')
13312         {
13313           unpack_varlen_hex (reply + 1, &uval);
13314           *val = (LONGEST) uval;
13315           return true;
13316         }
13317     }
13318   return false;
13319 }
13320
13321 int
13322 remote_target::save_trace_data (const char *filename)
13323 {
13324   struct remote_state *rs = get_remote_state ();
13325   char *p, *reply;
13326
13327   p = rs->buf;
13328   strcpy (p, "QTSave:");
13329   p += strlen (p);
13330   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13331     error (_("Remote file name too long for trace save packet"));
13332   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13333   *p++ = '\0';
13334   putpkt (rs->buf);
13335   reply = remote_get_noisy_reply ();
13336   if (*reply == '\0')
13337     error (_("Target does not support this command."));
13338   if (strcmp (reply, "OK") != 0)
13339     error (_("Bogus reply from target: %s"), reply);
13340   return 0;
13341 }
13342
13343 /* This is basically a memory transfer, but needs to be its own packet
13344    because we don't know how the target actually organizes its trace
13345    memory, plus we want to be able to ask for as much as possible, but
13346    not be unhappy if we don't get as much as we ask for.  */
13347
13348 LONGEST
13349 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13350 {
13351   struct remote_state *rs = get_remote_state ();
13352   char *reply;
13353   char *p;
13354   int rslt;
13355
13356   p = rs->buf;
13357   strcpy (p, "qTBuffer:");
13358   p += strlen (p);
13359   p += hexnumstr (p, offset);
13360   *p++ = ',';
13361   p += hexnumstr (p, len);
13362   *p++ = '\0';
13363
13364   putpkt (rs->buf);
13365   reply = remote_get_noisy_reply ();
13366   if (reply && *reply)
13367     {
13368       /* 'l' by itself means we're at the end of the buffer and
13369          there is nothing more to get.  */
13370       if (*reply == 'l')
13371         return 0;
13372
13373       /* Convert the reply into binary.  Limit the number of bytes to
13374          convert according to our passed-in buffer size, rather than
13375          what was returned in the packet; if the target is
13376          unexpectedly generous and gives us a bigger reply than we
13377          asked for, we don't want to crash.  */
13378       rslt = hex2bin (reply, buf, len);
13379       return rslt;
13380     }
13381
13382   /* Something went wrong, flag as an error.  */
13383   return -1;
13384 }
13385
13386 void
13387 remote_target::set_disconnected_tracing (int val)
13388 {
13389   struct remote_state *rs = get_remote_state ();
13390
13391   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13392     {
13393       char *reply;
13394
13395       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13396       putpkt (rs->buf);
13397       reply = remote_get_noisy_reply ();
13398       if (*reply == '\0')
13399         error (_("Target does not support this command."));
13400       if (strcmp (reply, "OK") != 0)
13401         error (_("Bogus reply from target: %s"), reply);
13402     }
13403   else if (val)
13404     warning (_("Target does not support disconnected tracing."));
13405 }
13406
13407 int
13408 remote_target::core_of_thread (ptid_t ptid)
13409 {
13410   struct thread_info *info = find_thread_ptid (ptid);
13411
13412   if (info != NULL && info->priv != NULL)
13413     return get_remote_thread_info (info)->core;
13414
13415   return -1;
13416 }
13417
13418 void
13419 remote_target::set_circular_trace_buffer (int val)
13420 {
13421   struct remote_state *rs = get_remote_state ();
13422   char *reply;
13423
13424   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13425   putpkt (rs->buf);
13426   reply = remote_get_noisy_reply ();
13427   if (*reply == '\0')
13428     error (_("Target does not support this command."));
13429   if (strcmp (reply, "OK") != 0)
13430     error (_("Bogus reply from target: %s"), reply);
13431 }
13432
13433 traceframe_info_up
13434 remote_target::traceframe_info ()
13435 {
13436   gdb::optional<gdb::char_vector> text
13437     = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13438                             NULL);
13439   if (text)
13440     return parse_traceframe_info (text->data ());
13441
13442   return NULL;
13443 }
13444
13445 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13446    instruction on which a fast tracepoint may be placed.  Returns -1
13447    if the packet is not supported, and 0 if the minimum instruction
13448    length is unknown.  */
13449
13450 int
13451 remote_target::get_min_fast_tracepoint_insn_len ()
13452 {
13453   struct remote_state *rs = get_remote_state ();
13454   char *reply;
13455
13456   /* If we're not debugging a process yet, the IPA can't be
13457      loaded.  */
13458   if (!target_has_execution)
13459     return 0;
13460
13461   /* Make sure the remote is pointing at the right process.  */
13462   set_general_process ();
13463
13464   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13465   putpkt (rs->buf);
13466   reply = remote_get_noisy_reply ();
13467   if (*reply == '\0')
13468     return -1;
13469   else
13470     {
13471       ULONGEST min_insn_len;
13472
13473       unpack_varlen_hex (reply, &min_insn_len);
13474
13475       return (int) min_insn_len;
13476     }
13477 }
13478
13479 void
13480 remote_target::set_trace_buffer_size (LONGEST val)
13481 {
13482   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13483     {
13484       struct remote_state *rs = get_remote_state ();
13485       char *buf = rs->buf;
13486       char *endbuf = rs->buf + get_remote_packet_size ();
13487       enum packet_result result;
13488
13489       gdb_assert (val >= 0 || val == -1);
13490       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13491       /* Send -1 as literal "-1" to avoid host size dependency.  */
13492       if (val < 0)
13493         {
13494           *buf++ = '-';
13495           buf += hexnumstr (buf, (ULONGEST) -val);
13496         }
13497       else
13498         buf += hexnumstr (buf, (ULONGEST) val);
13499
13500       putpkt (rs->buf);
13501       remote_get_noisy_reply ();
13502       result = packet_ok (rs->buf,
13503                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13504
13505       if (result != PACKET_OK)
13506         warning (_("Bogus reply from target: %s"), rs->buf);
13507     }
13508 }
13509
13510 bool
13511 remote_target::set_trace_notes (const char *user, const char *notes,
13512                                 const char *stop_notes)
13513 {
13514   struct remote_state *rs = get_remote_state ();
13515   char *reply;
13516   char *buf = rs->buf;
13517   char *endbuf = rs->buf + get_remote_packet_size ();
13518   int nbytes;
13519
13520   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13521   if (user)
13522     {
13523       buf += xsnprintf (buf, endbuf - buf, "user:");
13524       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13525       buf += 2 * nbytes;
13526       *buf++ = ';';
13527     }
13528   if (notes)
13529     {
13530       buf += xsnprintf (buf, endbuf - buf, "notes:");
13531       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13532       buf += 2 * nbytes;
13533       *buf++ = ';';
13534     }
13535   if (stop_notes)
13536     {
13537       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13538       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13539       buf += 2 * nbytes;
13540       *buf++ = ';';
13541     }
13542   /* Ensure the buffer is terminated.  */
13543   *buf = '\0';
13544
13545   putpkt (rs->buf);
13546   reply = remote_get_noisy_reply ();
13547   if (*reply == '\0')
13548     return false;
13549
13550   if (strcmp (reply, "OK") != 0)
13551     error (_("Bogus reply from target: %s"), reply);
13552
13553   return true;
13554 }
13555
13556 bool
13557 remote_target::use_agent (bool use)
13558 {
13559   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13560     {
13561       struct remote_state *rs = get_remote_state ();
13562
13563       /* If the stub supports QAgent.  */
13564       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13565       putpkt (rs->buf);
13566       getpkt (&rs->buf, &rs->buf_size, 0);
13567
13568       if (strcmp (rs->buf, "OK") == 0)
13569         {
13570           ::use_agent = use;
13571           return true;
13572         }
13573     }
13574
13575   return false;
13576 }
13577
13578 bool
13579 remote_target::can_use_agent ()
13580 {
13581   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13582 }
13583
13584 struct btrace_target_info
13585 {
13586   /* The ptid of the traced thread.  */
13587   ptid_t ptid;
13588
13589   /* The obtained branch trace configuration.  */
13590   struct btrace_config conf;
13591 };
13592
13593 /* Reset our idea of our target's btrace configuration.  */
13594
13595 static void
13596 remote_btrace_reset (remote_state *rs)
13597 {
13598   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13599 }
13600
13601 /* Synchronize the configuration with the target.  */
13602
13603 void
13604 remote_target::btrace_sync_conf (const btrace_config *conf)
13605 {
13606   struct packet_config *packet;
13607   struct remote_state *rs;
13608   char *buf, *pos, *endbuf;
13609
13610   rs = get_remote_state ();
13611   buf = rs->buf;
13612   endbuf = buf + get_remote_packet_size ();
13613
13614   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13615   if (packet_config_support (packet) == PACKET_ENABLE
13616       && conf->bts.size != rs->btrace_config.bts.size)
13617     {
13618       pos = buf;
13619       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13620                         conf->bts.size);
13621
13622       putpkt (buf);
13623       getpkt (&buf, &rs->buf_size, 0);
13624
13625       if (packet_ok (buf, packet) == PACKET_ERROR)
13626         {
13627           if (buf[0] == 'E' && buf[1] == '.')
13628             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13629           else
13630             error (_("Failed to configure the BTS buffer size."));
13631         }
13632
13633       rs->btrace_config.bts.size = conf->bts.size;
13634     }
13635
13636   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13637   if (packet_config_support (packet) == PACKET_ENABLE
13638       && conf->pt.size != rs->btrace_config.pt.size)
13639     {
13640       pos = buf;
13641       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13642                         conf->pt.size);
13643
13644       putpkt (buf);
13645       getpkt (&buf, &rs->buf_size, 0);
13646
13647       if (packet_ok (buf, packet) == PACKET_ERROR)
13648         {
13649           if (buf[0] == 'E' && buf[1] == '.')
13650             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13651           else
13652             error (_("Failed to configure the trace buffer size."));
13653         }
13654
13655       rs->btrace_config.pt.size = conf->pt.size;
13656     }
13657 }
13658
13659 /* Read the current thread's btrace configuration from the target and
13660    store it into CONF.  */
13661
13662 static void
13663 btrace_read_config (struct btrace_config *conf)
13664 {
13665   gdb::optional<gdb::char_vector> xml
13666     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13667   if (xml)
13668     parse_xml_btrace_conf (conf, xml->data ());
13669 }
13670
13671 /* Maybe reopen target btrace.  */
13672
13673 void
13674 remote_target::remote_btrace_maybe_reopen ()
13675 {
13676   struct remote_state *rs = get_remote_state ();
13677   struct thread_info *tp;
13678   int btrace_target_pushed = 0;
13679   int warned = 0;
13680
13681   scoped_restore_current_thread restore_thread;
13682
13683   ALL_NON_EXITED_THREADS (tp)
13684     {
13685       set_general_thread (tp->ptid);
13686
13687       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13688       btrace_read_config (&rs->btrace_config);
13689
13690       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13691         continue;
13692
13693 #if !defined (HAVE_LIBIPT)
13694       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13695         {
13696           if (!warned)
13697             {
13698               warned = 1;
13699               warning (_("Target is recording using Intel Processor Trace "
13700                          "but support was disabled at compile time."));
13701             }
13702
13703           continue;
13704         }
13705 #endif /* !defined (HAVE_LIBIPT) */
13706
13707       /* Push target, once, but before anything else happens.  This way our
13708          changes to the threads will be cleaned up by unpushing the target
13709          in case btrace_read_config () throws.  */
13710       if (!btrace_target_pushed)
13711         {
13712           btrace_target_pushed = 1;
13713           record_btrace_push_target ();
13714           printf_filtered (_("Target is recording using %s.\n"),
13715                            btrace_format_string (rs->btrace_config.format));
13716         }
13717
13718       tp->btrace.target = XCNEW (struct btrace_target_info);
13719       tp->btrace.target->ptid = tp->ptid;
13720       tp->btrace.target->conf = rs->btrace_config;
13721     }
13722 }
13723
13724 /* Enable branch tracing.  */
13725
13726 struct btrace_target_info *
13727 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13728 {
13729   struct btrace_target_info *tinfo = NULL;
13730   struct packet_config *packet = NULL;
13731   struct remote_state *rs = get_remote_state ();
13732   char *buf = rs->buf;
13733   char *endbuf = rs->buf + get_remote_packet_size ();
13734
13735   switch (conf->format)
13736     {
13737       case BTRACE_FORMAT_BTS:
13738         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13739         break;
13740
13741       case BTRACE_FORMAT_PT:
13742         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13743         break;
13744     }
13745
13746   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13747     error (_("Target does not support branch tracing."));
13748
13749   btrace_sync_conf (conf);
13750
13751   set_general_thread (ptid);
13752
13753   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13754   putpkt (rs->buf);
13755   getpkt (&rs->buf, &rs->buf_size, 0);
13756
13757   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13758     {
13759       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13760         error (_("Could not enable branch tracing for %s: %s"),
13761                target_pid_to_str (ptid), rs->buf + 2);
13762       else
13763         error (_("Could not enable branch tracing for %s."),
13764                target_pid_to_str (ptid));
13765     }
13766
13767   tinfo = XCNEW (struct btrace_target_info);
13768   tinfo->ptid = ptid;
13769
13770   /* If we fail to read the configuration, we lose some information, but the
13771      tracing itself is not impacted.  */
13772   TRY
13773     {
13774       btrace_read_config (&tinfo->conf);
13775     }
13776   CATCH (err, RETURN_MASK_ERROR)
13777     {
13778       if (err.message != NULL)
13779         warning ("%s", err.message);
13780     }
13781   END_CATCH
13782
13783   return tinfo;
13784 }
13785
13786 /* Disable branch tracing.  */
13787
13788 void
13789 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13790 {
13791   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13792   struct remote_state *rs = get_remote_state ();
13793   char *buf = rs->buf;
13794   char *endbuf = rs->buf + get_remote_packet_size ();
13795
13796   if (packet_config_support (packet) != PACKET_ENABLE)
13797     error (_("Target does not support branch tracing."));
13798
13799   set_general_thread (tinfo->ptid);
13800
13801   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13802   putpkt (rs->buf);
13803   getpkt (&rs->buf, &rs->buf_size, 0);
13804
13805   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13806     {
13807       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13808         error (_("Could not disable branch tracing for %s: %s"),
13809                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13810       else
13811         error (_("Could not disable branch tracing for %s."),
13812                target_pid_to_str (tinfo->ptid));
13813     }
13814
13815   xfree (tinfo);
13816 }
13817
13818 /* Teardown branch tracing.  */
13819
13820 void
13821 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13822 {
13823   /* We must not talk to the target during teardown.  */
13824   xfree (tinfo);
13825 }
13826
13827 /* Read the branch trace.  */
13828
13829 enum btrace_error
13830 remote_target::read_btrace (struct btrace_data *btrace,
13831                             struct btrace_target_info *tinfo,
13832                             enum btrace_read_type type)
13833 {
13834   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13835   const char *annex;
13836
13837   if (packet_config_support (packet) != PACKET_ENABLE)
13838     error (_("Target does not support branch tracing."));
13839
13840 #if !defined(HAVE_LIBEXPAT)
13841   error (_("Cannot process branch tracing result. XML parsing not supported."));
13842 #endif
13843
13844   switch (type)
13845     {
13846     case BTRACE_READ_ALL:
13847       annex = "all";
13848       break;
13849     case BTRACE_READ_NEW:
13850       annex = "new";
13851       break;
13852     case BTRACE_READ_DELTA:
13853       annex = "delta";
13854       break;
13855     default:
13856       internal_error (__FILE__, __LINE__,
13857                       _("Bad branch tracing read type: %u."),
13858                       (unsigned int) type);
13859     }
13860
13861   gdb::optional<gdb::char_vector> xml
13862     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13863   if (!xml)
13864     return BTRACE_ERR_UNKNOWN;
13865
13866   parse_xml_btrace (btrace, xml->data ());
13867
13868   return BTRACE_ERR_NONE;
13869 }
13870
13871 const struct btrace_config *
13872 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13873 {
13874   return &tinfo->conf;
13875 }
13876
13877 bool
13878 remote_target::augmented_libraries_svr4_read ()
13879 {
13880   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13881           == PACKET_ENABLE);
13882 }
13883
13884 /* Implementation of to_load.  */
13885
13886 void
13887 remote_target::load (const char *name, int from_tty)
13888 {
13889   generic_load (name, from_tty);
13890 }
13891
13892 /* Accepts an integer PID; returns a string representing a file that
13893    can be opened on the remote side to get the symbols for the child
13894    process.  Returns NULL if the operation is not supported.  */
13895
13896 char *
13897 remote_target::pid_to_exec_file (int pid)
13898 {
13899   static gdb::optional<gdb::char_vector> filename;
13900   struct inferior *inf;
13901   char *annex = NULL;
13902
13903   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13904     return NULL;
13905
13906   inf = find_inferior_pid (pid);
13907   if (inf == NULL)
13908     internal_error (__FILE__, __LINE__,
13909                     _("not currently attached to process %d"), pid);
13910
13911   if (!inf->fake_pid_p)
13912     {
13913       const int annex_size = 9;
13914
13915       annex = (char *) alloca (annex_size);
13916       xsnprintf (annex, annex_size, "%x", pid);
13917     }
13918
13919   filename = target_read_stralloc (current_top_target (),
13920                                    TARGET_OBJECT_EXEC_FILE, annex);
13921
13922   return filename ? filename->data () : nullptr;
13923 }
13924
13925 /* Implement the to_can_do_single_step target_ops method.  */
13926
13927 int
13928 remote_target::can_do_single_step ()
13929 {
13930   /* We can only tell whether target supports single step or not by
13931      supported s and S vCont actions if the stub supports vContSupported
13932      feature.  If the stub doesn't support vContSupported feature,
13933      we have conservatively to think target doesn't supports single
13934      step.  */
13935   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13936     {
13937       struct remote_state *rs = get_remote_state ();
13938
13939       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13940         remote_vcont_probe ();
13941
13942       return rs->supports_vCont.s && rs->supports_vCont.S;
13943     }
13944   else
13945     return 0;
13946 }
13947
13948 /* Implementation of the to_execution_direction method for the remote
13949    target.  */
13950
13951 enum exec_direction_kind
13952 remote_target::execution_direction ()
13953 {
13954   struct remote_state *rs = get_remote_state ();
13955
13956   return rs->last_resume_exec_dir;
13957 }
13958
13959 /* Return pointer to the thread_info struct which corresponds to
13960    THREAD_HANDLE (having length HANDLE_LEN).  */
13961
13962 thread_info *
13963 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13964                                              int handle_len,
13965                                              inferior *inf)
13966 {
13967   struct thread_info *tp;
13968
13969   ALL_NON_EXITED_THREADS (tp)
13970     {
13971       remote_thread_info *priv = get_remote_thread_info (tp);
13972
13973       if (tp->inf == inf && priv != NULL)
13974         {
13975           if (handle_len != priv->thread_handle.size ())
13976             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
13977                    handle_len, priv->thread_handle.size ());
13978           if (memcmp (thread_handle, priv->thread_handle.data (),
13979                       handle_len) == 0)
13980             return tp;
13981         }
13982     }
13983
13984   return NULL;
13985 }
13986
13987 bool
13988 remote_target::can_async_p ()
13989 {
13990   struct remote_state *rs = get_remote_state ();
13991
13992   /* We don't go async if the user has explicitly prevented it with the
13993      "maint set target-async" command.  */
13994   if (!target_async_permitted)
13995     return false;
13996
13997   /* We're async whenever the serial device is.  */
13998   return serial_can_async_p (rs->remote_desc);
13999 }
14000
14001 bool
14002 remote_target::is_async_p ()
14003 {
14004   struct remote_state *rs = get_remote_state ();
14005
14006   if (!target_async_permitted)
14007     /* We only enable async when the user specifically asks for it.  */
14008     return false;
14009
14010   /* We're async whenever the serial device is.  */
14011   return serial_is_async_p (rs->remote_desc);
14012 }
14013
14014 /* Pass the SERIAL event on and up to the client.  One day this code
14015    will be able to delay notifying the client of an event until the
14016    point where an entire packet has been received.  */
14017
14018 static serial_event_ftype remote_async_serial_handler;
14019
14020 static void
14021 remote_async_serial_handler (struct serial *scb, void *context)
14022 {
14023   /* Don't propogate error information up to the client.  Instead let
14024      the client find out about the error by querying the target.  */
14025   inferior_event_handler (INF_REG_EVENT, NULL);
14026 }
14027
14028 static void
14029 remote_async_inferior_event_handler (gdb_client_data data)
14030 {
14031   inferior_event_handler (INF_REG_EVENT, data);
14032 }
14033
14034 void
14035 remote_target::async (int enable)
14036 {
14037   struct remote_state *rs = get_remote_state ();
14038
14039   if (enable)
14040     {
14041       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14042
14043       /* If there are pending events in the stop reply queue tell the
14044          event loop to process them.  */
14045       if (!rs->stop_reply_queue.empty ())
14046         mark_async_event_handler (rs->remote_async_inferior_event_token);
14047       /* For simplicity, below we clear the pending events token
14048          without remembering whether it is marked, so here we always
14049          mark it.  If there's actually no pending notification to
14050          process, this ends up being a no-op (other than a spurious
14051          event-loop wakeup).  */
14052       if (target_is_non_stop_p ())
14053         mark_async_event_handler (rs->notif_state->get_pending_events_token);
14054     }
14055   else
14056     {
14057       serial_async (rs->remote_desc, NULL, NULL);
14058       /* If the core is disabling async, it doesn't want to be
14059          disturbed with target events.  Clear all async event sources
14060          too.  */
14061       clear_async_event_handler (rs->remote_async_inferior_event_token);
14062       if (target_is_non_stop_p ())
14063         clear_async_event_handler (rs->notif_state->get_pending_events_token);
14064     }
14065 }
14066
14067 /* Implementation of the to_thread_events method.  */
14068
14069 void
14070 remote_target::thread_events (int enable)
14071 {
14072   struct remote_state *rs = get_remote_state ();
14073   size_t size = get_remote_packet_size ();
14074
14075   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14076     return;
14077
14078   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14079   putpkt (rs->buf);
14080   getpkt (&rs->buf, &rs->buf_size, 0);
14081
14082   switch (packet_ok (rs->buf,
14083                      &remote_protocol_packets[PACKET_QThreadEvents]))
14084     {
14085     case PACKET_OK:
14086       if (strcmp (rs->buf, "OK") != 0)
14087         error (_("Remote refused setting thread events: %s"), rs->buf);
14088       break;
14089     case PACKET_ERROR:
14090       warning (_("Remote failure reply: %s"), rs->buf);
14091       break;
14092     case PACKET_UNKNOWN:
14093       break;
14094     }
14095 }
14096
14097 static void
14098 set_remote_cmd (const char *args, int from_tty)
14099 {
14100   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14101 }
14102
14103 static void
14104 show_remote_cmd (const char *args, int from_tty)
14105 {
14106   /* We can't just use cmd_show_list here, because we want to skip
14107      the redundant "show remote Z-packet" and the legacy aliases.  */
14108   struct cmd_list_element *list = remote_show_cmdlist;
14109   struct ui_out *uiout = current_uiout;
14110
14111   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14112   for (; list != NULL; list = list->next)
14113     if (strcmp (list->name, "Z-packet") == 0)
14114       continue;
14115     else if (list->type == not_set_cmd)
14116       /* Alias commands are exactly like the original, except they
14117          don't have the normal type.  */
14118       continue;
14119     else
14120       {
14121         ui_out_emit_tuple option_emitter (uiout, "option");
14122
14123         uiout->field_string ("name", list->name);
14124         uiout->text (":  ");
14125         if (list->type == show_cmd)
14126           do_show_command (NULL, from_tty, list);
14127         else
14128           cmd_func (list, NULL, from_tty);
14129       }
14130 }
14131
14132
14133 /* Function to be called whenever a new objfile (shlib) is detected.  */
14134 static void
14135 remote_new_objfile (struct objfile *objfile)
14136 {
14137   remote_target *remote = get_current_remote_target ();
14138
14139   if (remote != NULL)                   /* Have a remote connection.  */
14140     remote->remote_check_symbols ();
14141 }
14142
14143 /* Pull all the tracepoints defined on the target and create local
14144    data structures representing them.  We don't want to create real
14145    tracepoints yet, we don't want to mess up the user's existing
14146    collection.  */
14147   
14148 int
14149 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14150 {
14151   struct remote_state *rs = get_remote_state ();
14152   char *p;
14153
14154   /* Ask for a first packet of tracepoint definition.  */
14155   putpkt ("qTfP");
14156   getpkt (&rs->buf, &rs->buf_size, 0);
14157   p = rs->buf;
14158   while (*p && *p != 'l')
14159     {
14160       parse_tracepoint_definition (p, utpp);
14161       /* Ask for another packet of tracepoint definition.  */
14162       putpkt ("qTsP");
14163       getpkt (&rs->buf, &rs->buf_size, 0);
14164       p = rs->buf;
14165     }
14166   return 0;
14167 }
14168
14169 int
14170 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14171 {
14172   struct remote_state *rs = get_remote_state ();
14173   char *p;
14174
14175   /* Ask for a first packet of variable definition.  */
14176   putpkt ("qTfV");
14177   getpkt (&rs->buf, &rs->buf_size, 0);
14178   p = rs->buf;
14179   while (*p && *p != 'l')
14180     {
14181       parse_tsv_definition (p, utsvp);
14182       /* Ask for another packet of variable definition.  */
14183       putpkt ("qTsV");
14184       getpkt (&rs->buf, &rs->buf_size, 0);
14185       p = rs->buf;
14186     }
14187   return 0;
14188 }
14189
14190 /* The "set/show range-stepping" show hook.  */
14191
14192 static void
14193 show_range_stepping (struct ui_file *file, int from_tty,
14194                      struct cmd_list_element *c,
14195                      const char *value)
14196 {
14197   fprintf_filtered (file,
14198                     _("Debugger's willingness to use range stepping "
14199                       "is %s.\n"), value);
14200 }
14201
14202 /* Return true if the vCont;r action is supported by the remote
14203    stub.  */
14204
14205 bool
14206 remote_target::vcont_r_supported ()
14207 {
14208   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14209     remote_vcont_probe ();
14210
14211   return (packet_support (PACKET_vCont) == PACKET_ENABLE
14212           && get_remote_state ()->supports_vCont.r);
14213 }
14214
14215 /* The "set/show range-stepping" set hook.  */
14216
14217 static void
14218 set_range_stepping (const char *ignore_args, int from_tty,
14219                     struct cmd_list_element *c)
14220 {
14221   /* When enabling, check whether range stepping is actually supported
14222      by the target, and warn if not.  */
14223   if (use_range_stepping)
14224     {
14225       remote_target *remote = get_current_remote_target ();
14226       if (remote == NULL
14227           || !remote->vcont_r_supported ())
14228         warning (_("Range stepping is not supported by the current target"));
14229     }
14230 }
14231
14232 void
14233 _initialize_remote (void)
14234 {
14235   struct cmd_list_element *cmd;
14236   const char *cmd_name;
14237
14238   /* architecture specific data */
14239   remote_g_packet_data_handle =
14240     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14241
14242   remote_pspace_data
14243     = register_program_space_data_with_cleanup (NULL,
14244                                                 remote_pspace_data_cleanup);
14245
14246   add_target (remote_target_info, remote_target::open);
14247   add_target (extended_remote_target_info, extended_remote_target::open);
14248
14249   /* Hook into new objfile notification.  */
14250   gdb::observers::new_objfile.attach (remote_new_objfile);
14251
14252 #if 0
14253   init_remote_threadtests ();
14254 #endif
14255
14256   /* set/show remote ...  */
14257
14258   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14259 Remote protocol specific variables\n\
14260 Configure various remote-protocol specific variables such as\n\
14261 the packets being used"),
14262                   &remote_set_cmdlist, "set remote ",
14263                   0 /* allow-unknown */, &setlist);
14264   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14265 Remote protocol specific variables\n\
14266 Configure various remote-protocol specific variables such as\n\
14267 the packets being used"),
14268                   &remote_show_cmdlist, "show remote ",
14269                   0 /* allow-unknown */, &showlist);
14270
14271   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14272 Compare section data on target to the exec file.\n\
14273 Argument is a single section name (default: all loaded sections).\n\
14274 To compare only read-only loaded sections, specify the -r option."),
14275            &cmdlist);
14276
14277   add_cmd ("packet", class_maintenance, packet_command, _("\
14278 Send an arbitrary packet to a remote target.\n\
14279    maintenance packet TEXT\n\
14280 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14281 this command sends the string TEXT to the inferior, and displays the\n\
14282 response packet.  GDB supplies the initial `$' character, and the\n\
14283 terminating `#' character and checksum."),
14284            &maintenancelist);
14285
14286   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14287 Set whether to send break if interrupted."), _("\
14288 Show whether to send break if interrupted."), _("\
14289 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14290                            set_remotebreak, show_remotebreak,
14291                            &setlist, &showlist);
14292   cmd_name = "remotebreak";
14293   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14294   deprecate_cmd (cmd, "set remote interrupt-sequence");
14295   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14296   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14297   deprecate_cmd (cmd, "show remote interrupt-sequence");
14298
14299   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14300                         interrupt_sequence_modes, &interrupt_sequence_mode,
14301                         _("\
14302 Set interrupt sequence to remote target."), _("\
14303 Show interrupt sequence to remote target."), _("\
14304 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14305                         NULL, show_interrupt_sequence,
14306                         &remote_set_cmdlist,
14307                         &remote_show_cmdlist);
14308
14309   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14310                            &interrupt_on_connect, _("\
14311 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14312 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14313 If set, interrupt sequence is sent to remote target."),
14314                            NULL, NULL,
14315                            &remote_set_cmdlist, &remote_show_cmdlist);
14316
14317   /* Install commands for configuring memory read/write packets.  */
14318
14319   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14320 Set the maximum number of bytes per memory write packet (deprecated)."),
14321            &setlist);
14322   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14323 Show the maximum number of bytes per memory write packet (deprecated)."),
14324            &showlist);
14325   add_cmd ("memory-write-packet-size", no_class,
14326            set_memory_write_packet_size, _("\
14327 Set the maximum number of bytes per memory-write packet.\n\
14328 Specify the number of bytes in a packet or 0 (zero) for the\n\
14329 default packet size.  The actual limit is further reduced\n\
14330 dependent on the target.  Specify ``fixed'' to disable the\n\
14331 further restriction and ``limit'' to enable that restriction."),
14332            &remote_set_cmdlist);
14333   add_cmd ("memory-read-packet-size", no_class,
14334            set_memory_read_packet_size, _("\
14335 Set the maximum number of bytes per memory-read 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-write-packet-size", no_class,
14342            show_memory_write_packet_size,
14343            _("Show the maximum number of bytes per memory-write packet."),
14344            &remote_show_cmdlist);
14345   add_cmd ("memory-read-packet-size", no_class,
14346            show_memory_read_packet_size,
14347            _("Show the maximum number of bytes per memory-read packet."),
14348            &remote_show_cmdlist);
14349
14350   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14351                             &remote_hw_watchpoint_limit, _("\
14352 Set the maximum number of target hardware watchpoints."), _("\
14353 Show the maximum number of target hardware watchpoints."), _("\
14354 Specify a negative limit for unlimited."),
14355                             NULL, NULL, /* FIXME: i18n: The maximum
14356                                            number of target hardware
14357                                            watchpoints is %s.  */
14358                             &remote_set_cmdlist, &remote_show_cmdlist);
14359   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14360                             &remote_hw_watchpoint_length_limit, _("\
14361 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14362 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14363 Specify a negative limit for unlimited."),
14364                             NULL, NULL, /* FIXME: i18n: The maximum
14365                                            length (in bytes) of a target
14366                                            hardware watchpoint is %s.  */
14367                             &remote_set_cmdlist, &remote_show_cmdlist);
14368   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14369                             &remote_hw_breakpoint_limit, _("\
14370 Set the maximum number of target hardware breakpoints."), _("\
14371 Show the maximum number of target hardware breakpoints."), _("\
14372 Specify a negative limit for unlimited."),
14373                             NULL, NULL, /* FIXME: i18n: The maximum
14374                                            number of target hardware
14375                                            breakpoints is %s.  */
14376                             &remote_set_cmdlist, &remote_show_cmdlist);
14377
14378   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14379                              &remote_address_size, _("\
14380 Set the maximum size of the address (in bits) in a memory packet."), _("\
14381 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14382                              NULL,
14383                              NULL, /* FIXME: i18n: */
14384                              &setlist, &showlist);
14385
14386   init_all_packet_configs ();
14387
14388   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14389                          "X", "binary-download", 1);
14390
14391   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14392                          "vCont", "verbose-resume", 0);
14393
14394   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14395                          "QPassSignals", "pass-signals", 0);
14396
14397   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14398                          "QCatchSyscalls", "catch-syscalls", 0);
14399
14400   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14401                          "QProgramSignals", "program-signals", 0);
14402
14403   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14404                          "QSetWorkingDir", "set-working-dir", 0);
14405
14406   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14407                          "QStartupWithShell", "startup-with-shell", 0);
14408
14409   add_packet_config_cmd (&remote_protocol_packets
14410                          [PACKET_QEnvironmentHexEncoded],
14411                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14412                          0);
14413
14414   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14415                          "QEnvironmentReset", "environment-reset",
14416                          0);
14417
14418   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14419                          "QEnvironmentUnset", "environment-unset",
14420                          0);
14421
14422   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14423                          "qSymbol", "symbol-lookup", 0);
14424
14425   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14426                          "P", "set-register", 1);
14427
14428   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14429                          "p", "fetch-register", 1);
14430
14431   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14432                          "Z0", "software-breakpoint", 0);
14433
14434   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14435                          "Z1", "hardware-breakpoint", 0);
14436
14437   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14438                          "Z2", "write-watchpoint", 0);
14439
14440   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14441                          "Z3", "read-watchpoint", 0);
14442
14443   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14444                          "Z4", "access-watchpoint", 0);
14445
14446   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14447                          "qXfer:auxv:read", "read-aux-vector", 0);
14448
14449   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14450                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14451
14452   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14453                          "qXfer:features:read", "target-features", 0);
14454
14455   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14456                          "qXfer:libraries:read", "library-info", 0);
14457
14458   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14459                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14460
14461   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14462                          "qXfer:memory-map:read", "memory-map", 0);
14463
14464   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14465                          "qXfer:spu:read", "read-spu-object", 0);
14466
14467   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14468                          "qXfer:spu:write", "write-spu-object", 0);
14469
14470   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14471                         "qXfer:osdata:read", "osdata", 0);
14472
14473   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14474                          "qXfer:threads:read", "threads", 0);
14475
14476   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14477                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14478
14479   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14480                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14481
14482   add_packet_config_cmd
14483     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14484      "qXfer:traceframe-info:read", "traceframe-info", 0);
14485
14486   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14487                          "qXfer:uib:read", "unwind-info-block", 0);
14488
14489   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14490                          "qGetTLSAddr", "get-thread-local-storage-address",
14491                          0);
14492
14493   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14494                          "qGetTIBAddr", "get-thread-information-block-address",
14495                          0);
14496
14497   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14498                          "bc", "reverse-continue", 0);
14499
14500   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14501                          "bs", "reverse-step", 0);
14502
14503   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14504                          "qSupported", "supported-packets", 0);
14505
14506   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14507                          "qSearch:memory", "search-memory", 0);
14508
14509   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14510                          "qTStatus", "trace-status", 0);
14511
14512   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14513                          "vFile:setfs", "hostio-setfs", 0);
14514
14515   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14516                          "vFile:open", "hostio-open", 0);
14517
14518   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14519                          "vFile:pread", "hostio-pread", 0);
14520
14521   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14522                          "vFile:pwrite", "hostio-pwrite", 0);
14523
14524   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14525                          "vFile:close", "hostio-close", 0);
14526
14527   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14528                          "vFile:unlink", "hostio-unlink", 0);
14529
14530   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14531                          "vFile:readlink", "hostio-readlink", 0);
14532
14533   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14534                          "vFile:fstat", "hostio-fstat", 0);
14535
14536   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14537                          "vAttach", "attach", 0);
14538
14539   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14540                          "vRun", "run", 0);
14541
14542   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14543                          "QStartNoAckMode", "noack", 0);
14544
14545   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14546                          "vKill", "kill", 0);
14547
14548   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14549                          "qAttached", "query-attached", 0);
14550
14551   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14552                          "ConditionalTracepoints",
14553                          "conditional-tracepoints", 0);
14554
14555   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14556                          "ConditionalBreakpoints",
14557                          "conditional-breakpoints", 0);
14558
14559   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14560                          "BreakpointCommands",
14561                          "breakpoint-commands", 0);
14562
14563   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14564                          "FastTracepoints", "fast-tracepoints", 0);
14565
14566   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14567                          "TracepointSource", "TracepointSource", 0);
14568
14569   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14570                          "QAllow", "allow", 0);
14571
14572   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14573                          "StaticTracepoints", "static-tracepoints", 0);
14574
14575   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14576                          "InstallInTrace", "install-in-trace", 0);
14577
14578   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14579                          "qXfer:statictrace:read", "read-sdata-object", 0);
14580
14581   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14582                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14583
14584   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14585                          "QDisableRandomization", "disable-randomization", 0);
14586
14587   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14588                          "QAgent", "agent", 0);
14589
14590   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14591                          "QTBuffer:size", "trace-buffer-size", 0);
14592
14593   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14594        "Qbtrace:off", "disable-btrace", 0);
14595
14596   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14597        "Qbtrace:bts", "enable-btrace-bts", 0);
14598
14599   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14600        "Qbtrace:pt", "enable-btrace-pt", 0);
14601
14602   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14603        "qXfer:btrace", "read-btrace", 0);
14604
14605   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14606        "qXfer:btrace-conf", "read-btrace-conf", 0);
14607
14608   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14609        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14610
14611   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14612        "multiprocess-feature", "multiprocess-feature", 0);
14613
14614   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14615                          "swbreak-feature", "swbreak-feature", 0);
14616
14617   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14618                          "hwbreak-feature", "hwbreak-feature", 0);
14619
14620   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14621                          "fork-event-feature", "fork-event-feature", 0);
14622
14623   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14624                          "vfork-event-feature", "vfork-event-feature", 0);
14625
14626   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14627        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14628
14629   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14630                          "vContSupported", "verbose-resume-supported", 0);
14631
14632   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14633                          "exec-event-feature", "exec-event-feature", 0);
14634
14635   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14636                          "vCtrlC", "ctrl-c", 0);
14637
14638   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14639                          "QThreadEvents", "thread-events", 0);
14640
14641   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14642                          "N stop reply", "no-resumed-stop-reply", 0);
14643
14644   /* Assert that we've registered "set remote foo-packet" commands
14645      for all packet configs.  */
14646   {
14647     int i;
14648
14649     for (i = 0; i < PACKET_MAX; i++)
14650       {
14651         /* Ideally all configs would have a command associated.  Some
14652            still don't though.  */
14653         int excepted;
14654
14655         switch (i)
14656           {
14657           case PACKET_QNonStop:
14658           case PACKET_EnableDisableTracepoints_feature:
14659           case PACKET_tracenz_feature:
14660           case PACKET_DisconnectedTracing_feature:
14661           case PACKET_augmented_libraries_svr4_read_feature:
14662           case PACKET_qCRC:
14663             /* Additions to this list need to be well justified:
14664                pre-existing packets are OK; new packets are not.  */
14665             excepted = 1;
14666             break;
14667           default:
14668             excepted = 0;
14669             break;
14670           }
14671
14672         /* This catches both forgetting to add a config command, and
14673            forgetting to remove a packet from the exception list.  */
14674         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14675       }
14676   }
14677
14678   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14679      Z sub-packet has its own set and show commands, but users may
14680      have sets to this variable in their .gdbinit files (or in their
14681      documentation).  */
14682   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14683                                 &remote_Z_packet_detect, _("\
14684 Set use of remote protocol `Z' packets"), _("\
14685 Show use of remote protocol `Z' packets "), _("\
14686 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14687 packets."),
14688                                 set_remote_protocol_Z_packet_cmd,
14689                                 show_remote_protocol_Z_packet_cmd,
14690                                 /* FIXME: i18n: Use of remote protocol
14691                                    `Z' packets is %s.  */
14692                                 &remote_set_cmdlist, &remote_show_cmdlist);
14693
14694   add_prefix_cmd ("remote", class_files, remote_command, _("\
14695 Manipulate files on the remote system\n\
14696 Transfer files to and from the remote target system."),
14697                   &remote_cmdlist, "remote ",
14698                   0 /* allow-unknown */, &cmdlist);
14699
14700   add_cmd ("put", class_files, remote_put_command,
14701            _("Copy a local file to the remote system."),
14702            &remote_cmdlist);
14703
14704   add_cmd ("get", class_files, remote_get_command,
14705            _("Copy a remote file to the local system."),
14706            &remote_cmdlist);
14707
14708   add_cmd ("delete", class_files, remote_delete_command,
14709            _("Delete a remote file."),
14710            &remote_cmdlist);
14711
14712   add_setshow_string_noescape_cmd ("exec-file", class_files,
14713                                    &remote_exec_file_var, _("\
14714 Set the remote pathname for \"run\""), _("\
14715 Show the remote pathname for \"run\""), NULL,
14716                                    set_remote_exec_file,
14717                                    show_remote_exec_file,
14718                                    &remote_set_cmdlist,
14719                                    &remote_show_cmdlist);
14720
14721   add_setshow_boolean_cmd ("range-stepping", class_run,
14722                            &use_range_stepping, _("\
14723 Enable or disable range stepping."), _("\
14724 Show whether target-assisted range stepping is enabled."), _("\
14725 If on, and the target supports it, when stepping a source line, GDB\n\
14726 tells the target to step the corresponding range of addresses itself instead\n\
14727 of issuing multiple single-steps.  This speeds up source level\n\
14728 stepping.  If off, GDB always issues single-steps, even if range\n\
14729 stepping is supported by the target.  The default is on."),
14730                            set_range_stepping,
14731                            show_range_stepping,
14732                            &setlist,
14733                            &showlist);
14734
14735   /* Eventually initialize fileio.  See fileio.c */
14736   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14737
14738   /* Take advantage of the fact that the TID field is not used, to tag
14739      special ptids with it set to != 0.  */
14740   magic_null_ptid = ptid_t (42000, -1, 1);
14741   not_sent_ptid = ptid_t (42000, -2, 1);
14742   any_thread_ptid = ptid_t (42000, 0, 1);
14743 }