Use GNU style for metasyntactic variables in gdb
[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 /* Show the number of hardware watchpoints that can be used.  */
1732
1733 static void
1734 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1735                                 struct cmd_list_element *c,
1736                                 const char *value)
1737 {
1738   fprintf_filtered (file, _("The maximum number of target hardware "
1739                             "watchpoints is %s.\n"), value);
1740 }
1741
1742 /* Show the length limit (in bytes) for hardware watchpoints.  */
1743
1744 static void
1745 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1746                                        struct cmd_list_element *c,
1747                                        const char *value)
1748 {
1749   fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1750                             "hardware watchpoint is %s.\n"), value);
1751 }
1752
1753 /* Show the number of hardware breakpoints that can be used.  */
1754
1755 static void
1756 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1757                                 struct cmd_list_element *c,
1758                                 const char *value)
1759 {
1760   fprintf_filtered (file, _("The maximum number of target hardware "
1761                             "breakpoints is %s.\n"), value);
1762 }
1763
1764 long
1765 remote_target::get_memory_write_packet_size ()
1766 {
1767   return get_memory_packet_size (&memory_write_packet_config);
1768 }
1769
1770 static struct memory_packet_config memory_read_packet_config =
1771 {
1772   "memory-read-packet-size",
1773 };
1774
1775 static void
1776 set_memory_read_packet_size (const char *args, int from_tty)
1777 {
1778   set_memory_packet_size (args, &memory_read_packet_config);
1779 }
1780
1781 static void
1782 show_memory_read_packet_size (const char *args, int from_tty)
1783 {
1784   show_memory_packet_size (&memory_read_packet_config);
1785 }
1786
1787 long
1788 remote_target::get_memory_read_packet_size ()
1789 {
1790   long size = get_memory_packet_size (&memory_read_packet_config);
1791
1792   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1793      extra buffer size argument before the memory read size can be
1794      increased beyond this.  */
1795   if (size > get_remote_packet_size ())
1796     size = get_remote_packet_size ();
1797   return size;
1798 }
1799
1800 \f
1801
1802 struct packet_config
1803   {
1804     const char *name;
1805     const char *title;
1806
1807     /* If auto, GDB auto-detects support for this packet or feature,
1808        either through qSupported, or by trying the packet and looking
1809        at the response.  If true, GDB assumes the target supports this
1810        packet.  If false, the packet is disabled.  Configs that don't
1811        have an associated command always have this set to auto.  */
1812     enum auto_boolean detect;
1813
1814     /* Does the target support this packet?  */
1815     enum packet_support support;
1816   };
1817
1818 static enum packet_support packet_config_support (struct packet_config *config);
1819 static enum packet_support packet_support (int packet);
1820
1821 static void
1822 show_packet_config_cmd (struct packet_config *config)
1823 {
1824   const char *support = "internal-error";
1825
1826   switch (packet_config_support (config))
1827     {
1828     case PACKET_ENABLE:
1829       support = "enabled";
1830       break;
1831     case PACKET_DISABLE:
1832       support = "disabled";
1833       break;
1834     case PACKET_SUPPORT_UNKNOWN:
1835       support = "unknown";
1836       break;
1837     }
1838   switch (config->detect)
1839     {
1840     case AUTO_BOOLEAN_AUTO:
1841       printf_filtered (_("Support for the `%s' packet "
1842                          "is auto-detected, currently %s.\n"),
1843                        config->name, support);
1844       break;
1845     case AUTO_BOOLEAN_TRUE:
1846     case AUTO_BOOLEAN_FALSE:
1847       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1848                        config->name, support);
1849       break;
1850     }
1851 }
1852
1853 static void
1854 add_packet_config_cmd (struct packet_config *config, const char *name,
1855                        const char *title, int legacy)
1856 {
1857   char *set_doc;
1858   char *show_doc;
1859   char *cmd_name;
1860
1861   config->name = name;
1862   config->title = title;
1863   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1864                         name, title);
1865   show_doc = xstrprintf ("Show current use of remote "
1866                          "protocol `%s' (%s) packet",
1867                          name, title);
1868   /* set/show TITLE-packet {auto,on,off} */
1869   cmd_name = xstrprintf ("%s-packet", title);
1870   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1871                                 &config->detect, set_doc,
1872                                 show_doc, NULL, /* help_doc */
1873                                 NULL,
1874                                 show_remote_protocol_packet_cmd,
1875                                 &remote_set_cmdlist, &remote_show_cmdlist);
1876   /* The command code copies the documentation strings.  */
1877   xfree (set_doc);
1878   xfree (show_doc);
1879   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1880   if (legacy)
1881     {
1882       char *legacy_name;
1883
1884       legacy_name = xstrprintf ("%s-packet", name);
1885       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1886                      &remote_set_cmdlist);
1887       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1888                      &remote_show_cmdlist);
1889     }
1890 }
1891
1892 static enum packet_result
1893 packet_check_result (const char *buf)
1894 {
1895   if (buf[0] != '\0')
1896     {
1897       /* The stub recognized the packet request.  Check that the
1898          operation succeeded.  */
1899       if (buf[0] == 'E'
1900           && isxdigit (buf[1]) && isxdigit (buf[2])
1901           && buf[3] == '\0')
1902         /* "Enn"  - definitly an error.  */
1903         return PACKET_ERROR;
1904
1905       /* Always treat "E." as an error.  This will be used for
1906          more verbose error messages, such as E.memtypes.  */
1907       if (buf[0] == 'E' && buf[1] == '.')
1908         return PACKET_ERROR;
1909
1910       /* The packet may or may not be OK.  Just assume it is.  */
1911       return PACKET_OK;
1912     }
1913   else
1914     /* The stub does not support the packet.  */
1915     return PACKET_UNKNOWN;
1916 }
1917
1918 static enum packet_result
1919 packet_ok (const char *buf, struct packet_config *config)
1920 {
1921   enum packet_result result;
1922
1923   if (config->detect != AUTO_BOOLEAN_TRUE
1924       && config->support == PACKET_DISABLE)
1925     internal_error (__FILE__, __LINE__,
1926                     _("packet_ok: attempt to use a disabled packet"));
1927
1928   result = packet_check_result (buf);
1929   switch (result)
1930     {
1931     case PACKET_OK:
1932     case PACKET_ERROR:
1933       /* The stub recognized the packet request.  */
1934       if (config->support == PACKET_SUPPORT_UNKNOWN)
1935         {
1936           if (remote_debug)
1937             fprintf_unfiltered (gdb_stdlog,
1938                                 "Packet %s (%s) is supported\n",
1939                                 config->name, config->title);
1940           config->support = PACKET_ENABLE;
1941         }
1942       break;
1943     case PACKET_UNKNOWN:
1944       /* The stub does not support the packet.  */
1945       if (config->detect == AUTO_BOOLEAN_AUTO
1946           && config->support == PACKET_ENABLE)
1947         {
1948           /* If the stub previously indicated that the packet was
1949              supported then there is a protocol error.  */
1950           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1951                  config->name, config->title);
1952         }
1953       else if (config->detect == AUTO_BOOLEAN_TRUE)
1954         {
1955           /* The user set it wrong.  */
1956           error (_("Enabled packet %s (%s) not recognized by stub"),
1957                  config->name, config->title);
1958         }
1959
1960       if (remote_debug)
1961         fprintf_unfiltered (gdb_stdlog,
1962                             "Packet %s (%s) is NOT supported\n",
1963                             config->name, config->title);
1964       config->support = PACKET_DISABLE;
1965       break;
1966     }
1967
1968   return result;
1969 }
1970
1971 enum {
1972   PACKET_vCont = 0,
1973   PACKET_X,
1974   PACKET_qSymbol,
1975   PACKET_P,
1976   PACKET_p,
1977   PACKET_Z0,
1978   PACKET_Z1,
1979   PACKET_Z2,
1980   PACKET_Z3,
1981   PACKET_Z4,
1982   PACKET_vFile_setfs,
1983   PACKET_vFile_open,
1984   PACKET_vFile_pread,
1985   PACKET_vFile_pwrite,
1986   PACKET_vFile_close,
1987   PACKET_vFile_unlink,
1988   PACKET_vFile_readlink,
1989   PACKET_vFile_fstat,
1990   PACKET_qXfer_auxv,
1991   PACKET_qXfer_features,
1992   PACKET_qXfer_exec_file,
1993   PACKET_qXfer_libraries,
1994   PACKET_qXfer_libraries_svr4,
1995   PACKET_qXfer_memory_map,
1996   PACKET_qXfer_spu_read,
1997   PACKET_qXfer_spu_write,
1998   PACKET_qXfer_osdata,
1999   PACKET_qXfer_threads,
2000   PACKET_qXfer_statictrace_read,
2001   PACKET_qXfer_traceframe_info,
2002   PACKET_qXfer_uib,
2003   PACKET_qGetTIBAddr,
2004   PACKET_qGetTLSAddr,
2005   PACKET_qSupported,
2006   PACKET_qTStatus,
2007   PACKET_QPassSignals,
2008   PACKET_QCatchSyscalls,
2009   PACKET_QProgramSignals,
2010   PACKET_QSetWorkingDir,
2011   PACKET_QStartupWithShell,
2012   PACKET_QEnvironmentHexEncoded,
2013   PACKET_QEnvironmentReset,
2014   PACKET_QEnvironmentUnset,
2015   PACKET_qCRC,
2016   PACKET_qSearch_memory,
2017   PACKET_vAttach,
2018   PACKET_vRun,
2019   PACKET_QStartNoAckMode,
2020   PACKET_vKill,
2021   PACKET_qXfer_siginfo_read,
2022   PACKET_qXfer_siginfo_write,
2023   PACKET_qAttached,
2024
2025   /* Support for conditional tracepoints.  */
2026   PACKET_ConditionalTracepoints,
2027
2028   /* Support for target-side breakpoint conditions.  */
2029   PACKET_ConditionalBreakpoints,
2030
2031   /* Support for target-side breakpoint commands.  */
2032   PACKET_BreakpointCommands,
2033
2034   /* Support for fast tracepoints.  */
2035   PACKET_FastTracepoints,
2036
2037   /* Support for static tracepoints.  */
2038   PACKET_StaticTracepoints,
2039
2040   /* Support for installing tracepoints while a trace experiment is
2041      running.  */
2042   PACKET_InstallInTrace,
2043
2044   PACKET_bc,
2045   PACKET_bs,
2046   PACKET_TracepointSource,
2047   PACKET_QAllow,
2048   PACKET_qXfer_fdpic,
2049   PACKET_QDisableRandomization,
2050   PACKET_QAgent,
2051   PACKET_QTBuffer_size,
2052   PACKET_Qbtrace_off,
2053   PACKET_Qbtrace_bts,
2054   PACKET_Qbtrace_pt,
2055   PACKET_qXfer_btrace,
2056
2057   /* Support for the QNonStop packet.  */
2058   PACKET_QNonStop,
2059
2060   /* Support for the QThreadEvents packet.  */
2061   PACKET_QThreadEvents,
2062
2063   /* Support for multi-process extensions.  */
2064   PACKET_multiprocess_feature,
2065
2066   /* Support for enabling and disabling tracepoints while a trace
2067      experiment is running.  */
2068   PACKET_EnableDisableTracepoints_feature,
2069
2070   /* Support for collecting strings using the tracenz bytecode.  */
2071   PACKET_tracenz_feature,
2072
2073   /* Support for continuing to run a trace experiment while GDB is
2074      disconnected.  */
2075   PACKET_DisconnectedTracing_feature,
2076
2077   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
2078   PACKET_augmented_libraries_svr4_read_feature,
2079
2080   /* Support for the qXfer:btrace-conf:read packet.  */
2081   PACKET_qXfer_btrace_conf,
2082
2083   /* Support for the Qbtrace-conf:bts:size packet.  */
2084   PACKET_Qbtrace_conf_bts_size,
2085
2086   /* Support for swbreak+ feature.  */
2087   PACKET_swbreak_feature,
2088
2089   /* Support for hwbreak+ feature.  */
2090   PACKET_hwbreak_feature,
2091
2092   /* Support for fork events.  */
2093   PACKET_fork_event_feature,
2094
2095   /* Support for vfork events.  */
2096   PACKET_vfork_event_feature,
2097
2098   /* Support for the Qbtrace-conf:pt:size packet.  */
2099   PACKET_Qbtrace_conf_pt_size,
2100
2101   /* Support for exec events.  */
2102   PACKET_exec_event_feature,
2103
2104   /* Support for query supported vCont actions.  */
2105   PACKET_vContSupported,
2106
2107   /* Support remote CTRL-C.  */
2108   PACKET_vCtrlC,
2109
2110   /* Support TARGET_WAITKIND_NO_RESUMED.  */
2111   PACKET_no_resumed,
2112
2113   PACKET_MAX
2114 };
2115
2116 static struct packet_config remote_protocol_packets[PACKET_MAX];
2117
2118 /* Returns the packet's corresponding "set remote foo-packet" command
2119    state.  See struct packet_config for more details.  */
2120
2121 static enum auto_boolean
2122 packet_set_cmd_state (int packet)
2123 {
2124   return remote_protocol_packets[packet].detect;
2125 }
2126
2127 /* Returns whether a given packet or feature is supported.  This takes
2128    into account the state of the corresponding "set remote foo-packet"
2129    command, which may be used to bypass auto-detection.  */
2130
2131 static enum packet_support
2132 packet_config_support (struct packet_config *config)
2133 {
2134   switch (config->detect)
2135     {
2136     case AUTO_BOOLEAN_TRUE:
2137       return PACKET_ENABLE;
2138     case AUTO_BOOLEAN_FALSE:
2139       return PACKET_DISABLE;
2140     case AUTO_BOOLEAN_AUTO:
2141       return config->support;
2142     default:
2143       gdb_assert_not_reached (_("bad switch"));
2144     }
2145 }
2146
2147 /* Same as packet_config_support, but takes the packet's enum value as
2148    argument.  */
2149
2150 static enum packet_support
2151 packet_support (int packet)
2152 {
2153   struct packet_config *config = &remote_protocol_packets[packet];
2154
2155   return packet_config_support (config);
2156 }
2157
2158 static void
2159 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2160                                  struct cmd_list_element *c,
2161                                  const char *value)
2162 {
2163   struct packet_config *packet;
2164
2165   for (packet = remote_protocol_packets;
2166        packet < &remote_protocol_packets[PACKET_MAX];
2167        packet++)
2168     {
2169       if (&packet->detect == c->var)
2170         {
2171           show_packet_config_cmd (packet);
2172           return;
2173         }
2174     }
2175   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2176                   c->name);
2177 }
2178
2179 /* Should we try one of the 'Z' requests?  */
2180
2181 enum Z_packet_type
2182 {
2183   Z_PACKET_SOFTWARE_BP,
2184   Z_PACKET_HARDWARE_BP,
2185   Z_PACKET_WRITE_WP,
2186   Z_PACKET_READ_WP,
2187   Z_PACKET_ACCESS_WP,
2188   NR_Z_PACKET_TYPES
2189 };
2190
2191 /* For compatibility with older distributions.  Provide a ``set remote
2192    Z-packet ...'' command that updates all the Z packet types.  */
2193
2194 static enum auto_boolean remote_Z_packet_detect;
2195
2196 static void
2197 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2198                                   struct cmd_list_element *c)
2199 {
2200   int i;
2201
2202   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2203     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2204 }
2205
2206 static void
2207 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2208                                    struct cmd_list_element *c,
2209                                    const char *value)
2210 {
2211   int i;
2212
2213   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2214     {
2215       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2216     }
2217 }
2218
2219 /* Returns true if the multi-process extensions are in effect.  */
2220
2221 static int
2222 remote_multi_process_p (struct remote_state *rs)
2223 {
2224   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2225 }
2226
2227 /* Returns true if fork events are supported.  */
2228
2229 static int
2230 remote_fork_event_p (struct remote_state *rs)
2231 {
2232   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2233 }
2234
2235 /* Returns true if vfork events are supported.  */
2236
2237 static int
2238 remote_vfork_event_p (struct remote_state *rs)
2239 {
2240   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2241 }
2242
2243 /* Returns true if exec events are supported.  */
2244
2245 static int
2246 remote_exec_event_p (struct remote_state *rs)
2247 {
2248   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2249 }
2250
2251 /* Insert fork catchpoint target routine.  If fork events are enabled
2252    then return success, nothing more to do.  */
2253
2254 int
2255 remote_target::insert_fork_catchpoint (int pid)
2256 {
2257   struct remote_state *rs = get_remote_state ();
2258
2259   return !remote_fork_event_p (rs);
2260 }
2261
2262 /* Remove fork catchpoint target routine.  Nothing to do, just
2263    return success.  */
2264
2265 int
2266 remote_target::remove_fork_catchpoint (int pid)
2267 {
2268   return 0;
2269 }
2270
2271 /* Insert vfork catchpoint target routine.  If vfork events are enabled
2272    then return success, nothing more to do.  */
2273
2274 int
2275 remote_target::insert_vfork_catchpoint (int pid)
2276 {
2277   struct remote_state *rs = get_remote_state ();
2278
2279   return !remote_vfork_event_p (rs);
2280 }
2281
2282 /* Remove vfork catchpoint target routine.  Nothing to do, just
2283    return success.  */
2284
2285 int
2286 remote_target::remove_vfork_catchpoint (int pid)
2287 {
2288   return 0;
2289 }
2290
2291 /* Insert exec catchpoint target routine.  If exec events are
2292    enabled, just return success.  */
2293
2294 int
2295 remote_target::insert_exec_catchpoint (int pid)
2296 {
2297   struct remote_state *rs = get_remote_state ();
2298
2299   return !remote_exec_event_p (rs);
2300 }
2301
2302 /* Remove exec catchpoint target routine.  Nothing to do, just
2303    return success.  */
2304
2305 int
2306 remote_target::remove_exec_catchpoint (int pid)
2307 {
2308   return 0;
2309 }
2310
2311 \f
2312
2313 static ptid_t magic_null_ptid;
2314 static ptid_t not_sent_ptid;
2315 static ptid_t any_thread_ptid;
2316
2317 /* Find out if the stub attached to PID (and hence GDB should offer to
2318    detach instead of killing it when bailing out).  */
2319
2320 int
2321 remote_target::remote_query_attached (int pid)
2322 {
2323   struct remote_state *rs = get_remote_state ();
2324   size_t size = get_remote_packet_size ();
2325
2326   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2327     return 0;
2328
2329   if (remote_multi_process_p (rs))
2330     xsnprintf (rs->buf, size, "qAttached:%x", pid);
2331   else
2332     xsnprintf (rs->buf, size, "qAttached");
2333
2334   putpkt (rs->buf);
2335   getpkt (&rs->buf, &rs->buf_size, 0);
2336
2337   switch (packet_ok (rs->buf,
2338                      &remote_protocol_packets[PACKET_qAttached]))
2339     {
2340     case PACKET_OK:
2341       if (strcmp (rs->buf, "1") == 0)
2342         return 1;
2343       break;
2344     case PACKET_ERROR:
2345       warning (_("Remote failure reply: %s"), rs->buf);
2346       break;
2347     case PACKET_UNKNOWN:
2348       break;
2349     }
2350
2351   return 0;
2352 }
2353
2354 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2355    has been invented by GDB, instead of reported by the target.  Since
2356    we can be connected to a remote system before before knowing about
2357    any inferior, mark the target with execution when we find the first
2358    inferior.  If ATTACHED is 1, then we had just attached to this
2359    inferior.  If it is 0, then we just created this inferior.  If it
2360    is -1, then try querying the remote stub to find out if it had
2361    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2362    attempt to open this inferior's executable as the main executable
2363    if no main executable is open already.  */
2364
2365 inferior *
2366 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2367                                     int try_open_exec)
2368 {
2369   struct inferior *inf;
2370
2371   /* Check whether this process we're learning about is to be
2372      considered attached, or if is to be considered to have been
2373      spawned by the stub.  */
2374   if (attached == -1)
2375     attached = remote_query_attached (pid);
2376
2377   if (gdbarch_has_global_solist (target_gdbarch ()))
2378     {
2379       /* If the target shares code across all inferiors, then every
2380          attach adds a new inferior.  */
2381       inf = add_inferior (pid);
2382
2383       /* ... and every inferior is bound to the same program space.
2384          However, each inferior may still have its own address
2385          space.  */
2386       inf->aspace = maybe_new_address_space ();
2387       inf->pspace = current_program_space;
2388     }
2389   else
2390     {
2391       /* In the traditional debugging scenario, there's a 1-1 match
2392          between program/address spaces.  We simply bind the inferior
2393          to the program space's address space.  */
2394       inf = current_inferior ();
2395       inferior_appeared (inf, pid);
2396     }
2397
2398   inf->attach_flag = attached;
2399   inf->fake_pid_p = fake_pid_p;
2400
2401   /* If no main executable is currently open then attempt to
2402      open the file that was executed to create this inferior.  */
2403   if (try_open_exec && get_exec_file (0) == NULL)
2404     exec_file_locate_attach (pid, 0, 1);
2405
2406   return inf;
2407 }
2408
2409 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2410 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
2411
2412 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2413    according to RUNNING.  */
2414
2415 thread_info *
2416 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2417 {
2418   struct remote_state *rs = get_remote_state ();
2419   struct thread_info *thread;
2420
2421   /* GDB historically didn't pull threads in the initial connection
2422      setup.  If the remote target doesn't even have a concept of
2423      threads (e.g., a bare-metal target), even if internally we
2424      consider that a single-threaded target, mentioning a new thread
2425      might be confusing to the user.  Be silent then, preserving the
2426      age old behavior.  */
2427   if (rs->starting_up)
2428     thread = add_thread_silent (ptid);
2429   else
2430     thread = add_thread (ptid);
2431
2432   get_remote_thread_info (thread)->vcont_resumed = executing;
2433   set_executing (ptid, executing);
2434   set_running (ptid, running);
2435
2436   return thread;
2437 }
2438
2439 /* Come here when we learn about a thread id from the remote target.
2440    It may be the first time we hear about such thread, so take the
2441    opportunity to add it to GDB's thread list.  In case this is the
2442    first time we're noticing its corresponding inferior, add it to
2443    GDB's inferior list as well.  EXECUTING indicates whether the
2444    thread is (internally) executing or stopped.  */
2445
2446 void
2447 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2448 {
2449   /* In non-stop mode, we assume new found threads are (externally)
2450      running until proven otherwise with a stop reply.  In all-stop,
2451      we can only get here if all threads are stopped.  */
2452   int running = target_is_non_stop_p () ? 1 : 0;
2453
2454   /* If this is a new thread, add it to GDB's thread list.
2455      If we leave it up to WFI to do this, bad things will happen.  */
2456
2457   thread_info *tp = find_thread_ptid (currthread);
2458   if (tp != NULL && tp->state == THREAD_EXITED)
2459     {
2460       /* We're seeing an event on a thread id we knew had exited.
2461          This has to be a new thread reusing the old id.  Add it.  */
2462       remote_add_thread (currthread, running, executing);
2463       return;
2464     }
2465
2466   if (!in_thread_list (currthread))
2467     {
2468       struct inferior *inf = NULL;
2469       int pid = currthread.pid ();
2470
2471       if (inferior_ptid.is_pid ()
2472           && pid == inferior_ptid.pid ())
2473         {
2474           /* inferior_ptid has no thread member yet.  This can happen
2475              with the vAttach -> remote_wait,"TAAthread:" path if the
2476              stub doesn't support qC.  This is the first stop reported
2477              after an attach, so this is the main thread.  Update the
2478              ptid in the thread list.  */
2479           if (in_thread_list (ptid_t (pid)))
2480             thread_change_ptid (inferior_ptid, currthread);
2481           else
2482             {
2483               remote_add_thread (currthread, running, executing);
2484               inferior_ptid = currthread;
2485             }
2486           return;
2487         }
2488
2489       if (magic_null_ptid == inferior_ptid)
2490         {
2491           /* inferior_ptid is not set yet.  This can happen with the
2492              vRun -> remote_wait,"TAAthread:" path if the stub
2493              doesn't support qC.  This is the first stop reported
2494              after an attach, so this is the main thread.  Update the
2495              ptid in the thread list.  */
2496           thread_change_ptid (inferior_ptid, currthread);
2497           return;
2498         }
2499
2500       /* When connecting to a target remote, or to a target
2501          extended-remote which already was debugging an inferior, we
2502          may not know about it yet.  Add it before adding its child
2503          thread, so notifications are emitted in a sensible order.  */
2504       if (find_inferior_pid (currthread.pid ()) == NULL)
2505         {
2506           struct remote_state *rs = get_remote_state ();
2507           int fake_pid_p = !remote_multi_process_p (rs);
2508
2509           inf = remote_add_inferior (fake_pid_p,
2510                                      currthread.pid (), -1, 1);
2511         }
2512
2513       /* This is really a new thread.  Add it.  */
2514       thread_info *new_thr
2515         = remote_add_thread (currthread, running, executing);
2516
2517       /* If we found a new inferior, let the common code do whatever
2518          it needs to with it (e.g., read shared libraries, insert
2519          breakpoints), unless we're just setting up an all-stop
2520          connection.  */
2521       if (inf != NULL)
2522         {
2523           struct remote_state *rs = get_remote_state ();
2524
2525           if (!rs->starting_up)
2526             notice_new_inferior (new_thr, executing, 0);
2527         }
2528     }
2529 }
2530
2531 /* Return THREAD's private thread data, creating it if necessary.  */
2532
2533 static remote_thread_info *
2534 get_remote_thread_info (thread_info *thread)
2535 {
2536   gdb_assert (thread != NULL);
2537
2538   if (thread->priv == NULL)
2539     thread->priv.reset (new remote_thread_info);
2540
2541   return static_cast<remote_thread_info *> (thread->priv.get ());
2542 }
2543
2544 static remote_thread_info *
2545 get_remote_thread_info (ptid_t ptid)
2546 {
2547   thread_info *thr = find_thread_ptid (ptid);
2548   return get_remote_thread_info (thr);
2549 }
2550
2551 /* Call this function as a result of
2552    1) A halt indication (T packet) containing a thread id
2553    2) A direct query of currthread
2554    3) Successful execution of set thread */
2555
2556 static void
2557 record_currthread (struct remote_state *rs, ptid_t currthread)
2558 {
2559   rs->general_thread = currthread;
2560 }
2561
2562 /* If 'QPassSignals' is supported, tell the remote stub what signals
2563    it can simply pass through to the inferior without reporting.  */
2564
2565 void
2566 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2567 {
2568   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2569     {
2570       char *pass_packet, *p;
2571       int count = 0, i;
2572       struct remote_state *rs = get_remote_state ();
2573
2574       gdb_assert (numsigs < 256);
2575       for (i = 0; i < numsigs; i++)
2576         {
2577           if (pass_signals[i])
2578             count++;
2579         }
2580       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2581       strcpy (pass_packet, "QPassSignals:");
2582       p = pass_packet + strlen (pass_packet);
2583       for (i = 0; i < numsigs; i++)
2584         {
2585           if (pass_signals[i])
2586             {
2587               if (i >= 16)
2588                 *p++ = tohex (i >> 4);
2589               *p++ = tohex (i & 15);
2590               if (count)
2591                 *p++ = ';';
2592               else
2593                 break;
2594               count--;
2595             }
2596         }
2597       *p = 0;
2598       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2599         {
2600           putpkt (pass_packet);
2601           getpkt (&rs->buf, &rs->buf_size, 0);
2602           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2603           if (rs->last_pass_packet)
2604             xfree (rs->last_pass_packet);
2605           rs->last_pass_packet = pass_packet;
2606         }
2607       else
2608         xfree (pass_packet);
2609     }
2610 }
2611
2612 /* If 'QCatchSyscalls' is supported, tell the remote stub
2613    to report syscalls to GDB.  */
2614
2615 int
2616 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2617                                        gdb::array_view<const int> syscall_counts)
2618 {
2619   const char *catch_packet;
2620   enum packet_result result;
2621   int n_sysno = 0;
2622
2623   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2624     {
2625       /* Not supported.  */
2626       return 1;
2627     }
2628
2629   if (needed && any_count == 0)
2630     {
2631       /* Count how many syscalls are to be caught.  */
2632       for (size_t i = 0; i < syscall_counts.size (); i++)
2633         {
2634           if (syscall_counts[i] != 0)
2635             n_sysno++;
2636         }
2637     }
2638
2639   if (remote_debug)
2640     {
2641       fprintf_unfiltered (gdb_stdlog,
2642                           "remote_set_syscall_catchpoint "
2643                           "pid %d needed %d any_count %d n_sysno %d\n",
2644                           pid, needed, any_count, n_sysno);
2645     }
2646
2647   std::string built_packet;
2648   if (needed)
2649     {
2650       /* Prepare a packet with the sysno list, assuming max 8+1
2651          characters for a sysno.  If the resulting packet size is too
2652          big, fallback on the non-selective packet.  */
2653       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2654       built_packet.reserve (maxpktsz);
2655       built_packet = "QCatchSyscalls:1";
2656       if (any_count == 0)
2657         {
2658           /* Add in each syscall to be caught.  */
2659           for (size_t i = 0; i < syscall_counts.size (); i++)
2660             {
2661               if (syscall_counts[i] != 0)
2662                 string_appendf (built_packet, ";%zx", i);
2663             }
2664         }
2665       if (built_packet.size () > get_remote_packet_size ())
2666         {
2667           /* catch_packet too big.  Fallback to less efficient
2668              non selective mode, with GDB doing the filtering.  */
2669           catch_packet = "QCatchSyscalls:1";
2670         }
2671       else
2672         catch_packet = built_packet.c_str ();
2673     }
2674   else
2675     catch_packet = "QCatchSyscalls:0";
2676
2677   struct remote_state *rs = get_remote_state ();
2678
2679   putpkt (catch_packet);
2680   getpkt (&rs->buf, &rs->buf_size, 0);
2681   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2682   if (result == PACKET_OK)
2683     return 0;
2684   else
2685     return -1;
2686 }
2687
2688 /* If 'QProgramSignals' is supported, tell the remote stub what
2689    signals it should pass through to the inferior when detaching.  */
2690
2691 void
2692 remote_target::program_signals (int numsigs, unsigned char *signals)
2693 {
2694   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2695     {
2696       char *packet, *p;
2697       int count = 0, i;
2698       struct remote_state *rs = get_remote_state ();
2699
2700       gdb_assert (numsigs < 256);
2701       for (i = 0; i < numsigs; i++)
2702         {
2703           if (signals[i])
2704             count++;
2705         }
2706       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2707       strcpy (packet, "QProgramSignals:");
2708       p = packet + strlen (packet);
2709       for (i = 0; i < numsigs; i++)
2710         {
2711           if (signal_pass_state (i))
2712             {
2713               if (i >= 16)
2714                 *p++ = tohex (i >> 4);
2715               *p++ = tohex (i & 15);
2716               if (count)
2717                 *p++ = ';';
2718               else
2719                 break;
2720               count--;
2721             }
2722         }
2723       *p = 0;
2724       if (!rs->last_program_signals_packet
2725           || strcmp (rs->last_program_signals_packet, packet) != 0)
2726         {
2727           putpkt (packet);
2728           getpkt (&rs->buf, &rs->buf_size, 0);
2729           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2730           xfree (rs->last_program_signals_packet);
2731           rs->last_program_signals_packet = packet;
2732         }
2733       else
2734         xfree (packet);
2735     }
2736 }
2737
2738 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2739    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2740    thread.  If GEN is set, set the general thread, if not, then set
2741    the step/continue thread.  */
2742 void
2743 remote_target::set_thread (ptid_t ptid, int gen)
2744 {
2745   struct remote_state *rs = get_remote_state ();
2746   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2747   char *buf = rs->buf;
2748   char *endbuf = rs->buf + get_remote_packet_size ();
2749
2750   if (state == ptid)
2751     return;
2752
2753   *buf++ = 'H';
2754   *buf++ = gen ? 'g' : 'c';
2755   if (ptid == magic_null_ptid)
2756     xsnprintf (buf, endbuf - buf, "0");
2757   else if (ptid == any_thread_ptid)
2758     xsnprintf (buf, endbuf - buf, "0");
2759   else if (ptid == minus_one_ptid)
2760     xsnprintf (buf, endbuf - buf, "-1");
2761   else
2762     write_ptid (buf, endbuf, ptid);
2763   putpkt (rs->buf);
2764   getpkt (&rs->buf, &rs->buf_size, 0);
2765   if (gen)
2766     rs->general_thread = ptid;
2767   else
2768     rs->continue_thread = ptid;
2769 }
2770
2771 void
2772 remote_target::set_general_thread (ptid_t ptid)
2773 {
2774   set_thread (ptid, 1);
2775 }
2776
2777 void
2778 remote_target::set_continue_thread (ptid_t ptid)
2779 {
2780   set_thread (ptid, 0);
2781 }
2782
2783 /* Change the remote current process.  Which thread within the process
2784    ends up selected isn't important, as long as it is the same process
2785    as what INFERIOR_PTID points to.
2786
2787    This comes from that fact that there is no explicit notion of
2788    "selected process" in the protocol.  The selected process for
2789    general operations is the process the selected general thread
2790    belongs to.  */
2791
2792 void
2793 remote_target::set_general_process ()
2794 {
2795   struct remote_state *rs = get_remote_state ();
2796
2797   /* If the remote can't handle multiple processes, don't bother.  */
2798   if (!remote_multi_process_p (rs))
2799     return;
2800
2801   /* We only need to change the remote current thread if it's pointing
2802      at some other process.  */
2803   if (rs->general_thread.pid () != inferior_ptid.pid ())
2804     set_general_thread (inferior_ptid);
2805 }
2806
2807 \f
2808 /* Return nonzero if this is the main thread that we made up ourselves
2809    to model non-threaded targets as single-threaded.  */
2810
2811 static int
2812 remote_thread_always_alive (ptid_t ptid)
2813 {
2814   if (ptid == magic_null_ptid)
2815     /* The main thread is always alive.  */
2816     return 1;
2817
2818   if (ptid.pid () != 0 && ptid.lwp () == 0)
2819     /* The main thread is always alive.  This can happen after a
2820        vAttach, if the remote side doesn't support
2821        multi-threading.  */
2822     return 1;
2823
2824   return 0;
2825 }
2826
2827 /* Return nonzero if the thread PTID is still alive on the remote
2828    system.  */
2829
2830 bool
2831 remote_target::thread_alive (ptid_t ptid)
2832 {
2833   struct remote_state *rs = get_remote_state ();
2834   char *p, *endp;
2835
2836   /* Check if this is a thread that we made up ourselves to model
2837      non-threaded targets as single-threaded.  */
2838   if (remote_thread_always_alive (ptid))
2839     return 1;
2840
2841   p = rs->buf;
2842   endp = rs->buf + get_remote_packet_size ();
2843
2844   *p++ = 'T';
2845   write_ptid (p, endp, ptid);
2846
2847   putpkt (rs->buf);
2848   getpkt (&rs->buf, &rs->buf_size, 0);
2849   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2850 }
2851
2852 /* Return a pointer to a thread name if we know it and NULL otherwise.
2853    The thread_info object owns the memory for the name.  */
2854
2855 const char *
2856 remote_target::thread_name (struct thread_info *info)
2857 {
2858   if (info->priv != NULL)
2859     {
2860       const std::string &name = get_remote_thread_info (info)->name;
2861       return !name.empty () ? name.c_str () : NULL;
2862     }
2863
2864   return NULL;
2865 }
2866
2867 /* About these extended threadlist and threadinfo packets.  They are
2868    variable length packets but, the fields within them are often fixed
2869    length.  They are redundent enough to send over UDP as is the
2870    remote protocol in general.  There is a matching unit test module
2871    in libstub.  */
2872
2873 /* WARNING: This threadref data structure comes from the remote O.S.,
2874    libstub protocol encoding, and remote.c.  It is not particularly
2875    changable.  */
2876
2877 /* Right now, the internal structure is int. We want it to be bigger.
2878    Plan to fix this.  */
2879
2880 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2881
2882 /* gdb_ext_thread_info is an internal GDB data structure which is
2883    equivalent to the reply of the remote threadinfo packet.  */
2884
2885 struct gdb_ext_thread_info
2886   {
2887     threadref threadid;         /* External form of thread reference.  */
2888     int active;                 /* Has state interesting to GDB?
2889                                    regs, stack.  */
2890     char display[256];          /* Brief state display, name,
2891                                    blocked/suspended.  */
2892     char shortname[32];         /* To be used to name threads.  */
2893     char more_display[256];     /* Long info, statistics, queue depth,
2894                                    whatever.  */
2895   };
2896
2897 /* The volume of remote transfers can be limited by submitting
2898    a mask containing bits specifying the desired information.
2899    Use a union of these values as the 'selection' parameter to
2900    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2901
2902 #define TAG_THREADID 1
2903 #define TAG_EXISTS 2
2904 #define TAG_DISPLAY 4
2905 #define TAG_THREADNAME 8
2906 #define TAG_MOREDISPLAY 16
2907
2908 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2909
2910 static char *unpack_nibble (char *buf, int *val);
2911
2912 static char *unpack_byte (char *buf, int *value);
2913
2914 static char *pack_int (char *buf, int value);
2915
2916 static char *unpack_int (char *buf, int *value);
2917
2918 static char *unpack_string (char *src, char *dest, int length);
2919
2920 static char *pack_threadid (char *pkt, threadref *id);
2921
2922 static char *unpack_threadid (char *inbuf, threadref *id);
2923
2924 void int_to_threadref (threadref *id, int value);
2925
2926 static int threadref_to_int (threadref *ref);
2927
2928 static void copy_threadref (threadref *dest, threadref *src);
2929
2930 static int threadmatch (threadref *dest, threadref *src);
2931
2932 static char *pack_threadinfo_request (char *pkt, int mode,
2933                                       threadref *id);
2934
2935 static char *pack_threadlist_request (char *pkt, int startflag,
2936                                       int threadcount,
2937                                       threadref *nextthread);
2938
2939 static int remote_newthread_step (threadref *ref, void *context);
2940
2941
2942 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2943    buffer we're allowed to write to.  Returns
2944    BUF+CHARACTERS_WRITTEN.  */
2945
2946 char *
2947 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2948 {
2949   int pid, tid;
2950   struct remote_state *rs = get_remote_state ();
2951
2952   if (remote_multi_process_p (rs))
2953     {
2954       pid = ptid.pid ();
2955       if (pid < 0)
2956         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2957       else
2958         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2959     }
2960   tid = ptid.lwp ();
2961   if (tid < 0)
2962     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2963   else
2964     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2965
2966   return buf;
2967 }
2968
2969 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2970    last parsed char.  Returns null_ptid if no thread id is found, and
2971    throws an error if the thread id has an invalid format.  */
2972
2973 static ptid_t
2974 read_ptid (const char *buf, const char **obuf)
2975 {
2976   const char *p = buf;
2977   const char *pp;
2978   ULONGEST pid = 0, tid = 0;
2979
2980   if (*p == 'p')
2981     {
2982       /* Multi-process ptid.  */
2983       pp = unpack_varlen_hex (p + 1, &pid);
2984       if (*pp != '.')
2985         error (_("invalid remote ptid: %s"), p);
2986
2987       p = pp;
2988       pp = unpack_varlen_hex (p + 1, &tid);
2989       if (obuf)
2990         *obuf = pp;
2991       return ptid_t (pid, tid, 0);
2992     }
2993
2994   /* No multi-process.  Just a tid.  */
2995   pp = unpack_varlen_hex (p, &tid);
2996
2997   /* Return null_ptid when no thread id is found.  */
2998   if (p == pp)
2999     {
3000       if (obuf)
3001         *obuf = pp;
3002       return null_ptid;
3003     }
3004
3005   /* Since the stub is not sending a process id, then default to
3006      what's in inferior_ptid, unless it's null at this point.  If so,
3007      then since there's no way to know the pid of the reported
3008      threads, use the magic number.  */
3009   if (inferior_ptid == null_ptid)
3010     pid = magic_null_ptid.pid ();
3011   else
3012     pid = inferior_ptid.pid ();
3013
3014   if (obuf)
3015     *obuf = pp;
3016   return ptid_t (pid, tid, 0);
3017 }
3018
3019 static int
3020 stubhex (int ch)
3021 {
3022   if (ch >= 'a' && ch <= 'f')
3023     return ch - 'a' + 10;
3024   if (ch >= '0' && ch <= '9')
3025     return ch - '0';
3026   if (ch >= 'A' && ch <= 'F')
3027     return ch - 'A' + 10;
3028   return -1;
3029 }
3030
3031 static int
3032 stub_unpack_int (char *buff, int fieldlength)
3033 {
3034   int nibble;
3035   int retval = 0;
3036
3037   while (fieldlength)
3038     {
3039       nibble = stubhex (*buff++);
3040       retval |= nibble;
3041       fieldlength--;
3042       if (fieldlength)
3043         retval = retval << 4;
3044     }
3045   return retval;
3046 }
3047
3048 static char *
3049 unpack_nibble (char *buf, int *val)
3050 {
3051   *val = fromhex (*buf++);
3052   return buf;
3053 }
3054
3055 static char *
3056 unpack_byte (char *buf, int *value)
3057 {
3058   *value = stub_unpack_int (buf, 2);
3059   return buf + 2;
3060 }
3061
3062 static char *
3063 pack_int (char *buf, int value)
3064 {
3065   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3066   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3067   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3068   buf = pack_hex_byte (buf, (value & 0xff));
3069   return buf;
3070 }
3071
3072 static char *
3073 unpack_int (char *buf, int *value)
3074 {
3075   *value = stub_unpack_int (buf, 8);
3076   return buf + 8;
3077 }
3078
3079 #if 0                   /* Currently unused, uncomment when needed.  */
3080 static char *pack_string (char *pkt, char *string);
3081
3082 static char *
3083 pack_string (char *pkt, char *string)
3084 {
3085   char ch;
3086   int len;
3087
3088   len = strlen (string);
3089   if (len > 200)
3090     len = 200;          /* Bigger than most GDB packets, junk???  */
3091   pkt = pack_hex_byte (pkt, len);
3092   while (len-- > 0)
3093     {
3094       ch = *string++;
3095       if ((ch == '\0') || (ch == '#'))
3096         ch = '*';               /* Protect encapsulation.  */
3097       *pkt++ = ch;
3098     }
3099   return pkt;
3100 }
3101 #endif /* 0 (unused) */
3102
3103 static char *
3104 unpack_string (char *src, char *dest, int length)
3105 {
3106   while (length--)
3107     *dest++ = *src++;
3108   *dest = '\0';
3109   return src;
3110 }
3111
3112 static char *
3113 pack_threadid (char *pkt, threadref *id)
3114 {
3115   char *limit;
3116   unsigned char *altid;
3117
3118   altid = (unsigned char *) id;
3119   limit = pkt + BUF_THREAD_ID_SIZE;
3120   while (pkt < limit)
3121     pkt = pack_hex_byte (pkt, *altid++);
3122   return pkt;
3123 }
3124
3125
3126 static char *
3127 unpack_threadid (char *inbuf, threadref *id)
3128 {
3129   char *altref;
3130   char *limit = inbuf + BUF_THREAD_ID_SIZE;
3131   int x, y;
3132
3133   altref = (char *) id;
3134
3135   while (inbuf < limit)
3136     {
3137       x = stubhex (*inbuf++);
3138       y = stubhex (*inbuf++);
3139       *altref++ = (x << 4) | y;
3140     }
3141   return inbuf;
3142 }
3143
3144 /* Externally, threadrefs are 64 bits but internally, they are still
3145    ints.  This is due to a mismatch of specifications.  We would like
3146    to use 64bit thread references internally.  This is an adapter
3147    function.  */
3148
3149 void
3150 int_to_threadref (threadref *id, int value)
3151 {
3152   unsigned char *scan;
3153
3154   scan = (unsigned char *) id;
3155   {
3156     int i = 4;
3157     while (i--)
3158       *scan++ = 0;
3159   }
3160   *scan++ = (value >> 24) & 0xff;
3161   *scan++ = (value >> 16) & 0xff;
3162   *scan++ = (value >> 8) & 0xff;
3163   *scan++ = (value & 0xff);
3164 }
3165
3166 static int
3167 threadref_to_int (threadref *ref)
3168 {
3169   int i, value = 0;
3170   unsigned char *scan;
3171
3172   scan = *ref;
3173   scan += 4;
3174   i = 4;
3175   while (i-- > 0)
3176     value = (value << 8) | ((*scan++) & 0xff);
3177   return value;
3178 }
3179
3180 static void
3181 copy_threadref (threadref *dest, threadref *src)
3182 {
3183   int i;
3184   unsigned char *csrc, *cdest;
3185
3186   csrc = (unsigned char *) src;
3187   cdest = (unsigned char *) dest;
3188   i = 8;
3189   while (i--)
3190     *cdest++ = *csrc++;
3191 }
3192
3193 static int
3194 threadmatch (threadref *dest, threadref *src)
3195 {
3196   /* Things are broken right now, so just assume we got a match.  */
3197 #if 0
3198   unsigned char *srcp, *destp;
3199   int i, result;
3200   srcp = (char *) src;
3201   destp = (char *) dest;
3202
3203   result = 1;
3204   while (i-- > 0)
3205     result &= (*srcp++ == *destp++) ? 1 : 0;
3206   return result;
3207 #endif
3208   return 1;
3209 }
3210
3211 /*
3212    threadid:1,        # always request threadid
3213    context_exists:2,
3214    display:4,
3215    unique_name:8,
3216    more_display:16
3217  */
3218
3219 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
3220
3221 static char *
3222 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3223 {
3224   *pkt++ = 'q';                         /* Info Query */
3225   *pkt++ = 'P';                         /* process or thread info */
3226   pkt = pack_int (pkt, mode);           /* mode */
3227   pkt = pack_threadid (pkt, id);        /* threadid */
3228   *pkt = '\0';                          /* terminate */
3229   return pkt;
3230 }
3231
3232 /* These values tag the fields in a thread info response packet.  */
3233 /* Tagging the fields allows us to request specific fields and to
3234    add more fields as time goes by.  */
3235
3236 #define TAG_THREADID 1          /* Echo the thread identifier.  */
3237 #define TAG_EXISTS 2            /* Is this process defined enough to
3238                                    fetch registers and its stack?  */
3239 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
3240 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
3241 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
3242                                    the process.  */
3243
3244 int
3245 remote_target::remote_unpack_thread_info_response (char *pkt,
3246                                                    threadref *expectedref,
3247                                                    gdb_ext_thread_info *info)
3248 {
3249   struct remote_state *rs = get_remote_state ();
3250   int mask, length;
3251   int tag;
3252   threadref ref;
3253   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
3254   int retval = 1;
3255
3256   /* info->threadid = 0; FIXME: implement zero_threadref.  */
3257   info->active = 0;
3258   info->display[0] = '\0';
3259   info->shortname[0] = '\0';
3260   info->more_display[0] = '\0';
3261
3262   /* Assume the characters indicating the packet type have been
3263      stripped.  */
3264   pkt = unpack_int (pkt, &mask);        /* arg mask */
3265   pkt = unpack_threadid (pkt, &ref);
3266
3267   if (mask == 0)
3268     warning (_("Incomplete response to threadinfo request."));
3269   if (!threadmatch (&ref, expectedref))
3270     {                   /* This is an answer to a different request.  */
3271       warning (_("ERROR RMT Thread info mismatch."));
3272       return 0;
3273     }
3274   copy_threadref (&info->threadid, &ref);
3275
3276   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
3277
3278   /* Packets are terminated with nulls.  */
3279   while ((pkt < limit) && mask && *pkt)
3280     {
3281       pkt = unpack_int (pkt, &tag);     /* tag */
3282       pkt = unpack_byte (pkt, &length); /* length */
3283       if (!(tag & mask))                /* Tags out of synch with mask.  */
3284         {
3285           warning (_("ERROR RMT: threadinfo tag mismatch."));
3286           retval = 0;
3287           break;
3288         }
3289       if (tag == TAG_THREADID)
3290         {
3291           if (length != 16)
3292             {
3293               warning (_("ERROR RMT: length of threadid is not 16."));
3294               retval = 0;
3295               break;
3296             }
3297           pkt = unpack_threadid (pkt, &ref);
3298           mask = mask & ~TAG_THREADID;
3299           continue;
3300         }
3301       if (tag == TAG_EXISTS)
3302         {
3303           info->active = stub_unpack_int (pkt, length);
3304           pkt += length;
3305           mask = mask & ~(TAG_EXISTS);
3306           if (length > 8)
3307             {
3308               warning (_("ERROR RMT: 'exists' length too long."));
3309               retval = 0;
3310               break;
3311             }
3312           continue;
3313         }
3314       if (tag == TAG_THREADNAME)
3315         {
3316           pkt = unpack_string (pkt, &info->shortname[0], length);
3317           mask = mask & ~TAG_THREADNAME;
3318           continue;
3319         }
3320       if (tag == TAG_DISPLAY)
3321         {
3322           pkt = unpack_string (pkt, &info->display[0], length);
3323           mask = mask & ~TAG_DISPLAY;
3324           continue;
3325         }
3326       if (tag == TAG_MOREDISPLAY)
3327         {
3328           pkt = unpack_string (pkt, &info->more_display[0], length);
3329           mask = mask & ~TAG_MOREDISPLAY;
3330           continue;
3331         }
3332       warning (_("ERROR RMT: unknown thread info tag."));
3333       break;                    /* Not a tag we know about.  */
3334     }
3335   return retval;
3336 }
3337
3338 int
3339 remote_target::remote_get_threadinfo (threadref *threadid,
3340                                       int fieldset,
3341                                       gdb_ext_thread_info *info)
3342 {
3343   struct remote_state *rs = get_remote_state ();
3344   int result;
3345
3346   pack_threadinfo_request (rs->buf, fieldset, threadid);
3347   putpkt (rs->buf);
3348   getpkt (&rs->buf, &rs->buf_size, 0);
3349
3350   if (rs->buf[0] == '\0')
3351     return 0;
3352
3353   result = remote_unpack_thread_info_response (rs->buf + 2,
3354                                                threadid, info);
3355   return result;
3356 }
3357
3358 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3359
3360 static char *
3361 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3362                          threadref *nextthread)
3363 {
3364   *pkt++ = 'q';                 /* info query packet */
3365   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3366   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3367   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3368   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3369   *pkt = '\0';
3370   return pkt;
3371 }
3372
3373 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3374
3375 int
3376 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3377                                           threadref *original_echo,
3378                                           threadref *resultlist,
3379                                           int *doneflag)
3380 {
3381   struct remote_state *rs = get_remote_state ();
3382   char *limit;
3383   int count, resultcount, done;
3384
3385   resultcount = 0;
3386   /* Assume the 'q' and 'M chars have been stripped.  */
3387   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3388   /* done parse past here */
3389   pkt = unpack_byte (pkt, &count);      /* count field */
3390   pkt = unpack_nibble (pkt, &done);
3391   /* The first threadid is the argument threadid.  */
3392   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3393   while ((count-- > 0) && (pkt < limit))
3394     {
3395       pkt = unpack_threadid (pkt, resultlist++);
3396       if (resultcount++ >= result_limit)
3397         break;
3398     }
3399   if (doneflag)
3400     *doneflag = done;
3401   return resultcount;
3402 }
3403
3404 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3405    qL packet is not supported, 0 on error and 1 on success.  */
3406
3407 int
3408 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3409                                       int result_limit, int *done, int *result_count,
3410                                       threadref *threadlist)
3411 {
3412   struct remote_state *rs = get_remote_state ();
3413   int result = 1;
3414
3415   /* Trancate result limit to be smaller than the packet size.  */
3416   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3417       >= get_remote_packet_size ())
3418     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3419
3420   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3421   putpkt (rs->buf);
3422   getpkt (&rs->buf, &rs->buf_size, 0);
3423   if (*rs->buf == '\0')
3424     {
3425       /* Packet not supported.  */
3426       return -1;
3427     }
3428
3429   *result_count =
3430     parse_threadlist_response (rs->buf + 2, result_limit,
3431                                &rs->echo_nextthread, threadlist, done);
3432
3433   if (!threadmatch (&rs->echo_nextthread, nextthread))
3434     {
3435       /* FIXME: This is a good reason to drop the packet.  */
3436       /* Possably, there is a duplicate response.  */
3437       /* Possabilities :
3438          retransmit immediatly - race conditions
3439          retransmit after timeout - yes
3440          exit
3441          wait for packet, then exit
3442        */
3443       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3444       return 0;                 /* I choose simply exiting.  */
3445     }
3446   if (*result_count <= 0)
3447     {
3448       if (*done != 1)
3449         {
3450           warning (_("RMT ERROR : failed to get remote thread list."));
3451           result = 0;
3452         }
3453       return result;            /* break; */
3454     }
3455   if (*result_count > result_limit)
3456     {
3457       *result_count = 0;
3458       warning (_("RMT ERROR: threadlist response longer than requested."));
3459       return 0;
3460     }
3461   return result;
3462 }
3463
3464 /* Fetch the list of remote threads, with the qL packet, and call
3465    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3466    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3467    STEPFUNCTION returns false.  If the packet is not supported,
3468    returns -1.  */
3469
3470 int
3471 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3472                                            void *context, int looplimit)
3473 {
3474   struct remote_state *rs = get_remote_state ();
3475   int done, i, result_count;
3476   int startflag = 1;
3477   int result = 1;
3478   int loopcount = 0;
3479
3480   done = 0;
3481   while (!done)
3482     {
3483       if (loopcount++ > looplimit)
3484         {
3485           result = 0;
3486           warning (_("Remote fetch threadlist -infinite loop-."));
3487           break;
3488         }
3489       result = remote_get_threadlist (startflag, &rs->nextthread,
3490                                       MAXTHREADLISTRESULTS,
3491                                       &done, &result_count,
3492                                       rs->resultthreadlist);
3493       if (result <= 0)
3494         break;
3495       /* Clear for later iterations.  */
3496       startflag = 0;
3497       /* Setup to resume next batch of thread references, set nextthread.  */
3498       if (result_count >= 1)
3499         copy_threadref (&rs->nextthread,
3500                         &rs->resultthreadlist[result_count - 1]);
3501       i = 0;
3502       while (result_count--)
3503         {
3504           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3505             {
3506               result = 0;
3507               break;
3508             }
3509         }
3510     }
3511   return result;
3512 }
3513
3514 /* A thread found on the remote target.  */
3515
3516 struct thread_item
3517 {
3518   explicit thread_item (ptid_t ptid_)
3519   : ptid (ptid_)
3520   {}
3521
3522   thread_item (thread_item &&other) = default;
3523   thread_item &operator= (thread_item &&other) = default;
3524
3525   DISABLE_COPY_AND_ASSIGN (thread_item);
3526
3527   /* The thread's PTID.  */
3528   ptid_t ptid;
3529
3530   /* The thread's extra info.  */
3531   std::string extra;
3532
3533   /* The thread's name.  */
3534   std::string name;
3535
3536   /* The core the thread was running on.  -1 if not known.  */
3537   int core = -1;
3538
3539   /* The thread handle associated with the thread.  */
3540   gdb::byte_vector thread_handle;
3541 };
3542
3543 /* Context passed around to the various methods listing remote
3544    threads.  As new threads are found, they're added to the ITEMS
3545    vector.  */
3546
3547 struct threads_listing_context
3548 {
3549   /* Return true if this object contains an entry for a thread with ptid
3550      PTID.  */
3551
3552   bool contains_thread (ptid_t ptid) const
3553   {
3554     auto match_ptid = [&] (const thread_item &item)
3555       {
3556         return item.ptid == ptid;
3557       };
3558
3559     auto it = std::find_if (this->items.begin (),
3560                             this->items.end (),
3561                             match_ptid);
3562
3563     return it != this->items.end ();
3564   }
3565
3566   /* Remove the thread with ptid PTID.  */
3567
3568   void remove_thread (ptid_t ptid)
3569   {
3570     auto match_ptid = [&] (const thread_item &item)
3571       {
3572         return item.ptid == ptid;
3573       };
3574
3575     auto it = std::remove_if (this->items.begin (),
3576                               this->items.end (),
3577                               match_ptid);
3578
3579     if (it != this->items.end ())
3580       this->items.erase (it);
3581   }
3582
3583   /* The threads found on the remote target.  */
3584   std::vector<thread_item> items;
3585 };
3586
3587 static int
3588 remote_newthread_step (threadref *ref, void *data)
3589 {
3590   struct threads_listing_context *context
3591     = (struct threads_listing_context *) data;
3592   int pid = inferior_ptid.pid ();
3593   int lwp = threadref_to_int (ref);
3594   ptid_t ptid (pid, lwp);
3595
3596   context->items.emplace_back (ptid);
3597
3598   return 1;                     /* continue iterator */
3599 }
3600
3601 #define CRAZY_MAX_THREADS 1000
3602
3603 ptid_t
3604 remote_target::remote_current_thread (ptid_t oldpid)
3605 {
3606   struct remote_state *rs = get_remote_state ();
3607
3608   putpkt ("qC");
3609   getpkt (&rs->buf, &rs->buf_size, 0);
3610   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3611     {
3612       const char *obuf;
3613       ptid_t result;
3614
3615       result = read_ptid (&rs->buf[2], &obuf);
3616       if (*obuf != '\0' && remote_debug)
3617         fprintf_unfiltered (gdb_stdlog,
3618                             "warning: garbage in qC reply\n");
3619
3620       return result;
3621     }
3622   else
3623     return oldpid;
3624 }
3625
3626 /* List remote threads using the deprecated qL packet.  */
3627
3628 int
3629 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3630 {
3631   if (remote_threadlist_iterator (remote_newthread_step, context,
3632                                   CRAZY_MAX_THREADS) >= 0)
3633     return 1;
3634
3635   return 0;
3636 }
3637
3638 #if defined(HAVE_LIBEXPAT)
3639
3640 static void
3641 start_thread (struct gdb_xml_parser *parser,
3642               const struct gdb_xml_element *element,
3643               void *user_data,
3644               std::vector<gdb_xml_value> &attributes)
3645 {
3646   struct threads_listing_context *data
3647     = (struct threads_listing_context *) user_data;
3648   struct gdb_xml_value *attr;
3649
3650   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3651   ptid_t ptid = read_ptid (id, NULL);
3652
3653   data->items.emplace_back (ptid);
3654   thread_item &item = data->items.back ();
3655
3656   attr = xml_find_attribute (attributes, "core");
3657   if (attr != NULL)
3658     item.core = *(ULONGEST *) attr->value.get ();
3659
3660   attr = xml_find_attribute (attributes, "name");
3661   if (attr != NULL)
3662     item.name = (const char *) attr->value.get ();
3663
3664   attr = xml_find_attribute (attributes, "handle");
3665   if (attr != NULL)
3666     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3667 }
3668
3669 static void
3670 end_thread (struct gdb_xml_parser *parser,
3671             const struct gdb_xml_element *element,
3672             void *user_data, const char *body_text)
3673 {
3674   struct threads_listing_context *data
3675     = (struct threads_listing_context *) user_data;
3676
3677   if (body_text != NULL && *body_text != '\0')
3678     data->items.back ().extra = body_text;
3679 }
3680
3681 const struct gdb_xml_attribute thread_attributes[] = {
3682   { "id", GDB_XML_AF_NONE, NULL, NULL },
3683   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3684   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3685   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3686   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3687 };
3688
3689 const struct gdb_xml_element thread_children[] = {
3690   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3691 };
3692
3693 const struct gdb_xml_element threads_children[] = {
3694   { "thread", thread_attributes, thread_children,
3695     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3696     start_thread, end_thread },
3697   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3698 };
3699
3700 const struct gdb_xml_element threads_elements[] = {
3701   { "threads", NULL, threads_children,
3702     GDB_XML_EF_NONE, NULL, NULL },
3703   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3704 };
3705
3706 #endif
3707
3708 /* List remote threads using qXfer:threads:read.  */
3709
3710 int
3711 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3712 {
3713 #if defined(HAVE_LIBEXPAT)
3714   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3715     {
3716       gdb::optional<gdb::char_vector> xml
3717         = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3718
3719       if (xml && (*xml)[0] != '\0')
3720         {
3721           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3722                                threads_elements, xml->data (), context);
3723         }
3724
3725       return 1;
3726     }
3727 #endif
3728
3729   return 0;
3730 }
3731
3732 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3733
3734 int
3735 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3736 {
3737   struct remote_state *rs = get_remote_state ();
3738
3739   if (rs->use_threadinfo_query)
3740     {
3741       const char *bufp;
3742
3743       putpkt ("qfThreadInfo");
3744       getpkt (&rs->buf, &rs->buf_size, 0);
3745       bufp = rs->buf;
3746       if (bufp[0] != '\0')              /* q packet recognized */
3747         {
3748           while (*bufp++ == 'm')        /* reply contains one or more TID */
3749             {
3750               do
3751                 {
3752                   ptid_t ptid = read_ptid (bufp, &bufp);
3753                   context->items.emplace_back (ptid);
3754                 }
3755               while (*bufp++ == ',');   /* comma-separated list */
3756               putpkt ("qsThreadInfo");
3757               getpkt (&rs->buf, &rs->buf_size, 0);
3758               bufp = rs->buf;
3759             }
3760           return 1;
3761         }
3762       else
3763         {
3764           /* Packet not recognized.  */
3765           rs->use_threadinfo_query = 0;
3766         }
3767     }
3768
3769   return 0;
3770 }
3771
3772 /* Implement the to_update_thread_list function for the remote
3773    targets.  */
3774
3775 void
3776 remote_target::update_thread_list ()
3777 {
3778   struct threads_listing_context context;
3779   int got_list = 0;
3780
3781   /* We have a few different mechanisms to fetch the thread list.  Try
3782      them all, starting with the most preferred one first, falling
3783      back to older methods.  */
3784   if (remote_get_threads_with_qxfer (&context)
3785       || remote_get_threads_with_qthreadinfo (&context)
3786       || remote_get_threads_with_ql (&context))
3787     {
3788       struct thread_info *tp, *tmp;
3789
3790       got_list = 1;
3791
3792       if (context.items.empty ()
3793           && remote_thread_always_alive (inferior_ptid))
3794         {
3795           /* Some targets don't really support threads, but still
3796              reply an (empty) thread list in response to the thread
3797              listing packets, instead of replying "packet not
3798              supported".  Exit early so we don't delete the main
3799              thread.  */
3800           return;
3801         }
3802
3803       /* CONTEXT now holds the current thread list on the remote
3804          target end.  Delete GDB-side threads no longer found on the
3805          target.  */
3806       ALL_THREADS_SAFE (tp, tmp)
3807         {
3808           if (!context.contains_thread (tp->ptid))
3809             {
3810               /* Not found.  */
3811               delete_thread (tp);
3812             }
3813         }
3814
3815       /* Remove any unreported fork child threads from CONTEXT so
3816          that we don't interfere with follow fork, which is where
3817          creation of such threads is handled.  */
3818       remove_new_fork_children (&context);
3819
3820       /* And now add threads we don't know about yet to our list.  */
3821       for (thread_item &item : context.items)
3822         {
3823           if (item.ptid != null_ptid)
3824             {
3825               /* In non-stop mode, we assume new found threads are
3826                  executing until proven otherwise with a stop reply.
3827                  In all-stop, we can only get here if all threads are
3828                  stopped.  */
3829               int executing = target_is_non_stop_p () ? 1 : 0;
3830
3831               remote_notice_new_inferior (item.ptid, executing);
3832
3833               thread_info *tp = find_thread_ptid (item.ptid);
3834               remote_thread_info *info = get_remote_thread_info (tp);
3835               info->core = item.core;
3836               info->extra = std::move (item.extra);
3837               info->name = std::move (item.name);
3838               info->thread_handle = std::move (item.thread_handle);
3839             }
3840         }
3841     }
3842
3843   if (!got_list)
3844     {
3845       /* If no thread listing method is supported, then query whether
3846          each known thread is alive, one by one, with the T packet.
3847          If the target doesn't support threads at all, then this is a
3848          no-op.  See remote_thread_alive.  */
3849       prune_threads ();
3850     }
3851 }
3852
3853 /*
3854  * Collect a descriptive string about the given thread.
3855  * The target may say anything it wants to about the thread
3856  * (typically info about its blocked / runnable state, name, etc.).
3857  * This string will appear in the info threads display.
3858  *
3859  * Optional: targets are not required to implement this function.
3860  */
3861
3862 const char *
3863 remote_target::extra_thread_info (thread_info *tp)
3864 {
3865   struct remote_state *rs = get_remote_state ();
3866   int set;
3867   threadref id;
3868   struct gdb_ext_thread_info threadinfo;
3869
3870   if (rs->remote_desc == 0)             /* paranoia */
3871     internal_error (__FILE__, __LINE__,
3872                     _("remote_threads_extra_info"));
3873
3874   if (tp->ptid == magic_null_ptid
3875       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
3876     /* This is the main thread which was added by GDB.  The remote
3877        server doesn't know about it.  */
3878     return NULL;
3879
3880   std::string &extra = get_remote_thread_info (tp)->extra;
3881
3882   /* If already have cached info, use it.  */
3883   if (!extra.empty ())
3884     return extra.c_str ();
3885
3886   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3887     {
3888       /* If we're using qXfer:threads:read, then the extra info is
3889          included in the XML.  So if we didn't have anything cached,
3890          it's because there's really no extra info.  */
3891       return NULL;
3892     }
3893
3894   if (rs->use_threadextra_query)
3895     {
3896       char *b = rs->buf;
3897       char *endb = rs->buf + get_remote_packet_size ();
3898
3899       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3900       b += strlen (b);
3901       write_ptid (b, endb, tp->ptid);
3902
3903       putpkt (rs->buf);
3904       getpkt (&rs->buf, &rs->buf_size, 0);
3905       if (rs->buf[0] != 0)
3906         {
3907           extra.resize (strlen (rs->buf) / 2);
3908           hex2bin (rs->buf, (gdb_byte *) &extra[0], extra.size ());
3909           return extra.c_str ();
3910         }
3911     }
3912
3913   /* If the above query fails, fall back to the old method.  */
3914   rs->use_threadextra_query = 0;
3915   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3916     | TAG_MOREDISPLAY | TAG_DISPLAY;
3917   int_to_threadref (&id, tp->ptid.lwp ());
3918   if (remote_get_threadinfo (&id, set, &threadinfo))
3919     if (threadinfo.active)
3920       {
3921         if (*threadinfo.shortname)
3922           string_appendf (extra, " Name: %s", threadinfo.shortname);
3923         if (*threadinfo.display)
3924           {
3925             if (!extra.empty ())
3926               extra += ',';
3927             string_appendf (extra, " State: %s", threadinfo.display);
3928           }
3929         if (*threadinfo.more_display)
3930           {
3931             if (!extra.empty ())
3932               extra += ',';
3933             string_appendf (extra, " Priority: %s", threadinfo.more_display);
3934           }
3935         return extra.c_str ();
3936       }
3937   return NULL;
3938 }
3939 \f
3940
3941 bool
3942 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3943                                             struct static_tracepoint_marker *marker)
3944 {
3945   struct remote_state *rs = get_remote_state ();
3946   char *p = rs->buf;
3947
3948   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3949   p += strlen (p);
3950   p += hexnumstr (p, addr);
3951   putpkt (rs->buf);
3952   getpkt (&rs->buf, &rs->buf_size, 0);
3953   p = rs->buf;
3954
3955   if (*p == 'E')
3956     error (_("Remote failure reply: %s"), p);
3957
3958   if (*p++ == 'm')
3959     {
3960       parse_static_tracepoint_marker_definition (p, NULL, marker);
3961       return true;
3962     }
3963
3964   return false;
3965 }
3966
3967 std::vector<static_tracepoint_marker>
3968 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3969 {
3970   struct remote_state *rs = get_remote_state ();
3971   std::vector<static_tracepoint_marker> markers;
3972   const char *p;
3973   static_tracepoint_marker marker;
3974
3975   /* Ask for a first packet of static tracepoint marker
3976      definition.  */
3977   putpkt ("qTfSTM");
3978   getpkt (&rs->buf, &rs->buf_size, 0);
3979   p = rs->buf;
3980   if (*p == 'E')
3981     error (_("Remote failure reply: %s"), p);
3982
3983   while (*p++ == 'm')
3984     {
3985       do
3986         {
3987           parse_static_tracepoint_marker_definition (p, &p, &marker);
3988
3989           if (strid == NULL || marker.str_id == strid)
3990             markers.push_back (std::move (marker));
3991         }
3992       while (*p++ == ',');      /* comma-separated list */
3993       /* Ask for another packet of static tracepoint definition.  */
3994       putpkt ("qTsSTM");
3995       getpkt (&rs->buf, &rs->buf_size, 0);
3996       p = rs->buf;
3997     }
3998
3999   return markers;
4000 }
4001
4002 \f
4003 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
4004
4005 ptid_t
4006 remote_target::get_ada_task_ptid (long lwp, long thread)
4007 {
4008   return ptid_t (inferior_ptid.pid (), lwp, 0);
4009 }
4010 \f
4011
4012 /* Restart the remote side; this is an extended protocol operation.  */
4013
4014 void
4015 remote_target::extended_remote_restart ()
4016 {
4017   struct remote_state *rs = get_remote_state ();
4018
4019   /* Send the restart command; for reasons I don't understand the
4020      remote side really expects a number after the "R".  */
4021   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
4022   putpkt (rs->buf);
4023
4024   remote_fileio_reset ();
4025 }
4026 \f
4027 /* Clean up connection to a remote debugger.  */
4028
4029 void
4030 remote_target::close ()
4031 {
4032   /* Make sure we leave stdin registered in the event loop.  */
4033   terminal_ours ();
4034
4035   /* We don't have a connection to the remote stub anymore.  Get rid
4036      of all the inferiors and their threads we were controlling.
4037      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4038      will be unable to find the thread corresponding to (pid, 0, 0).  */
4039   inferior_ptid = null_ptid;
4040   discard_all_inferiors ();
4041
4042   trace_reset_local_state ();
4043
4044   delete this;
4045 }
4046
4047 remote_target::~remote_target ()
4048 {
4049   struct remote_state *rs = get_remote_state ();
4050
4051   /* Check for NULL because we may get here with a partially
4052      constructed target/connection.  */
4053   if (rs->remote_desc == nullptr)
4054     return;
4055
4056   serial_close (rs->remote_desc);
4057
4058   /* We are destroying the remote target, so we should discard
4059      everything of this target.  */
4060   discard_pending_stop_replies_in_queue ();
4061
4062   if (rs->remote_async_inferior_event_token)
4063     delete_async_event_handler (&rs->remote_async_inferior_event_token);
4064
4065   remote_notif_state_xfree (rs->notif_state);
4066 }
4067
4068 /* Query the remote side for the text, data and bss offsets.  */
4069
4070 void
4071 remote_target::get_offsets ()
4072 {
4073   struct remote_state *rs = get_remote_state ();
4074   char *buf;
4075   char *ptr;
4076   int lose, num_segments = 0, do_sections, do_segments;
4077   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4078   struct section_offsets *offs;
4079   struct symfile_segment_data *data;
4080
4081   if (symfile_objfile == NULL)
4082     return;
4083
4084   putpkt ("qOffsets");
4085   getpkt (&rs->buf, &rs->buf_size, 0);
4086   buf = rs->buf;
4087
4088   if (buf[0] == '\000')
4089     return;                     /* Return silently.  Stub doesn't support
4090                                    this command.  */
4091   if (buf[0] == 'E')
4092     {
4093       warning (_("Remote failure reply: %s"), buf);
4094       return;
4095     }
4096
4097   /* Pick up each field in turn.  This used to be done with scanf, but
4098      scanf will make trouble if CORE_ADDR size doesn't match
4099      conversion directives correctly.  The following code will work
4100      with any size of CORE_ADDR.  */
4101   text_addr = data_addr = bss_addr = 0;
4102   ptr = buf;
4103   lose = 0;
4104
4105   if (startswith (ptr, "Text="))
4106     {
4107       ptr += 5;
4108       /* Don't use strtol, could lose on big values.  */
4109       while (*ptr && *ptr != ';')
4110         text_addr = (text_addr << 4) + fromhex (*ptr++);
4111
4112       if (startswith (ptr, ";Data="))
4113         {
4114           ptr += 6;
4115           while (*ptr && *ptr != ';')
4116             data_addr = (data_addr << 4) + fromhex (*ptr++);
4117         }
4118       else
4119         lose = 1;
4120
4121       if (!lose && startswith (ptr, ";Bss="))
4122         {
4123           ptr += 5;
4124           while (*ptr && *ptr != ';')
4125             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4126
4127           if (bss_addr != data_addr)
4128             warning (_("Target reported unsupported offsets: %s"), buf);
4129         }
4130       else
4131         lose = 1;
4132     }
4133   else if (startswith (ptr, "TextSeg="))
4134     {
4135       ptr += 8;
4136       /* Don't use strtol, could lose on big values.  */
4137       while (*ptr && *ptr != ';')
4138         text_addr = (text_addr << 4) + fromhex (*ptr++);
4139       num_segments = 1;
4140
4141       if (startswith (ptr, ";DataSeg="))
4142         {
4143           ptr += 9;
4144           while (*ptr && *ptr != ';')
4145             data_addr = (data_addr << 4) + fromhex (*ptr++);
4146           num_segments++;
4147         }
4148     }
4149   else
4150     lose = 1;
4151
4152   if (lose)
4153     error (_("Malformed response to offset query, %s"), buf);
4154   else if (*ptr != '\0')
4155     warning (_("Target reported unsupported offsets: %s"), buf);
4156
4157   offs = ((struct section_offsets *)
4158           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4159   memcpy (offs, symfile_objfile->section_offsets,
4160           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4161
4162   data = get_symfile_segment_data (symfile_objfile->obfd);
4163   do_segments = (data != NULL);
4164   do_sections = num_segments == 0;
4165
4166   if (num_segments > 0)
4167     {
4168       segments[0] = text_addr;
4169       segments[1] = data_addr;
4170     }
4171   /* If we have two segments, we can still try to relocate everything
4172      by assuming that the .text and .data offsets apply to the whole
4173      text and data segments.  Convert the offsets given in the packet
4174      to base addresses for symfile_map_offsets_to_segments.  */
4175   else if (data && data->num_segments == 2)
4176     {
4177       segments[0] = data->segment_bases[0] + text_addr;
4178       segments[1] = data->segment_bases[1] + data_addr;
4179       num_segments = 2;
4180     }
4181   /* If the object file has only one segment, assume that it is text
4182      rather than data; main programs with no writable data are rare,
4183      but programs with no code are useless.  Of course the code might
4184      have ended up in the data segment... to detect that we would need
4185      the permissions here.  */
4186   else if (data && data->num_segments == 1)
4187     {
4188       segments[0] = data->segment_bases[0] + text_addr;
4189       num_segments = 1;
4190     }
4191   /* There's no way to relocate by segment.  */
4192   else
4193     do_segments = 0;
4194
4195   if (do_segments)
4196     {
4197       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4198                                                  offs, num_segments, segments);
4199
4200       if (ret == 0 && !do_sections)
4201         error (_("Can not handle qOffsets TextSeg "
4202                  "response with this symbol file"));
4203
4204       if (ret > 0)
4205         do_sections = 0;
4206     }
4207
4208   if (data)
4209     free_symfile_segment_data (data);
4210
4211   if (do_sections)
4212     {
4213       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4214
4215       /* This is a temporary kludge to force data and bss to use the
4216          same offsets because that's what nlmconv does now.  The real
4217          solution requires changes to the stub and remote.c that I
4218          don't have time to do right now.  */
4219
4220       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4221       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4222     }
4223
4224   objfile_relocate (symfile_objfile, offs);
4225 }
4226
4227 /* Send interrupt_sequence to remote target.  */
4228
4229 void
4230 remote_target::send_interrupt_sequence ()
4231 {
4232   struct remote_state *rs = get_remote_state ();
4233
4234   if (interrupt_sequence_mode == interrupt_sequence_control_c)
4235     remote_serial_write ("\x03", 1);
4236   else if (interrupt_sequence_mode == interrupt_sequence_break)
4237     serial_send_break (rs->remote_desc);
4238   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4239     {
4240       serial_send_break (rs->remote_desc);
4241       remote_serial_write ("g", 1);
4242     }
4243   else
4244     internal_error (__FILE__, __LINE__,
4245                     _("Invalid value for interrupt_sequence_mode: %s."),
4246                     interrupt_sequence_mode);
4247 }
4248
4249
4250 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4251    and extract the PTID.  Returns NULL_PTID if not found.  */
4252
4253 static ptid_t
4254 stop_reply_extract_thread (char *stop_reply)
4255 {
4256   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4257     {
4258       const char *p;
4259
4260       /* Txx r:val ; r:val (...)  */
4261       p = &stop_reply[3];
4262
4263       /* Look for "register" named "thread".  */
4264       while (*p != '\0')
4265         {
4266           const char *p1;
4267
4268           p1 = strchr (p, ':');
4269           if (p1 == NULL)
4270             return null_ptid;
4271
4272           if (strncmp (p, "thread", p1 - p) == 0)
4273             return read_ptid (++p1, &p);
4274
4275           p1 = strchr (p, ';');
4276           if (p1 == NULL)
4277             return null_ptid;
4278           p1++;
4279
4280           p = p1;
4281         }
4282     }
4283
4284   return null_ptid;
4285 }
4286
4287 /* Determine the remote side's current thread.  If we have a stop
4288    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4289    "thread" register we can extract the current thread from.  If not,
4290    ask the remote which is the current thread with qC.  The former
4291    method avoids a roundtrip.  */
4292
4293 ptid_t
4294 remote_target::get_current_thread (char *wait_status)
4295 {
4296   ptid_t ptid = null_ptid;
4297
4298   /* Note we don't use remote_parse_stop_reply as that makes use of
4299      the target architecture, which we haven't yet fully determined at
4300      this point.  */
4301   if (wait_status != NULL)
4302     ptid = stop_reply_extract_thread (wait_status);
4303   if (ptid == null_ptid)
4304     ptid = remote_current_thread (inferior_ptid);
4305
4306   return ptid;
4307 }
4308
4309 /* Query the remote target for which is the current thread/process,
4310    add it to our tables, and update INFERIOR_PTID.  The caller is
4311    responsible for setting the state such that the remote end is ready
4312    to return the current thread.
4313
4314    This function is called after handling the '?' or 'vRun' packets,
4315    whose response is a stop reply from which we can also try
4316    extracting the thread.  If the target doesn't support the explicit
4317    qC query, we infer the current thread from that stop reply, passed
4318    in in WAIT_STATUS, which may be NULL.  */
4319
4320 void
4321 remote_target::add_current_inferior_and_thread (char *wait_status)
4322 {
4323   struct remote_state *rs = get_remote_state ();
4324   int fake_pid_p = 0;
4325
4326   inferior_ptid = null_ptid;
4327
4328   /* Now, if we have thread information, update inferior_ptid.  */
4329   ptid_t curr_ptid = get_current_thread (wait_status);
4330
4331   if (curr_ptid != null_ptid)
4332     {
4333       if (!remote_multi_process_p (rs))
4334         fake_pid_p = 1;
4335     }
4336   else
4337     {
4338       /* Without this, some commands which require an active target
4339          (such as kill) won't work.  This variable serves (at least)
4340          double duty as both the pid of the target process (if it has
4341          such), and as a flag indicating that a target is active.  */
4342       curr_ptid = magic_null_ptid;
4343       fake_pid_p = 1;
4344     }
4345
4346   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4347
4348   /* Add the main thread and switch to it.  Don't try reading
4349      registers yet, since we haven't fetched the target description
4350      yet.  */
4351   thread_info *tp = add_thread_silent (curr_ptid);
4352   switch_to_thread_no_regs (tp);
4353 }
4354
4355 /* Print info about a thread that was found already stopped on
4356    connection.  */
4357
4358 static void
4359 print_one_stopped_thread (struct thread_info *thread)
4360 {
4361   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4362
4363   switch_to_thread (thread);
4364   thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4365   set_current_sal_from_frame (get_current_frame ());
4366
4367   thread->suspend.waitstatus_pending_p = 0;
4368
4369   if (ws->kind == TARGET_WAITKIND_STOPPED)
4370     {
4371       enum gdb_signal sig = ws->value.sig;
4372
4373       if (signal_print_state (sig))
4374         gdb::observers::signal_received.notify (sig);
4375     }
4376   gdb::observers::normal_stop.notify (NULL, 1);
4377 }
4378
4379 /* Process all initial stop replies the remote side sent in response
4380    to the ? packet.  These indicate threads that were already stopped
4381    on initial connection.  We mark these threads as stopped and print
4382    their current frame before giving the user the prompt.  */
4383
4384 void
4385 remote_target::process_initial_stop_replies (int from_tty)
4386 {
4387   int pending_stop_replies = stop_reply_queue_length ();
4388   struct inferior *inf;
4389   struct thread_info *thread;
4390   struct thread_info *selected = NULL;
4391   struct thread_info *lowest_stopped = NULL;
4392   struct thread_info *first = NULL;
4393
4394   /* Consume the initial pending events.  */
4395   while (pending_stop_replies-- > 0)
4396     {
4397       ptid_t waiton_ptid = minus_one_ptid;
4398       ptid_t event_ptid;
4399       struct target_waitstatus ws;
4400       int ignore_event = 0;
4401       struct thread_info *thread;
4402
4403       memset (&ws, 0, sizeof (ws));
4404       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4405       if (remote_debug)
4406         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4407
4408       switch (ws.kind)
4409         {
4410         case TARGET_WAITKIND_IGNORE:
4411         case TARGET_WAITKIND_NO_RESUMED:
4412         case TARGET_WAITKIND_SIGNALLED:
4413         case TARGET_WAITKIND_EXITED:
4414           /* We shouldn't see these, but if we do, just ignore.  */
4415           if (remote_debug)
4416             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4417           ignore_event = 1;
4418           break;
4419
4420         case TARGET_WAITKIND_EXECD:
4421           xfree (ws.value.execd_pathname);
4422           break;
4423         default:
4424           break;
4425         }
4426
4427       if (ignore_event)
4428         continue;
4429
4430       thread = find_thread_ptid (event_ptid);
4431
4432       if (ws.kind == TARGET_WAITKIND_STOPPED)
4433         {
4434           enum gdb_signal sig = ws.value.sig;
4435
4436           /* Stubs traditionally report SIGTRAP as initial signal,
4437              instead of signal 0.  Suppress it.  */
4438           if (sig == GDB_SIGNAL_TRAP)
4439             sig = GDB_SIGNAL_0;
4440           thread->suspend.stop_signal = sig;
4441           ws.value.sig = sig;
4442         }
4443
4444       thread->suspend.waitstatus = ws;
4445
4446       if (ws.kind != TARGET_WAITKIND_STOPPED
4447           || ws.value.sig != GDB_SIGNAL_0)
4448         thread->suspend.waitstatus_pending_p = 1;
4449
4450       set_executing (event_ptid, 0);
4451       set_running (event_ptid, 0);
4452       get_remote_thread_info (thread)->vcont_resumed = 0;
4453     }
4454
4455   /* "Notice" the new inferiors before anything related to
4456      registers/memory.  */
4457   ALL_INFERIORS (inf)
4458     {
4459       if (inf->pid == 0)
4460         continue;
4461
4462       inf->needs_setup = 1;
4463
4464       if (non_stop)
4465         {
4466           thread = any_live_thread_of_inferior (inf);
4467           notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4468                                from_tty);
4469         }
4470     }
4471
4472   /* If all-stop on top of non-stop, pause all threads.  Note this
4473      records the threads' stop pc, so must be done after "noticing"
4474      the inferiors.  */
4475   if (!non_stop)
4476     {
4477       stop_all_threads ();
4478
4479       /* If all threads of an inferior were already stopped, we
4480          haven't setup the inferior yet.  */
4481       ALL_INFERIORS (inf)
4482         {
4483           if (inf->pid == 0)
4484             continue;
4485
4486           if (inf->needs_setup)
4487             {
4488               thread = any_live_thread_of_inferior (inf);
4489               switch_to_thread_no_regs (thread);
4490               setup_inferior (0);
4491             }
4492         }
4493     }
4494
4495   /* Now go over all threads that are stopped, and print their current
4496      frame.  If all-stop, then if there's a signalled thread, pick
4497      that as current.  */
4498   ALL_NON_EXITED_THREADS (thread)
4499     {
4500       if (first == NULL)
4501         first = thread;
4502
4503       if (!non_stop)
4504         thread->set_running (false);
4505       else if (thread->state != THREAD_STOPPED)
4506         continue;
4507
4508       if (selected == NULL
4509           && thread->suspend.waitstatus_pending_p)
4510         selected = thread;
4511
4512       if (lowest_stopped == NULL
4513           || thread->inf->num < lowest_stopped->inf->num
4514           || thread->per_inf_num < lowest_stopped->per_inf_num)
4515         lowest_stopped = thread;
4516
4517       if (non_stop)
4518         print_one_stopped_thread (thread);
4519     }
4520
4521   /* In all-stop, we only print the status of one thread, and leave
4522      others with their status pending.  */
4523   if (!non_stop)
4524     {
4525       thread = selected;
4526       if (thread == NULL)
4527         thread = lowest_stopped;
4528       if (thread == NULL)
4529         thread = first;
4530
4531       print_one_stopped_thread (thread);
4532     }
4533
4534   /* For "info program".  */
4535   thread = inferior_thread ();
4536   if (thread->state == THREAD_STOPPED)
4537     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4538 }
4539
4540 /* Start the remote connection and sync state.  */
4541
4542 void
4543 remote_target::start_remote (int from_tty, int extended_p)
4544 {
4545   struct remote_state *rs = get_remote_state ();
4546   struct packet_config *noack_config;
4547   char *wait_status = NULL;
4548
4549   /* Signal other parts that we're going through the initial setup,
4550      and so things may not be stable yet.  E.g., we don't try to
4551      install tracepoints until we've relocated symbols.  Also, a
4552      Ctrl-C before we're connected and synced up can't interrupt the
4553      target.  Instead, it offers to drop the (potentially wedged)
4554      connection.  */
4555   rs->starting_up = 1;
4556
4557   QUIT;
4558
4559   if (interrupt_on_connect)
4560     send_interrupt_sequence ();
4561
4562   /* Ack any packet which the remote side has already sent.  */
4563   remote_serial_write ("+", 1);
4564
4565   /* The first packet we send to the target is the optional "supported
4566      packets" request.  If the target can answer this, it will tell us
4567      which later probes to skip.  */
4568   remote_query_supported ();
4569
4570   /* If the stub wants to get a QAllow, compose one and send it.  */
4571   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4572     set_permissions ();
4573
4574   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4575      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4576      as a reply to known packet.  For packet "vFile:setfs:" it is an
4577      invalid reply and GDB would return error in
4578      remote_hostio_set_filesystem, making remote files access impossible.
4579      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4580      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4581   {
4582     const char v_mustreplyempty[] = "vMustReplyEmpty";
4583
4584     putpkt (v_mustreplyempty);
4585     getpkt (&rs->buf, &rs->buf_size, 0);
4586     if (strcmp (rs->buf, "OK") == 0)
4587       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4588     else if (strcmp (rs->buf, "") != 0)
4589       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4590              rs->buf);
4591   }
4592
4593   /* Next, we possibly activate noack mode.
4594
4595      If the QStartNoAckMode packet configuration is set to AUTO,
4596      enable noack mode if the stub reported a wish for it with
4597      qSupported.
4598
4599      If set to TRUE, then enable noack mode even if the stub didn't
4600      report it in qSupported.  If the stub doesn't reply OK, the
4601      session ends with an error.
4602
4603      If FALSE, then don't activate noack mode, regardless of what the
4604      stub claimed should be the default with qSupported.  */
4605
4606   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4607   if (packet_config_support (noack_config) != PACKET_DISABLE)
4608     {
4609       putpkt ("QStartNoAckMode");
4610       getpkt (&rs->buf, &rs->buf_size, 0);
4611       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4612         rs->noack_mode = 1;
4613     }
4614
4615   if (extended_p)
4616     {
4617       /* Tell the remote that we are using the extended protocol.  */
4618       putpkt ("!");
4619       getpkt (&rs->buf, &rs->buf_size, 0);
4620     }
4621
4622   /* Let the target know which signals it is allowed to pass down to
4623      the program.  */
4624   update_signals_program_target ();
4625
4626   /* Next, if the target can specify a description, read it.  We do
4627      this before anything involving memory or registers.  */
4628   target_find_description ();
4629
4630   /* Next, now that we know something about the target, update the
4631      address spaces in the program spaces.  */
4632   update_address_spaces ();
4633
4634   /* On OSs where the list of libraries is global to all
4635      processes, we fetch them early.  */
4636   if (gdbarch_has_global_solist (target_gdbarch ()))
4637     solib_add (NULL, from_tty, auto_solib_add);
4638
4639   if (target_is_non_stop_p ())
4640     {
4641       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4642         error (_("Non-stop mode requested, but remote "
4643                  "does not support non-stop"));
4644
4645       putpkt ("QNonStop:1");
4646       getpkt (&rs->buf, &rs->buf_size, 0);
4647
4648       if (strcmp (rs->buf, "OK") != 0)
4649         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4650
4651       /* Find about threads and processes the stub is already
4652          controlling.  We default to adding them in the running state.
4653          The '?' query below will then tell us about which threads are
4654          stopped.  */
4655       this->update_thread_list ();
4656     }
4657   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4658     {
4659       /* Don't assume that the stub can operate in all-stop mode.
4660          Request it explicitly.  */
4661       putpkt ("QNonStop:0");
4662       getpkt (&rs->buf, &rs->buf_size, 0);
4663
4664       if (strcmp (rs->buf, "OK") != 0)
4665         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4666     }
4667
4668   /* Upload TSVs regardless of whether the target is running or not.  The
4669      remote stub, such as GDBserver, may have some predefined or builtin
4670      TSVs, even if the target is not running.  */
4671   if (get_trace_status (current_trace_status ()) != -1)
4672     {
4673       struct uploaded_tsv *uploaded_tsvs = NULL;
4674
4675       upload_trace_state_variables (&uploaded_tsvs);
4676       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4677     }
4678
4679   /* Check whether the target is running now.  */
4680   putpkt ("?");
4681   getpkt (&rs->buf, &rs->buf_size, 0);
4682
4683   if (!target_is_non_stop_p ())
4684     {
4685       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4686         {
4687           if (!extended_p)
4688             error (_("The target is not running (try extended-remote?)"));
4689
4690           /* We're connected, but not running.  Drop out before we
4691              call start_remote.  */
4692           rs->starting_up = 0;
4693           return;
4694         }
4695       else
4696         {
4697           /* Save the reply for later.  */
4698           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4699           strcpy (wait_status, rs->buf);
4700         }
4701
4702       /* Fetch thread list.  */
4703       target_update_thread_list ();
4704
4705       /* Let the stub know that we want it to return the thread.  */
4706       set_continue_thread (minus_one_ptid);
4707
4708       if (thread_count () == 0)
4709         {
4710           /* Target has no concept of threads at all.  GDB treats
4711              non-threaded target as single-threaded; add a main
4712              thread.  */
4713           add_current_inferior_and_thread (wait_status);
4714         }
4715       else
4716         {
4717           /* We have thread information; select the thread the target
4718              says should be current.  If we're reconnecting to a
4719              multi-threaded program, this will ideally be the thread
4720              that last reported an event before GDB disconnected.  */
4721           inferior_ptid = get_current_thread (wait_status);
4722           if (inferior_ptid == null_ptid)
4723             {
4724               /* Odd... The target was able to list threads, but not
4725                  tell us which thread was current (no "thread"
4726                  register in T stop reply?).  Just pick the first
4727                  thread in the thread list then.  */
4728               
4729               if (remote_debug)
4730                 fprintf_unfiltered (gdb_stdlog,
4731                                     "warning: couldn't determine remote "
4732                                     "current thread; picking first in list.\n");
4733
4734               inferior_ptid = thread_list->ptid;
4735             }
4736         }
4737
4738       /* init_wait_for_inferior should be called before get_offsets in order
4739          to manage `inserted' flag in bp loc in a correct state.
4740          breakpoint_init_inferior, called from init_wait_for_inferior, set
4741          `inserted' flag to 0, while before breakpoint_re_set, called from
4742          start_remote, set `inserted' flag to 1.  In the initialization of
4743          inferior, breakpoint_init_inferior should be called first, and then
4744          breakpoint_re_set can be called.  If this order is broken, state of
4745          `inserted' flag is wrong, and cause some problems on breakpoint
4746          manipulation.  */
4747       init_wait_for_inferior ();
4748
4749       get_offsets ();           /* Get text, data & bss offsets.  */
4750
4751       /* If we could not find a description using qXfer, and we know
4752          how to do it some other way, try again.  This is not
4753          supported for non-stop; it could be, but it is tricky if
4754          there are no stopped threads when we connect.  */
4755       if (remote_read_description_p (this)
4756           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4757         {
4758           target_clear_description ();
4759           target_find_description ();
4760         }
4761
4762       /* Use the previously fetched status.  */
4763       gdb_assert (wait_status != NULL);
4764       strcpy (rs->buf, wait_status);
4765       rs->cached_wait_status = 1;
4766
4767       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4768     }
4769   else
4770     {
4771       /* Clear WFI global state.  Do this before finding about new
4772          threads and inferiors, and setting the current inferior.
4773          Otherwise we would clear the proceed status of the current
4774          inferior when we want its stop_soon state to be preserved
4775          (see notice_new_inferior).  */
4776       init_wait_for_inferior ();
4777
4778       /* In non-stop, we will either get an "OK", meaning that there
4779          are no stopped threads at this time; or, a regular stop
4780          reply.  In the latter case, there may be more than one thread
4781          stopped --- we pull them all out using the vStopped
4782          mechanism.  */
4783       if (strcmp (rs->buf, "OK") != 0)
4784         {
4785           struct notif_client *notif = &notif_client_stop;
4786
4787           /* remote_notif_get_pending_replies acks this one, and gets
4788              the rest out.  */
4789           rs->notif_state->pending_event[notif_client_stop.id]
4790             = remote_notif_parse (this, notif, rs->buf);
4791           remote_notif_get_pending_events (notif);
4792         }
4793
4794       if (thread_count () == 0)
4795         {
4796           if (!extended_p)
4797             error (_("The target is not running (try extended-remote?)"));
4798
4799           /* We're connected, but not running.  Drop out before we
4800              call start_remote.  */
4801           rs->starting_up = 0;
4802           return;
4803         }
4804
4805       /* In non-stop mode, any cached wait status will be stored in
4806          the stop reply queue.  */
4807       gdb_assert (wait_status == NULL);
4808
4809       /* Report all signals during attach/startup.  */
4810       pass_signals (0, NULL);
4811
4812       /* If there are already stopped threads, mark them stopped and
4813          report their stops before giving the prompt to the user.  */
4814       process_initial_stop_replies (from_tty);
4815
4816       if (target_can_async_p ())
4817         target_async (1);
4818     }
4819
4820   /* If we connected to a live target, do some additional setup.  */
4821   if (target_has_execution)
4822     {
4823       if (symfile_objfile)      /* No use without a symbol-file.  */
4824         remote_check_symbols ();
4825     }
4826
4827   /* Possibly the target has been engaged in a trace run started
4828      previously; find out where things are at.  */
4829   if (get_trace_status (current_trace_status ()) != -1)
4830     {
4831       struct uploaded_tp *uploaded_tps = NULL;
4832
4833       if (current_trace_status ()->running)
4834         printf_filtered (_("Trace is already running on the target.\n"));
4835
4836       upload_tracepoints (&uploaded_tps);
4837
4838       merge_uploaded_tracepoints (&uploaded_tps);
4839     }
4840
4841   /* Possibly the target has been engaged in a btrace record started
4842      previously; find out where things are at.  */
4843   remote_btrace_maybe_reopen ();
4844
4845   /* The thread and inferior lists are now synchronized with the
4846      target, our symbols have been relocated, and we're merged the
4847      target's tracepoints with ours.  We're done with basic start
4848      up.  */
4849   rs->starting_up = 0;
4850
4851   /* Maybe breakpoints are global and need to be inserted now.  */
4852   if (breakpoints_should_be_inserted_now ())
4853     insert_breakpoints ();
4854 }
4855
4856 /* Open a connection to a remote debugger.
4857    NAME is the filename used for communication.  */
4858
4859 void
4860 remote_target::open (const char *name, int from_tty)
4861 {
4862   open_1 (name, from_tty, 0);
4863 }
4864
4865 /* Open a connection to a remote debugger using the extended
4866    remote gdb protocol.  NAME is the filename used for communication.  */
4867
4868 void
4869 extended_remote_target::open (const char *name, int from_tty)
4870 {
4871   open_1 (name, from_tty, 1 /*extended_p */);
4872 }
4873
4874 /* Reset all packets back to "unknown support".  Called when opening a
4875    new connection to a remote target.  */
4876
4877 static void
4878 reset_all_packet_configs_support (void)
4879 {
4880   int i;
4881
4882   for (i = 0; i < PACKET_MAX; i++)
4883     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4884 }
4885
4886 /* Initialize all packet configs.  */
4887
4888 static void
4889 init_all_packet_configs (void)
4890 {
4891   int i;
4892
4893   for (i = 0; i < PACKET_MAX; i++)
4894     {
4895       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4896       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4897     }
4898 }
4899
4900 /* Symbol look-up.  */
4901
4902 void
4903 remote_target::remote_check_symbols ()
4904 {
4905   char *msg, *reply, *tmp;
4906   int end;
4907   long reply_size;
4908   struct cleanup *old_chain;
4909
4910   /* The remote side has no concept of inferiors that aren't running
4911      yet, it only knows about running processes.  If we're connected
4912      but our current inferior is not running, we should not invite the
4913      remote target to request symbol lookups related to its
4914      (unrelated) current process.  */
4915   if (!target_has_execution)
4916     return;
4917
4918   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4919     return;
4920
4921   /* Make sure the remote is pointing at the right process.  Note
4922      there's no way to select "no process".  */
4923   set_general_process ();
4924
4925   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4926      because we need both at the same time.  */
4927   msg = (char *) xmalloc (get_remote_packet_size ());
4928   old_chain = make_cleanup (xfree, msg);
4929   reply = (char *) xmalloc (get_remote_packet_size ());
4930   make_cleanup (free_current_contents, &reply);
4931   reply_size = get_remote_packet_size ();
4932
4933   /* Invite target to request symbol lookups.  */
4934
4935   putpkt ("qSymbol::");
4936   getpkt (&reply, &reply_size, 0);
4937   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4938
4939   while (startswith (reply, "qSymbol:"))
4940     {
4941       struct bound_minimal_symbol sym;
4942
4943       tmp = &reply[8];
4944       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4945       msg[end] = '\0';
4946       sym = lookup_minimal_symbol (msg, NULL, NULL);
4947       if (sym.minsym == NULL)
4948         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4949       else
4950         {
4951           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4952           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4953
4954           /* If this is a function address, return the start of code
4955              instead of any data function descriptor.  */
4956           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4957                                                          sym_addr,
4958                                                          current_top_target ());
4959
4960           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4961                      phex_nz (sym_addr, addr_size), &reply[8]);
4962         }
4963   
4964       putpkt (msg);
4965       getpkt (&reply, &reply_size, 0);
4966     }
4967
4968   do_cleanups (old_chain);
4969 }
4970
4971 static struct serial *
4972 remote_serial_open (const char *name)
4973 {
4974   static int udp_warning = 0;
4975
4976   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4977      of in ser-tcp.c, because it is the remote protocol assuming that the
4978      serial connection is reliable and not the serial connection promising
4979      to be.  */
4980   if (!udp_warning && startswith (name, "udp:"))
4981     {
4982       warning (_("The remote protocol may be unreliable over UDP.\n"
4983                  "Some events may be lost, rendering further debugging "
4984                  "impossible."));
4985       udp_warning = 1;
4986     }
4987
4988   return serial_open (name);
4989 }
4990
4991 /* Inform the target of our permission settings.  The permission flags
4992    work without this, but if the target knows the settings, it can do
4993    a couple things.  First, it can add its own check, to catch cases
4994    that somehow manage to get by the permissions checks in target
4995    methods.  Second, if the target is wired to disallow particular
4996    settings (for instance, a system in the field that is not set up to
4997    be able to stop at a breakpoint), it can object to any unavailable
4998    permissions.  */
4999
5000 void
5001 remote_target::set_permissions ()
5002 {
5003   struct remote_state *rs = get_remote_state ();
5004
5005   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
5006              "WriteReg:%x;WriteMem:%x;"
5007              "InsertBreak:%x;InsertTrace:%x;"
5008              "InsertFastTrace:%x;Stop:%x",
5009              may_write_registers, may_write_memory,
5010              may_insert_breakpoints, may_insert_tracepoints,
5011              may_insert_fast_tracepoints, may_stop);
5012   putpkt (rs->buf);
5013   getpkt (&rs->buf, &rs->buf_size, 0);
5014
5015   /* If the target didn't like the packet, warn the user.  Do not try
5016      to undo the user's settings, that would just be maddening.  */
5017   if (strcmp (rs->buf, "OK") != 0)
5018     warning (_("Remote refused setting permissions with: %s"), rs->buf);
5019 }
5020
5021 /* This type describes each known response to the qSupported
5022    packet.  */
5023 struct protocol_feature
5024 {
5025   /* The name of this protocol feature.  */
5026   const char *name;
5027
5028   /* The default for this protocol feature.  */
5029   enum packet_support default_support;
5030
5031   /* The function to call when this feature is reported, or after
5032      qSupported processing if the feature is not supported.
5033      The first argument points to this structure.  The second
5034      argument indicates whether the packet requested support be
5035      enabled, disabled, or probed (or the default, if this function
5036      is being called at the end of processing and this feature was
5037      not reported).  The third argument may be NULL; if not NULL, it
5038      is a NUL-terminated string taken from the packet following
5039      this feature's name and an equals sign.  */
5040   void (*func) (remote_target *remote, const struct protocol_feature *,
5041                 enum packet_support, const char *);
5042
5043   /* The corresponding packet for this feature.  Only used if
5044      FUNC is remote_supported_packet.  */
5045   int packet;
5046 };
5047
5048 static void
5049 remote_supported_packet (remote_target *remote,
5050                          const struct protocol_feature *feature,
5051                          enum packet_support support,
5052                          const char *argument)
5053 {
5054   if (argument)
5055     {
5056       warning (_("Remote qSupported response supplied an unexpected value for"
5057                  " \"%s\"."), feature->name);
5058       return;
5059     }
5060
5061   remote_protocol_packets[feature->packet].support = support;
5062 }
5063
5064 void
5065 remote_target::remote_packet_size (const protocol_feature *feature,
5066                                    enum packet_support support, const char *value)
5067 {
5068   struct remote_state *rs = get_remote_state ();
5069
5070   int packet_size;
5071   char *value_end;
5072
5073   if (support != PACKET_ENABLE)
5074     return;
5075
5076   if (value == NULL || *value == '\0')
5077     {
5078       warning (_("Remote target reported \"%s\" without a size."),
5079                feature->name);
5080       return;
5081     }
5082
5083   errno = 0;
5084   packet_size = strtol (value, &value_end, 16);
5085   if (errno != 0 || *value_end != '\0' || packet_size < 0)
5086     {
5087       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5088                feature->name, value);
5089       return;
5090     }
5091
5092   /* Record the new maximum packet size.  */
5093   rs->explicit_packet_size = packet_size;
5094 }
5095
5096 void
5097 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5098                     enum packet_support support, const char *value)
5099 {
5100   remote->remote_packet_size (feature, support, value);
5101 }
5102
5103 static const struct protocol_feature remote_protocol_features[] = {
5104   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5105   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5106     PACKET_qXfer_auxv },
5107   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5108     PACKET_qXfer_exec_file },
5109   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5110     PACKET_qXfer_features },
5111   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5112     PACKET_qXfer_libraries },
5113   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5114     PACKET_qXfer_libraries_svr4 },
5115   { "augmented-libraries-svr4-read", PACKET_DISABLE,
5116     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5117   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5118     PACKET_qXfer_memory_map },
5119   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5120     PACKET_qXfer_spu_read },
5121   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5122     PACKET_qXfer_spu_write },
5123   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5124     PACKET_qXfer_osdata },
5125   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5126     PACKET_qXfer_threads },
5127   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5128     PACKET_qXfer_traceframe_info },
5129   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5130     PACKET_QPassSignals },
5131   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5132     PACKET_QCatchSyscalls },
5133   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5134     PACKET_QProgramSignals },
5135   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5136     PACKET_QSetWorkingDir },
5137   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5138     PACKET_QStartupWithShell },
5139   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5140     PACKET_QEnvironmentHexEncoded },
5141   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5142     PACKET_QEnvironmentReset },
5143   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5144     PACKET_QEnvironmentUnset },
5145   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5146     PACKET_QStartNoAckMode },
5147   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5148     PACKET_multiprocess_feature },
5149   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5150   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5151     PACKET_qXfer_siginfo_read },
5152   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5153     PACKET_qXfer_siginfo_write },
5154   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5155     PACKET_ConditionalTracepoints },
5156   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5157     PACKET_ConditionalBreakpoints },
5158   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5159     PACKET_BreakpointCommands },
5160   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5161     PACKET_FastTracepoints },
5162   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5163     PACKET_StaticTracepoints },
5164   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5165    PACKET_InstallInTrace},
5166   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5167     PACKET_DisconnectedTracing_feature },
5168   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5169     PACKET_bc },
5170   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5171     PACKET_bs },
5172   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5173     PACKET_TracepointSource },
5174   { "QAllow", PACKET_DISABLE, remote_supported_packet,
5175     PACKET_QAllow },
5176   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5177     PACKET_EnableDisableTracepoints_feature },
5178   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5179     PACKET_qXfer_fdpic },
5180   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5181     PACKET_qXfer_uib },
5182   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5183     PACKET_QDisableRandomization },
5184   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5185   { "QTBuffer:size", PACKET_DISABLE,
5186     remote_supported_packet, PACKET_QTBuffer_size},
5187   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5188   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5189   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5190   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5191   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5192     PACKET_qXfer_btrace },
5193   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5194     PACKET_qXfer_btrace_conf },
5195   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5196     PACKET_Qbtrace_conf_bts_size },
5197   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5198   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5199   { "fork-events", PACKET_DISABLE, remote_supported_packet,
5200     PACKET_fork_event_feature },
5201   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5202     PACKET_vfork_event_feature },
5203   { "exec-events", PACKET_DISABLE, remote_supported_packet,
5204     PACKET_exec_event_feature },
5205   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5206     PACKET_Qbtrace_conf_pt_size },
5207   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5208   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5209   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5210 };
5211
5212 static char *remote_support_xml;
5213
5214 /* Register string appended to "xmlRegisters=" in qSupported query.  */
5215
5216 void
5217 register_remote_support_xml (const char *xml)
5218 {
5219 #if defined(HAVE_LIBEXPAT)
5220   if (remote_support_xml == NULL)
5221     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5222   else
5223     {
5224       char *copy = xstrdup (remote_support_xml + 13);
5225       char *p = strtok (copy, ",");
5226
5227       do
5228         {
5229           if (strcmp (p, xml) == 0)
5230             {
5231               /* already there */
5232               xfree (copy);
5233               return;
5234             }
5235         }
5236       while ((p = strtok (NULL, ",")) != NULL);
5237       xfree (copy);
5238
5239       remote_support_xml = reconcat (remote_support_xml,
5240                                      remote_support_xml, ",", xml,
5241                                      (char *) NULL);
5242     }
5243 #endif
5244 }
5245
5246 static void
5247 remote_query_supported_append (std::string *msg, const char *append)
5248 {
5249   if (!msg->empty ())
5250     msg->append (";");
5251   msg->append (append);
5252 }
5253
5254 void
5255 remote_target::remote_query_supported ()
5256 {
5257   struct remote_state *rs = get_remote_state ();
5258   char *next;
5259   int i;
5260   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5261
5262   /* The packet support flags are handled differently for this packet
5263      than for most others.  We treat an error, a disabled packet, and
5264      an empty response identically: any features which must be reported
5265      to be used will be automatically disabled.  An empty buffer
5266      accomplishes this, since that is also the representation for a list
5267      containing no features.  */
5268
5269   rs->buf[0] = 0;
5270   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5271     {
5272       std::string q;
5273
5274       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5275         remote_query_supported_append (&q, "multiprocess+");
5276
5277       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5278         remote_query_supported_append (&q, "swbreak+");
5279       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5280         remote_query_supported_append (&q, "hwbreak+");
5281
5282       remote_query_supported_append (&q, "qRelocInsn+");
5283
5284       if (packet_set_cmd_state (PACKET_fork_event_feature)
5285           != AUTO_BOOLEAN_FALSE)
5286         remote_query_supported_append (&q, "fork-events+");
5287       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5288           != AUTO_BOOLEAN_FALSE)
5289         remote_query_supported_append (&q, "vfork-events+");
5290       if (packet_set_cmd_state (PACKET_exec_event_feature)
5291           != AUTO_BOOLEAN_FALSE)
5292         remote_query_supported_append (&q, "exec-events+");
5293
5294       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5295         remote_query_supported_append (&q, "vContSupported+");
5296
5297       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5298         remote_query_supported_append (&q, "QThreadEvents+");
5299
5300       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5301         remote_query_supported_append (&q, "no-resumed+");
5302
5303       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5304          the qSupported:xmlRegisters=i386 handling.  */
5305       if (remote_support_xml != NULL
5306           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5307         remote_query_supported_append (&q, remote_support_xml);
5308
5309       q = "qSupported:" + q;
5310       putpkt (q.c_str ());
5311
5312       getpkt (&rs->buf, &rs->buf_size, 0);
5313
5314       /* If an error occured, warn, but do not return - just reset the
5315          buffer to empty and go on to disable features.  */
5316       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5317           == PACKET_ERROR)
5318         {
5319           warning (_("Remote failure reply: %s"), rs->buf);
5320           rs->buf[0] = 0;
5321         }
5322     }
5323
5324   memset (seen, 0, sizeof (seen));
5325
5326   next = rs->buf;
5327   while (*next)
5328     {
5329       enum packet_support is_supported;
5330       char *p, *end, *name_end, *value;
5331
5332       /* First separate out this item from the rest of the packet.  If
5333          there's another item after this, we overwrite the separator
5334          (terminated strings are much easier to work with).  */
5335       p = next;
5336       end = strchr (p, ';');
5337       if (end == NULL)
5338         {
5339           end = p + strlen (p);
5340           next = end;
5341         }
5342       else
5343         {
5344           *end = '\0';
5345           next = end + 1;
5346
5347           if (end == p)
5348             {
5349               warning (_("empty item in \"qSupported\" response"));
5350               continue;
5351             }
5352         }
5353
5354       name_end = strchr (p, '=');
5355       if (name_end)
5356         {
5357           /* This is a name=value entry.  */
5358           is_supported = PACKET_ENABLE;
5359           value = name_end + 1;
5360           *name_end = '\0';
5361         }
5362       else
5363         {
5364           value = NULL;
5365           switch (end[-1])
5366             {
5367             case '+':
5368               is_supported = PACKET_ENABLE;
5369               break;
5370
5371             case '-':
5372               is_supported = PACKET_DISABLE;
5373               break;
5374
5375             case '?':
5376               is_supported = PACKET_SUPPORT_UNKNOWN;
5377               break;
5378
5379             default:
5380               warning (_("unrecognized item \"%s\" "
5381                          "in \"qSupported\" response"), p);
5382               continue;
5383             }
5384           end[-1] = '\0';
5385         }
5386
5387       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5388         if (strcmp (remote_protocol_features[i].name, p) == 0)
5389           {
5390             const struct protocol_feature *feature;
5391
5392             seen[i] = 1;
5393             feature = &remote_protocol_features[i];
5394             feature->func (this, feature, is_supported, value);
5395             break;
5396           }
5397     }
5398
5399   /* If we increased the packet size, make sure to increase the global
5400      buffer size also.  We delay this until after parsing the entire
5401      qSupported packet, because this is the same buffer we were
5402      parsing.  */
5403   if (rs->buf_size < rs->explicit_packet_size)
5404     {
5405       rs->buf_size = rs->explicit_packet_size;
5406       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5407     }
5408
5409   /* Handle the defaults for unmentioned features.  */
5410   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5411     if (!seen[i])
5412       {
5413         const struct protocol_feature *feature;
5414
5415         feature = &remote_protocol_features[i];
5416         feature->func (this, feature, feature->default_support, NULL);
5417       }
5418 }
5419
5420 /* Serial QUIT handler for the remote serial descriptor.
5421
5422    Defers handling a Ctrl-C until we're done with the current
5423    command/response packet sequence, unless:
5424
5425    - We're setting up the connection.  Don't send a remote interrupt
5426      request, as we're not fully synced yet.  Quit immediately
5427      instead.
5428
5429    - The target has been resumed in the foreground
5430      (target_terminal::is_ours is false) with a synchronous resume
5431      packet, and we're blocked waiting for the stop reply, thus a
5432      Ctrl-C should be immediately sent to the target.
5433
5434    - We get a second Ctrl-C while still within the same serial read or
5435      write.  In that case the serial is seemingly wedged --- offer to
5436      quit/disconnect.
5437
5438    - We see a second Ctrl-C without target response, after having
5439      previously interrupted the target.  In that case the target/stub
5440      is probably wedged --- offer to quit/disconnect.
5441 */
5442
5443 void
5444 remote_target::remote_serial_quit_handler ()
5445 {
5446   struct remote_state *rs = get_remote_state ();
5447
5448   if (check_quit_flag ())
5449     {
5450       /* If we're starting up, we're not fully synced yet.  Quit
5451          immediately.  */
5452       if (rs->starting_up)
5453         quit ();
5454       else if (rs->got_ctrlc_during_io)
5455         {
5456           if (query (_("The target is not responding to GDB commands.\n"
5457                        "Stop debugging it? ")))
5458             remote_unpush_and_throw ();
5459         }
5460       /* If ^C has already been sent once, offer to disconnect.  */
5461       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5462         interrupt_query ();
5463       /* All-stop protocol, and blocked waiting for stop reply.  Send
5464          an interrupt request.  */
5465       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5466         target_interrupt ();
5467       else
5468         rs->got_ctrlc_during_io = 1;
5469     }
5470 }
5471
5472 /* The remote_target that is current while the quit handler is
5473    overridden with remote_serial_quit_handler.  */
5474 static remote_target *curr_quit_handler_target;
5475
5476 static void
5477 remote_serial_quit_handler ()
5478 {
5479   curr_quit_handler_target->remote_serial_quit_handler ();
5480 }
5481
5482 /* Remove any of the remote.c targets from target stack.  Upper targets depend
5483    on it so remove them first.  */
5484
5485 static void
5486 remote_unpush_target (void)
5487 {
5488   pop_all_targets_at_and_above (process_stratum);
5489 }
5490
5491 static void
5492 remote_unpush_and_throw (void)
5493 {
5494   remote_unpush_target ();
5495   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5496 }
5497
5498 void
5499 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5500 {
5501   remote_target *curr_remote = get_current_remote_target ();
5502
5503   if (name == 0)
5504     error (_("To open a remote debug connection, you need to specify what\n"
5505            "serial device is attached to the remote system\n"
5506            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5507
5508   /* If we're connected to a running target, target_preopen will kill it.
5509      Ask this question first, before target_preopen has a chance to kill
5510      anything.  */
5511   if (curr_remote != NULL && !have_inferiors ())
5512     {
5513       if (from_tty
5514           && !query (_("Already connected to a remote target.  Disconnect? ")))
5515         error (_("Still connected."));
5516     }
5517
5518   /* Here the possibly existing remote target gets unpushed.  */
5519   target_preopen (from_tty);
5520
5521   remote_fileio_reset ();
5522   reopen_exec_file ();
5523   reread_symbols ();
5524
5525   remote_target *remote
5526     = (extended_p ? new extended_remote_target () : new remote_target ());
5527   target_ops_up target_holder (remote);
5528
5529   remote_state *rs = remote->get_remote_state ();
5530
5531   /* See FIXME above.  */
5532   if (!target_async_permitted)
5533     rs->wait_forever_enabled_p = 1;
5534
5535   rs->remote_desc = remote_serial_open (name);
5536   if (!rs->remote_desc)
5537     perror_with_name (name);
5538
5539   if (baud_rate != -1)
5540     {
5541       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5542         {
5543           /* The requested speed could not be set.  Error out to
5544              top level after closing remote_desc.  Take care to
5545              set remote_desc to NULL to avoid closing remote_desc
5546              more than once.  */
5547           serial_close (rs->remote_desc);
5548           rs->remote_desc = NULL;
5549           perror_with_name (name);
5550         }
5551     }
5552
5553   serial_setparity (rs->remote_desc, serial_parity);
5554   serial_raw (rs->remote_desc);
5555
5556   /* If there is something sitting in the buffer we might take it as a
5557      response to a command, which would be bad.  */
5558   serial_flush_input (rs->remote_desc);
5559
5560   if (from_tty)
5561     {
5562       puts_filtered ("Remote debugging using ");
5563       puts_filtered (name);
5564       puts_filtered ("\n");
5565     }
5566
5567   /* Switch to using the remote target now.  */
5568   push_target (remote);
5569   /* The target stack owns the target now.  */
5570   target_holder.release ();
5571
5572   /* Register extra event sources in the event loop.  */
5573   rs->remote_async_inferior_event_token
5574     = create_async_event_handler (remote_async_inferior_event_handler,
5575                                   remote);
5576   rs->notif_state = remote_notif_state_allocate (remote);
5577
5578   /* Reset the target state; these things will be queried either by
5579      remote_query_supported or as they are needed.  */
5580   reset_all_packet_configs_support ();
5581   rs->cached_wait_status = 0;
5582   rs->explicit_packet_size = 0;
5583   rs->noack_mode = 0;
5584   rs->extended = extended_p;
5585   rs->waiting_for_stop_reply = 0;
5586   rs->ctrlc_pending_p = 0;
5587   rs->got_ctrlc_during_io = 0;
5588
5589   rs->general_thread = not_sent_ptid;
5590   rs->continue_thread = not_sent_ptid;
5591   rs->remote_traceframe_number = -1;
5592
5593   rs->last_resume_exec_dir = EXEC_FORWARD;
5594
5595   /* Probe for ability to use "ThreadInfo" query, as required.  */
5596   rs->use_threadinfo_query = 1;
5597   rs->use_threadextra_query = 1;
5598
5599   rs->readahead_cache.invalidate ();
5600
5601   if (target_async_permitted)
5602     {
5603       /* FIXME: cagney/1999-09-23: During the initial connection it is
5604          assumed that the target is already ready and able to respond to
5605          requests.  Unfortunately remote_start_remote() eventually calls
5606          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5607          around this.  Eventually a mechanism that allows
5608          wait_for_inferior() to expect/get timeouts will be
5609          implemented.  */
5610       rs->wait_forever_enabled_p = 0;
5611     }
5612
5613   /* First delete any symbols previously loaded from shared libraries.  */
5614   no_shared_libraries (NULL, 0);
5615
5616   /* Start afresh.  */
5617   init_thread_list ();
5618
5619   /* Start the remote connection.  If error() or QUIT, discard this
5620      target (we'd otherwise be in an inconsistent state) and then
5621      propogate the error on up the exception chain.  This ensures that
5622      the caller doesn't stumble along blindly assuming that the
5623      function succeeded.  The CLI doesn't have this problem but other
5624      UI's, such as MI do.
5625
5626      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5627      this function should return an error indication letting the
5628      caller restore the previous state.  Unfortunately the command
5629      ``target remote'' is directly wired to this function making that
5630      impossible.  On a positive note, the CLI side of this problem has
5631      been fixed - the function set_cmd_context() makes it possible for
5632      all the ``target ....'' commands to share a common callback
5633      function.  See cli-dump.c.  */
5634   {
5635
5636     TRY
5637       {
5638         remote->start_remote (from_tty, extended_p);
5639       }
5640     CATCH (ex, RETURN_MASK_ALL)
5641       {
5642         /* Pop the partially set up target - unless something else did
5643            already before throwing the exception.  */
5644         if (ex.error != TARGET_CLOSE_ERROR)
5645           remote_unpush_target ();
5646         throw_exception (ex);
5647       }
5648     END_CATCH
5649   }
5650
5651   remote_btrace_reset (rs);
5652
5653   if (target_async_permitted)
5654     rs->wait_forever_enabled_p = 1;
5655 }
5656
5657 /* Detach the specified process.  */
5658
5659 void
5660 remote_target::remote_detach_pid (int pid)
5661 {
5662   struct remote_state *rs = get_remote_state ();
5663
5664   /* This should not be necessary, but the handling for D;PID in
5665      GDBserver versions prior to 8.2 incorrectly assumes that the
5666      selected process points to the same process we're detaching,
5667      leading to misbehavior (and possibly GDBserver crashing) when it
5668      does not.  Since it's easy and cheap, work around it by forcing
5669      GDBserver to select GDB's current process.  */
5670   set_general_process ();
5671
5672   if (remote_multi_process_p (rs))
5673     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5674   else
5675     strcpy (rs->buf, "D");
5676
5677   putpkt (rs->buf);
5678   getpkt (&rs->buf, &rs->buf_size, 0);
5679
5680   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5681     ;
5682   else if (rs->buf[0] == '\0')
5683     error (_("Remote doesn't know how to detach"));
5684   else
5685     error (_("Can't detach process."));
5686 }
5687
5688 /* This detaches a program to which we previously attached, using
5689    inferior_ptid to identify the process.  After this is done, GDB
5690    can be used to debug some other program.  We better not have left
5691    any breakpoints in the target program or it'll die when it hits
5692    one.  */
5693
5694 void
5695 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5696 {
5697   int pid = inferior_ptid.pid ();
5698   struct remote_state *rs = get_remote_state ();
5699   int is_fork_parent;
5700
5701   if (!target_has_execution)
5702     error (_("No process to detach from."));
5703
5704   target_announce_detach (from_tty);
5705
5706   /* Tell the remote target to detach.  */
5707   remote_detach_pid (pid);
5708
5709   /* Exit only if this is the only active inferior.  */
5710   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5711     puts_filtered (_("Ending remote debugging.\n"));
5712
5713   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5714
5715   /* Check to see if we are detaching a fork parent.  Note that if we
5716      are detaching a fork child, tp == NULL.  */
5717   is_fork_parent = (tp != NULL
5718                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5719
5720   /* If doing detach-on-fork, we don't mourn, because that will delete
5721      breakpoints that should be available for the followed inferior.  */
5722   if (!is_fork_parent)
5723     {
5724       /* Save the pid as a string before mourning, since that will
5725          unpush the remote target, and we need the string after.  */
5726       std::string infpid = target_pid_to_str (ptid_t (pid));
5727
5728       target_mourn_inferior (inferior_ptid);
5729       if (print_inferior_events)
5730         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5731                            inf->num, infpid.c_str ());
5732     }
5733   else
5734     {
5735       inferior_ptid = null_ptid;
5736       detach_inferior (current_inferior ());
5737     }
5738 }
5739
5740 void
5741 remote_target::detach (inferior *inf, int from_tty)
5742 {
5743   remote_detach_1 (inf, from_tty);
5744 }
5745
5746 void
5747 extended_remote_target::detach (inferior *inf, int from_tty)
5748 {
5749   remote_detach_1 (inf, from_tty);
5750 }
5751
5752 /* Target follow-fork function for remote targets.  On entry, and
5753    at return, the current inferior is the fork parent.
5754
5755    Note that although this is currently only used for extended-remote,
5756    it is named remote_follow_fork in anticipation of using it for the
5757    remote target as well.  */
5758
5759 int
5760 remote_target::follow_fork (int follow_child, int detach_fork)
5761 {
5762   struct remote_state *rs = get_remote_state ();
5763   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5764
5765   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5766       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5767     {
5768       /* When following the parent and detaching the child, we detach
5769          the child here.  For the case of following the child and
5770          detaching the parent, the detach is done in the target-
5771          independent follow fork code in infrun.c.  We can't use
5772          target_detach when detaching an unfollowed child because
5773          the client side doesn't know anything about the child.  */
5774       if (detach_fork && !follow_child)
5775         {
5776           /* Detach the fork child.  */
5777           ptid_t child_ptid;
5778           pid_t child_pid;
5779
5780           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5781           child_pid = child_ptid.pid ();
5782
5783           remote_detach_pid (child_pid);
5784         }
5785     }
5786   return 0;
5787 }
5788
5789 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5790    in the program space of the new inferior.  On entry and at return the
5791    current inferior is the exec'ing inferior.  INF is the new exec'd
5792    inferior, which may be the same as the exec'ing inferior unless
5793    follow-exec-mode is "new".  */
5794
5795 void
5796 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5797 {
5798   /* We know that this is a target file name, so if it has the "target:"
5799      prefix we strip it off before saving it in the program space.  */
5800   if (is_target_filename (execd_pathname))
5801     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5802
5803   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5804 }
5805
5806 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5807
5808 void
5809 remote_target::disconnect (const char *args, int from_tty)
5810 {
5811   if (args)
5812     error (_("Argument given to \"disconnect\" when remotely debugging."));
5813
5814   /* Make sure we unpush even the extended remote targets.  Calling
5815      target_mourn_inferior won't unpush, and remote_mourn won't
5816      unpush if there is more than one inferior left.  */
5817   unpush_target (this);
5818   generic_mourn_inferior ();
5819
5820   if (from_tty)
5821     puts_filtered ("Ending remote debugging.\n");
5822 }
5823
5824 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5825    be chatty about it.  */
5826
5827 void
5828 extended_remote_target::attach (const char *args, int from_tty)
5829 {
5830   struct remote_state *rs = get_remote_state ();
5831   int pid;
5832   char *wait_status = NULL;
5833
5834   pid = parse_pid_to_attach (args);
5835
5836   /* Remote PID can be freely equal to getpid, do not check it here the same
5837      way as in other targets.  */
5838
5839   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5840     error (_("This target does not support attaching to a process"));
5841
5842   if (from_tty)
5843     {
5844       char *exec_file = get_exec_file (0);
5845
5846       if (exec_file)
5847         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5848                            target_pid_to_str (ptid_t (pid)));
5849       else
5850         printf_unfiltered (_("Attaching to %s\n"),
5851                            target_pid_to_str (ptid_t (pid)));
5852
5853       gdb_flush (gdb_stdout);
5854     }
5855
5856   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5857   putpkt (rs->buf);
5858   getpkt (&rs->buf, &rs->buf_size, 0);
5859
5860   switch (packet_ok (rs->buf,
5861                      &remote_protocol_packets[PACKET_vAttach]))
5862     {
5863     case PACKET_OK:
5864       if (!target_is_non_stop_p ())
5865         {
5866           /* Save the reply for later.  */
5867           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5868           strcpy (wait_status, rs->buf);
5869         }
5870       else if (strcmp (rs->buf, "OK") != 0)
5871         error (_("Attaching to %s failed with: %s"),
5872                target_pid_to_str (ptid_t (pid)),
5873                rs->buf);
5874       break;
5875     case PACKET_UNKNOWN:
5876       error (_("This target does not support attaching to a process"));
5877     default:
5878       error (_("Attaching to %s failed"),
5879              target_pid_to_str (ptid_t (pid)));
5880     }
5881
5882   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5883
5884   inferior_ptid = ptid_t (pid);
5885
5886   if (target_is_non_stop_p ())
5887     {
5888       struct thread_info *thread;
5889
5890       /* Get list of threads.  */
5891       update_thread_list ();
5892
5893       thread = first_thread_of_inferior (current_inferior ());
5894       if (thread)
5895         inferior_ptid = thread->ptid;
5896       else
5897         inferior_ptid = ptid_t (pid);
5898
5899       /* Invalidate our notion of the remote current thread.  */
5900       record_currthread (rs, minus_one_ptid);
5901     }
5902   else
5903     {
5904       /* Now, if we have thread information, update inferior_ptid.  */
5905       inferior_ptid = remote_current_thread (inferior_ptid);
5906
5907       /* Add the main thread to the thread list.  */
5908       thread_info *thr = add_thread_silent (inferior_ptid);
5909       /* Don't consider the thread stopped until we've processed the
5910          saved stop reply.  */
5911       set_executing (thr->ptid, true);
5912     }
5913
5914   /* Next, if the target can specify a description, read it.  We do
5915      this before anything involving memory or registers.  */
5916   target_find_description ();
5917
5918   if (!target_is_non_stop_p ())
5919     {
5920       /* Use the previously fetched status.  */
5921       gdb_assert (wait_status != NULL);
5922
5923       if (target_can_async_p ())
5924         {
5925           struct notif_event *reply
5926             =  remote_notif_parse (this, &notif_client_stop, wait_status);
5927
5928           push_stop_reply ((struct stop_reply *) reply);
5929
5930           target_async (1);
5931         }
5932       else
5933         {
5934           gdb_assert (wait_status != NULL);
5935           strcpy (rs->buf, wait_status);
5936           rs->cached_wait_status = 1;
5937         }
5938     }
5939   else
5940     gdb_assert (wait_status == NULL);
5941 }
5942
5943 /* Implementation of the to_post_attach method.  */
5944
5945 void
5946 extended_remote_target::post_attach (int pid)
5947 {
5948   /* Get text, data & bss offsets.  */
5949   get_offsets ();
5950
5951   /* In certain cases GDB might not have had the chance to start
5952      symbol lookup up until now.  This could happen if the debugged
5953      binary is not using shared libraries, the vsyscall page is not
5954      present (on Linux) and the binary itself hadn't changed since the
5955      debugging process was started.  */
5956   if (symfile_objfile != NULL)
5957     remote_check_symbols();
5958 }
5959
5960 \f
5961 /* Check for the availability of vCont.  This function should also check
5962    the response.  */
5963
5964 void
5965 remote_target::remote_vcont_probe ()
5966 {
5967   remote_state *rs = get_remote_state ();
5968   char *buf;
5969
5970   strcpy (rs->buf, "vCont?");
5971   putpkt (rs->buf);
5972   getpkt (&rs->buf, &rs->buf_size, 0);
5973   buf = rs->buf;
5974
5975   /* Make sure that the features we assume are supported.  */
5976   if (startswith (buf, "vCont"))
5977     {
5978       char *p = &buf[5];
5979       int support_c, support_C;
5980
5981       rs->supports_vCont.s = 0;
5982       rs->supports_vCont.S = 0;
5983       support_c = 0;
5984       support_C = 0;
5985       rs->supports_vCont.t = 0;
5986       rs->supports_vCont.r = 0;
5987       while (p && *p == ';')
5988         {
5989           p++;
5990           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5991             rs->supports_vCont.s = 1;
5992           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5993             rs->supports_vCont.S = 1;
5994           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5995             support_c = 1;
5996           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5997             support_C = 1;
5998           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5999             rs->supports_vCont.t = 1;
6000           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
6001             rs->supports_vCont.r = 1;
6002
6003           p = strchr (p, ';');
6004         }
6005
6006       /* If c, and C are not all supported, we can't use vCont.  Clearing
6007          BUF will make packet_ok disable the packet.  */
6008       if (!support_c || !support_C)
6009         buf[0] = 0;
6010     }
6011
6012   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
6013 }
6014
6015 /* Helper function for building "vCont" resumptions.  Write a
6016    resumption to P.  ENDP points to one-passed-the-end of the buffer
6017    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
6018    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
6019    resumed thread should be single-stepped and/or signalled.  If PTID
6020    equals minus_one_ptid, then all threads are resumed; if PTID
6021    represents a process, then all threads of the process are resumed;
6022    the thread to be stepped and/or signalled is given in the global
6023    INFERIOR_PTID.  */
6024
6025 char *
6026 remote_target::append_resumption (char *p, char *endp,
6027                                   ptid_t ptid, int step, gdb_signal siggnal)
6028 {
6029   struct remote_state *rs = get_remote_state ();
6030
6031   if (step && siggnal != GDB_SIGNAL_0)
6032     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6033   else if (step
6034            /* GDB is willing to range step.  */
6035            && use_range_stepping
6036            /* Target supports range stepping.  */
6037            && rs->supports_vCont.r
6038            /* We don't currently support range stepping multiple
6039               threads with a wildcard (though the protocol allows it,
6040               so stubs shouldn't make an active effort to forbid
6041               it).  */
6042            && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6043     {
6044       struct thread_info *tp;
6045
6046       if (ptid == minus_one_ptid)
6047         {
6048           /* If we don't know about the target thread's tid, then
6049              we're resuming magic_null_ptid (see caller).  */
6050           tp = find_thread_ptid (magic_null_ptid);
6051         }
6052       else
6053         tp = find_thread_ptid (ptid);
6054       gdb_assert (tp != NULL);
6055
6056       if (tp->control.may_range_step)
6057         {
6058           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6059
6060           p += xsnprintf (p, endp - p, ";r%s,%s",
6061                           phex_nz (tp->control.step_range_start,
6062                                    addr_size),
6063                           phex_nz (tp->control.step_range_end,
6064                                    addr_size));
6065         }
6066       else
6067         p += xsnprintf (p, endp - p, ";s");
6068     }
6069   else if (step)
6070     p += xsnprintf (p, endp - p, ";s");
6071   else if (siggnal != GDB_SIGNAL_0)
6072     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6073   else
6074     p += xsnprintf (p, endp - p, ";c");
6075
6076   if (remote_multi_process_p (rs) && ptid.is_pid ())
6077     {
6078       ptid_t nptid;
6079
6080       /* All (-1) threads of process.  */
6081       nptid = ptid_t (ptid.pid (), -1, 0);
6082
6083       p += xsnprintf (p, endp - p, ":");
6084       p = write_ptid (p, endp, nptid);
6085     }
6086   else if (ptid != minus_one_ptid)
6087     {
6088       p += xsnprintf (p, endp - p, ":");
6089       p = write_ptid (p, endp, ptid);
6090     }
6091
6092   return p;
6093 }
6094
6095 /* Clear the thread's private info on resume.  */
6096
6097 static void
6098 resume_clear_thread_private_info (struct thread_info *thread)
6099 {
6100   if (thread->priv != NULL)
6101     {
6102       remote_thread_info *priv = get_remote_thread_info (thread);
6103
6104       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6105       priv->watch_data_address = 0;
6106     }
6107 }
6108
6109 /* Append a vCont continue-with-signal action for threads that have a
6110    non-zero stop signal.  */
6111
6112 char *
6113 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6114                                                   ptid_t ptid)
6115 {
6116   struct thread_info *thread;
6117
6118   ALL_NON_EXITED_THREADS (thread)
6119     if (thread->ptid.matches (ptid)
6120         && inferior_ptid != thread->ptid
6121         && thread->suspend.stop_signal != GDB_SIGNAL_0)
6122       {
6123         p = append_resumption (p, endp, thread->ptid,
6124                                0, thread->suspend.stop_signal);
6125         thread->suspend.stop_signal = GDB_SIGNAL_0;
6126         resume_clear_thread_private_info (thread);
6127       }
6128
6129   return p;
6130 }
6131
6132 /* Set the target running, using the packets that use Hc
6133    (c/s/C/S).  */
6134
6135 void
6136 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6137                                       gdb_signal siggnal)
6138 {
6139   struct remote_state *rs = get_remote_state ();
6140   struct thread_info *thread;
6141   char *buf;
6142
6143   rs->last_sent_signal = siggnal;
6144   rs->last_sent_step = step;
6145
6146   /* The c/s/C/S resume packets use Hc, so set the continue
6147      thread.  */
6148   if (ptid == minus_one_ptid)
6149     set_continue_thread (any_thread_ptid);
6150   else
6151     set_continue_thread (ptid);
6152
6153   ALL_NON_EXITED_THREADS (thread)
6154     resume_clear_thread_private_info (thread);
6155
6156   buf = rs->buf;
6157   if (::execution_direction == EXEC_REVERSE)
6158     {
6159       /* We don't pass signals to the target in reverse exec mode.  */
6160       if (info_verbose && siggnal != GDB_SIGNAL_0)
6161         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6162                  siggnal);
6163
6164       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6165         error (_("Remote reverse-step not supported."));
6166       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6167         error (_("Remote reverse-continue not supported."));
6168
6169       strcpy (buf, step ? "bs" : "bc");
6170     }
6171   else if (siggnal != GDB_SIGNAL_0)
6172     {
6173       buf[0] = step ? 'S' : 'C';
6174       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6175       buf[2] = tohex (((int) siggnal) & 0xf);
6176       buf[3] = '\0';
6177     }
6178   else
6179     strcpy (buf, step ? "s" : "c");
6180
6181   putpkt (buf);
6182 }
6183
6184 /* Resume the remote inferior by using a "vCont" packet.  The thread
6185    to be resumed is PTID; STEP and SIGGNAL indicate whether the
6186    resumed thread should be single-stepped and/or signalled.  If PTID
6187    equals minus_one_ptid, then all threads are resumed; the thread to
6188    be stepped and/or signalled is given in the global INFERIOR_PTID.
6189    This function returns non-zero iff it resumes the inferior.
6190
6191    This function issues a strict subset of all possible vCont commands
6192    at the moment.  */
6193
6194 int
6195 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6196                                          enum gdb_signal siggnal)
6197 {
6198   struct remote_state *rs = get_remote_state ();
6199   char *p;
6200   char *endp;
6201
6202   /* No reverse execution actions defined for vCont.  */
6203   if (::execution_direction == EXEC_REVERSE)
6204     return 0;
6205
6206   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6207     remote_vcont_probe ();
6208
6209   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6210     return 0;
6211
6212   p = rs->buf;
6213   endp = rs->buf + get_remote_packet_size ();
6214
6215   /* If we could generate a wider range of packets, we'd have to worry
6216      about overflowing BUF.  Should there be a generic
6217      "multi-part-packet" packet?  */
6218
6219   p += xsnprintf (p, endp - p, "vCont");
6220
6221   if (ptid == magic_null_ptid)
6222     {
6223       /* MAGIC_NULL_PTID means that we don't have any active threads,
6224          so we don't have any TID numbers the inferior will
6225          understand.  Make sure to only send forms that do not specify
6226          a TID.  */
6227       append_resumption (p, endp, minus_one_ptid, step, siggnal);
6228     }
6229   else if (ptid == minus_one_ptid || ptid.is_pid ())
6230     {
6231       /* Resume all threads (of all processes, or of a single
6232          process), with preference for INFERIOR_PTID.  This assumes
6233          inferior_ptid belongs to the set of all threads we are about
6234          to resume.  */
6235       if (step || siggnal != GDB_SIGNAL_0)
6236         {
6237           /* Step inferior_ptid, with or without signal.  */
6238           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6239         }
6240
6241       /* Also pass down any pending signaled resumption for other
6242          threads not the current.  */
6243       p = append_pending_thread_resumptions (p, endp, ptid);
6244
6245       /* And continue others without a signal.  */
6246       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6247     }
6248   else
6249     {
6250       /* Scheduler locking; resume only PTID.  */
6251       append_resumption (p, endp, ptid, step, siggnal);
6252     }
6253
6254   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6255   putpkt (rs->buf);
6256
6257   if (target_is_non_stop_p ())
6258     {
6259       /* In non-stop, the stub replies to vCont with "OK".  The stop
6260          reply will be reported asynchronously by means of a `%Stop'
6261          notification.  */
6262       getpkt (&rs->buf, &rs->buf_size, 0);
6263       if (strcmp (rs->buf, "OK") != 0)
6264         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6265     }
6266
6267   return 1;
6268 }
6269
6270 /* Tell the remote machine to resume.  */
6271
6272 void
6273 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6274 {
6275   struct remote_state *rs = get_remote_state ();
6276
6277   /* When connected in non-stop mode, the core resumes threads
6278      individually.  Resuming remote threads directly in target_resume
6279      would thus result in sending one packet per thread.  Instead, to
6280      minimize roundtrip latency, here we just store the resume
6281      request; the actual remote resumption will be done in
6282      target_commit_resume / remote_commit_resume, where we'll be able
6283      to do vCont action coalescing.  */
6284   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6285     {
6286       remote_thread_info *remote_thr;
6287
6288       if (minus_one_ptid == ptid || ptid.is_pid ())
6289         remote_thr = get_remote_thread_info (inferior_ptid);
6290       else
6291         remote_thr = get_remote_thread_info (ptid);
6292
6293       remote_thr->last_resume_step = step;
6294       remote_thr->last_resume_sig = siggnal;
6295       return;
6296     }
6297
6298   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6299      (explained in remote-notif.c:handle_notification) so
6300      remote_notif_process is not called.  We need find a place where
6301      it is safe to start a 'vNotif' sequence.  It is good to do it
6302      before resuming inferior, because inferior was stopped and no RSP
6303      traffic at that moment.  */
6304   if (!target_is_non_stop_p ())
6305     remote_notif_process (rs->notif_state, &notif_client_stop);
6306
6307   rs->last_resume_exec_dir = ::execution_direction;
6308
6309   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6310   if (!remote_resume_with_vcont (ptid, step, siggnal))
6311     remote_resume_with_hc (ptid, step, siggnal);
6312
6313   /* We are about to start executing the inferior, let's register it
6314      with the event loop.  NOTE: this is the one place where all the
6315      execution commands end up.  We could alternatively do this in each
6316      of the execution commands in infcmd.c.  */
6317   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6318      into infcmd.c in order to allow inferior function calls to work
6319      NOT asynchronously.  */
6320   if (target_can_async_p ())
6321     target_async (1);
6322
6323   /* We've just told the target to resume.  The remote server will
6324      wait for the inferior to stop, and then send a stop reply.  In
6325      the mean time, we can't start another command/query ourselves
6326      because the stub wouldn't be ready to process it.  This applies
6327      only to the base all-stop protocol, however.  In non-stop (which
6328      only supports vCont), the stub replies with an "OK", and is
6329      immediate able to process further serial input.  */
6330   if (!target_is_non_stop_p ())
6331     rs->waiting_for_stop_reply = 1;
6332 }
6333
6334 static int is_pending_fork_parent_thread (struct thread_info *thread);
6335
6336 /* Private per-inferior info for target remote processes.  */
6337
6338 struct remote_inferior : public private_inferior
6339 {
6340   /* Whether we can send a wildcard vCont for this process.  */
6341   bool may_wildcard_vcont = true;
6342 };
6343
6344 /* Get the remote private inferior data associated to INF.  */
6345
6346 static remote_inferior *
6347 get_remote_inferior (inferior *inf)
6348 {
6349   if (inf->priv == NULL)
6350     inf->priv.reset (new remote_inferior);
6351
6352   return static_cast<remote_inferior *> (inf->priv.get ());
6353 }
6354
6355 /* Class used to track the construction of a vCont packet in the
6356    outgoing packet buffer.  This is used to send multiple vCont
6357    packets if we have more actions than would fit a single packet.  */
6358
6359 class vcont_builder
6360 {
6361 public:
6362   explicit vcont_builder (remote_target *remote)
6363     : m_remote (remote)
6364   {
6365     restart ();
6366   }
6367
6368   void flush ();
6369   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6370
6371 private:
6372   void restart ();
6373
6374   /* The remote target.  */
6375   remote_target *m_remote;
6376
6377   /* Pointer to the first action.  P points here if no action has been
6378      appended yet.  */
6379   char *m_first_action;
6380
6381   /* Where the next action will be appended.  */
6382   char *m_p;
6383
6384   /* The end of the buffer.  Must never write past this.  */
6385   char *m_endp;
6386 };
6387
6388 /* Prepare the outgoing buffer for a new vCont packet.  */
6389
6390 void
6391 vcont_builder::restart ()
6392 {
6393   struct remote_state *rs = m_remote->get_remote_state ();
6394
6395   m_p = rs->buf;
6396   m_endp = rs->buf + m_remote->get_remote_packet_size ();
6397   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6398   m_first_action = m_p;
6399 }
6400
6401 /* If the vCont packet being built has any action, send it to the
6402    remote end.  */
6403
6404 void
6405 vcont_builder::flush ()
6406 {
6407   struct remote_state *rs;
6408
6409   if (m_p == m_first_action)
6410     return;
6411
6412   rs = m_remote->get_remote_state ();
6413   m_remote->putpkt (rs->buf);
6414   m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6415   if (strcmp (rs->buf, "OK") != 0)
6416     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6417 }
6418
6419 /* The largest action is range-stepping, with its two addresses.  This
6420    is more than sufficient.  If a new, bigger action is created, it'll
6421    quickly trigger a failed assertion in append_resumption (and we'll
6422    just bump this).  */
6423 #define MAX_ACTION_SIZE 200
6424
6425 /* Append a new vCont action in the outgoing packet being built.  If
6426    the action doesn't fit the packet along with previous actions, push
6427    what we've got so far to the remote end and start over a new vCont
6428    packet (with the new action).  */
6429
6430 void
6431 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6432 {
6433   char buf[MAX_ACTION_SIZE + 1];
6434
6435   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6436                                             ptid, step, siggnal);
6437
6438   /* Check whether this new action would fit in the vCont packet along
6439      with previous actions.  If not, send what we've got so far and
6440      start a new vCont packet.  */
6441   size_t rsize = endp - buf;
6442   if (rsize > m_endp - m_p)
6443     {
6444       flush ();
6445       restart ();
6446
6447       /* Should now fit.  */
6448       gdb_assert (rsize <= m_endp - m_p);
6449     }
6450
6451   memcpy (m_p, buf, rsize);
6452   m_p += rsize;
6453   *m_p = '\0';
6454 }
6455
6456 /* to_commit_resume implementation.  */
6457
6458 void
6459 remote_target::commit_resume ()
6460 {
6461   struct inferior *inf;
6462   struct thread_info *tp;
6463   int any_process_wildcard;
6464   int may_global_wildcard_vcont;
6465
6466   /* If connected in all-stop mode, we'd send the remote resume
6467      request directly from remote_resume.  Likewise if
6468      reverse-debugging, as there are no defined vCont actions for
6469      reverse execution.  */
6470   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6471     return;
6472
6473   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6474      instead of resuming all threads of each process individually.
6475      However, if any thread of a process must remain halted, we can't
6476      send wildcard resumes and must send one action per thread.
6477
6478      Care must be taken to not resume threads/processes the server
6479      side already told us are stopped, but the core doesn't know about
6480      yet, because the events are still in the vStopped notification
6481      queue.  For example:
6482
6483        #1 => vCont s:p1.1;c
6484        #2 <= OK
6485        #3 <= %Stopped T05 p1.1
6486        #4 => vStopped
6487        #5 <= T05 p1.2
6488        #6 => vStopped
6489        #7 <= OK
6490        #8 (infrun handles the stop for p1.1 and continues stepping)
6491        #9 => vCont s:p1.1;c
6492
6493      The last vCont above would resume thread p1.2 by mistake, because
6494      the server has no idea that the event for p1.2 had not been
6495      handled yet.
6496
6497      The server side must similarly ignore resume actions for the
6498      thread that has a pending %Stopped notification (and any other
6499      threads with events pending), until GDB acks the notification
6500      with vStopped.  Otherwise, e.g., the following case is
6501      mishandled:
6502
6503        #1 => g  (or any other packet)
6504        #2 <= [registers]
6505        #3 <= %Stopped T05 p1.2
6506        #4 => vCont s:p1.1;c
6507        #5 <= OK
6508
6509      Above, the server must not resume thread p1.2.  GDB can't know
6510      that p1.2 stopped until it acks the %Stopped notification, and
6511      since from GDB's perspective all threads should be running, it
6512      sends a "c" action.
6513
6514      Finally, special care must also be given to handling fork/vfork
6515      events.  A (v)fork event actually tells us that two processes
6516      stopped -- the parent and the child.  Until we follow the fork,
6517      we must not resume the child.  Therefore, if we have a pending
6518      fork follow, we must not send a global wildcard resume action
6519      (vCont;c).  We can still send process-wide wildcards though.  */
6520
6521   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6522   may_global_wildcard_vcont = 1;
6523
6524   /* And assume every process is individually wildcard-able too.  */
6525   ALL_NON_EXITED_INFERIORS (inf)
6526     {
6527       remote_inferior *priv = get_remote_inferior (inf);
6528
6529       priv->may_wildcard_vcont = true;
6530     }
6531
6532   /* Check for any pending events (not reported or processed yet) and
6533      disable process and global wildcard resumes appropriately.  */
6534   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6535
6536   ALL_NON_EXITED_THREADS (tp)
6537     {
6538       /* If a thread of a process is not meant to be resumed, then we
6539          can't wildcard that process.  */
6540       if (!tp->executing)
6541         {
6542           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6543
6544           /* And if we can't wildcard a process, we can't wildcard
6545              everything either.  */
6546           may_global_wildcard_vcont = 0;
6547           continue;
6548         }
6549
6550       /* If a thread is the parent of an unfollowed fork, then we
6551          can't do a global wildcard, as that would resume the fork
6552          child.  */
6553       if (is_pending_fork_parent_thread (tp))
6554         may_global_wildcard_vcont = 0;
6555     }
6556
6557   /* Now let's build the vCont packet(s).  Actions must be appended
6558      from narrower to wider scopes (thread -> process -> global).  If
6559      we end up with too many actions for a single packet vcont_builder
6560      flushes the current vCont packet to the remote side and starts a
6561      new one.  */
6562   struct vcont_builder vcont_builder (this);
6563
6564   /* Threads first.  */
6565   ALL_NON_EXITED_THREADS (tp)
6566     {
6567       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6568
6569       if (!tp->executing || remote_thr->vcont_resumed)
6570         continue;
6571
6572       gdb_assert (!thread_is_in_step_over_chain (tp));
6573
6574       if (!remote_thr->last_resume_step
6575           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6576           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6577         {
6578           /* We'll send a wildcard resume instead.  */
6579           remote_thr->vcont_resumed = 1;
6580           continue;
6581         }
6582
6583       vcont_builder.push_action (tp->ptid,
6584                                  remote_thr->last_resume_step,
6585                                  remote_thr->last_resume_sig);
6586       remote_thr->vcont_resumed = 1;
6587     }
6588
6589   /* Now check whether we can send any process-wide wildcard.  This is
6590      to avoid sending a global wildcard in the case nothing is
6591      supposed to be resumed.  */
6592   any_process_wildcard = 0;
6593
6594   ALL_NON_EXITED_INFERIORS (inf)
6595     {
6596       if (get_remote_inferior (inf)->may_wildcard_vcont)
6597         {
6598           any_process_wildcard = 1;
6599           break;
6600         }
6601     }
6602
6603   if (any_process_wildcard)
6604     {
6605       /* If all processes are wildcard-able, then send a single "c"
6606          action, otherwise, send an "all (-1) threads of process"
6607          continue action for each running process, if any.  */
6608       if (may_global_wildcard_vcont)
6609         {
6610           vcont_builder.push_action (minus_one_ptid,
6611                                      false, GDB_SIGNAL_0);
6612         }
6613       else
6614         {
6615           ALL_NON_EXITED_INFERIORS (inf)
6616             {
6617               if (get_remote_inferior (inf)->may_wildcard_vcont)
6618                 {
6619                   vcont_builder.push_action (ptid_t (inf->pid),
6620                                              false, GDB_SIGNAL_0);
6621                 }
6622             }
6623         }
6624     }
6625
6626   vcont_builder.flush ();
6627 }
6628
6629 \f
6630
6631 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6632    thread, all threads of a remote process, or all threads of all
6633    processes.  */
6634
6635 void
6636 remote_target::remote_stop_ns (ptid_t ptid)
6637 {
6638   struct remote_state *rs = get_remote_state ();
6639   char *p = rs->buf;
6640   char *endp = rs->buf + get_remote_packet_size ();
6641
6642   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6643     remote_vcont_probe ();
6644
6645   if (!rs->supports_vCont.t)
6646     error (_("Remote server does not support stopping threads"));
6647
6648   if (ptid == minus_one_ptid
6649       || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6650     p += xsnprintf (p, endp - p, "vCont;t");
6651   else
6652     {
6653       ptid_t nptid;
6654
6655       p += xsnprintf (p, endp - p, "vCont;t:");
6656
6657       if (ptid.is_pid ())
6658           /* All (-1) threads of process.  */
6659         nptid = ptid_t (ptid.pid (), -1, 0);
6660       else
6661         {
6662           /* Small optimization: if we already have a stop reply for
6663              this thread, no use in telling the stub we want this
6664              stopped.  */
6665           if (peek_stop_reply (ptid))
6666             return;
6667
6668           nptid = ptid;
6669         }
6670
6671       write_ptid (p, endp, nptid);
6672     }
6673
6674   /* In non-stop, we get an immediate OK reply.  The stop reply will
6675      come in asynchronously by notification.  */
6676   putpkt (rs->buf);
6677   getpkt (&rs->buf, &rs->buf_size, 0);
6678   if (strcmp (rs->buf, "OK") != 0)
6679     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6680 }
6681
6682 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6683    interrupt the remote target.  It is undefined which thread of which
6684    process reports the interrupt.  */
6685
6686 void
6687 remote_target::remote_interrupt_as ()
6688 {
6689   struct remote_state *rs = get_remote_state ();
6690
6691   rs->ctrlc_pending_p = 1;
6692
6693   /* If the inferior is stopped already, but the core didn't know
6694      about it yet, just ignore the request.  The cached wait status
6695      will be collected in remote_wait.  */
6696   if (rs->cached_wait_status)
6697     return;
6698
6699   /* Send interrupt_sequence to remote target.  */
6700   send_interrupt_sequence ();
6701 }
6702
6703 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6704    the remote target.  It is undefined which thread of which process
6705    reports the interrupt.  Throws an error if the packet is not
6706    supported by the server.  */
6707
6708 void
6709 remote_target::remote_interrupt_ns ()
6710 {
6711   struct remote_state *rs = get_remote_state ();
6712   char *p = rs->buf;
6713   char *endp = rs->buf + get_remote_packet_size ();
6714
6715   xsnprintf (p, endp - p, "vCtrlC");
6716
6717   /* In non-stop, we get an immediate OK reply.  The stop reply will
6718      come in asynchronously by notification.  */
6719   putpkt (rs->buf);
6720   getpkt (&rs->buf, &rs->buf_size, 0);
6721
6722   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6723     {
6724     case PACKET_OK:
6725       break;
6726     case PACKET_UNKNOWN:
6727       error (_("No support for interrupting the remote target."));
6728     case PACKET_ERROR:
6729       error (_("Interrupting target failed: %s"), rs->buf);
6730     }
6731 }
6732
6733 /* Implement the to_stop function for the remote targets.  */
6734
6735 void
6736 remote_target::stop (ptid_t ptid)
6737 {
6738   if (remote_debug)
6739     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6740
6741   if (target_is_non_stop_p ())
6742     remote_stop_ns (ptid);
6743   else
6744     {
6745       /* We don't currently have a way to transparently pause the
6746          remote target in all-stop mode.  Interrupt it instead.  */
6747       remote_interrupt_as ();
6748     }
6749 }
6750
6751 /* Implement the to_interrupt function for the remote targets.  */
6752
6753 void
6754 remote_target::interrupt ()
6755 {
6756   if (remote_debug)
6757     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6758
6759   if (target_is_non_stop_p ())
6760     remote_interrupt_ns ();
6761   else
6762     remote_interrupt_as ();
6763 }
6764
6765 /* Implement the to_pass_ctrlc function for the remote targets.  */
6766
6767 void
6768 remote_target::pass_ctrlc ()
6769 {
6770   struct remote_state *rs = get_remote_state ();
6771
6772   if (remote_debug)
6773     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6774
6775   /* If we're starting up, we're not fully synced yet.  Quit
6776      immediately.  */
6777   if (rs->starting_up)
6778     quit ();
6779   /* If ^C has already been sent once, offer to disconnect.  */
6780   else if (rs->ctrlc_pending_p)
6781     interrupt_query ();
6782   else
6783     target_interrupt ();
6784 }
6785
6786 /* Ask the user what to do when an interrupt is received.  */
6787
6788 void
6789 remote_target::interrupt_query ()
6790 {
6791   struct remote_state *rs = get_remote_state ();
6792
6793   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6794     {
6795       if (query (_("The target is not responding to interrupt requests.\n"
6796                    "Stop debugging it? ")))
6797         {
6798           remote_unpush_target ();
6799           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6800         }
6801     }
6802   else
6803     {
6804       if (query (_("Interrupted while waiting for the program.\n"
6805                    "Give up waiting? ")))
6806         quit ();
6807     }
6808 }
6809
6810 /* Enable/disable target terminal ownership.  Most targets can use
6811    terminal groups to control terminal ownership.  Remote targets are
6812    different in that explicit transfer of ownership to/from GDB/target
6813    is required.  */
6814
6815 void
6816 remote_target::terminal_inferior ()
6817 {
6818   /* NOTE: At this point we could also register our selves as the
6819      recipient of all input.  Any characters typed could then be
6820      passed on down to the target.  */
6821 }
6822
6823 void
6824 remote_target::terminal_ours ()
6825 {
6826 }
6827
6828 static void
6829 remote_console_output (char *msg)
6830 {
6831   char *p;
6832
6833   for (p = msg; p[0] && p[1]; p += 2)
6834     {
6835       char tb[2];
6836       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6837
6838       tb[0] = c;
6839       tb[1] = 0;
6840       fputs_unfiltered (tb, gdb_stdtarg);
6841     }
6842   gdb_flush (gdb_stdtarg);
6843 }
6844
6845 DEF_VEC_O(cached_reg_t);
6846
6847 typedef struct stop_reply
6848 {
6849   struct notif_event base;
6850
6851   /* The identifier of the thread about this event  */
6852   ptid_t ptid;
6853
6854   /* The remote state this event is associated with.  When the remote
6855      connection, represented by a remote_state object, is closed,
6856      all the associated stop_reply events should be released.  */
6857   struct remote_state *rs;
6858
6859   struct target_waitstatus ws;
6860
6861   /* The architecture associated with the expedited registers.  */
6862   gdbarch *arch;
6863
6864   /* Expedited registers.  This makes remote debugging a bit more
6865      efficient for those targets that provide critical registers as
6866      part of their normal status mechanism (as another roundtrip to
6867      fetch them is avoided).  */
6868   VEC(cached_reg_t) *regcache;
6869
6870   enum target_stop_reason stop_reason;
6871
6872   CORE_ADDR watch_data_address;
6873
6874   int core;
6875 } *stop_reply_p;
6876
6877 static void
6878 stop_reply_xfree (struct stop_reply *r)
6879 {
6880   notif_event_xfree ((struct notif_event *) r);
6881 }
6882
6883 /* Return the length of the stop reply queue.  */
6884
6885 int
6886 remote_target::stop_reply_queue_length ()
6887 {
6888   remote_state *rs = get_remote_state ();
6889   return rs->stop_reply_queue.size ();
6890 }
6891
6892 void
6893 remote_notif_stop_parse (remote_target *remote,
6894                          struct notif_client *self, char *buf,
6895                          struct notif_event *event)
6896 {
6897   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6898 }
6899
6900 static void
6901 remote_notif_stop_ack (remote_target *remote,
6902                        struct notif_client *self, char *buf,
6903                        struct notif_event *event)
6904 {
6905   struct stop_reply *stop_reply = (struct stop_reply *) event;
6906
6907   /* acknowledge */
6908   putpkt (remote, self->ack_command);
6909
6910   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6911     {
6912       /* We got an unknown stop reply.  */
6913       error (_("Unknown stop reply"));
6914     }
6915
6916   remote->push_stop_reply (stop_reply);
6917 }
6918
6919 static int
6920 remote_notif_stop_can_get_pending_events (remote_target *remote,
6921                                           struct notif_client *self)
6922 {
6923   /* We can't get pending events in remote_notif_process for
6924      notification stop, and we have to do this in remote_wait_ns
6925      instead.  If we fetch all queued events from stub, remote stub
6926      may exit and we have no chance to process them back in
6927      remote_wait_ns.  */
6928   remote_state *rs = remote->get_remote_state ();
6929   mark_async_event_handler (rs->remote_async_inferior_event_token);
6930   return 0;
6931 }
6932
6933 static void
6934 stop_reply_dtr (struct notif_event *event)
6935 {
6936   struct stop_reply *r = (struct stop_reply *) event;
6937   cached_reg_t *reg;
6938   int ix;
6939
6940   for (ix = 0;
6941        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6942        ix++)
6943     xfree (reg->data);
6944
6945   VEC_free (cached_reg_t, r->regcache);
6946 }
6947
6948 static struct notif_event *
6949 remote_notif_stop_alloc_reply (void)
6950 {
6951   /* We cast to a pointer to the "base class".  */
6952   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6953
6954   r->dtr = stop_reply_dtr;
6955
6956   return r;
6957 }
6958
6959 /* A client of notification Stop.  */
6960
6961 struct notif_client notif_client_stop =
6962 {
6963   "Stop",
6964   "vStopped",
6965   remote_notif_stop_parse,
6966   remote_notif_stop_ack,
6967   remote_notif_stop_can_get_pending_events,
6968   remote_notif_stop_alloc_reply,
6969   REMOTE_NOTIF_STOP,
6970 };
6971
6972 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6973    the pid of the process that owns the threads we want to check, or
6974    -1 if we want to check all threads.  */
6975
6976 static int
6977 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6978                         ptid_t thread_ptid)
6979 {
6980   if (ws->kind == TARGET_WAITKIND_FORKED
6981       || ws->kind == TARGET_WAITKIND_VFORKED)
6982     {
6983       if (event_pid == -1 || event_pid == thread_ptid.pid ())
6984         return 1;
6985     }
6986
6987   return 0;
6988 }
6989
6990 /* Return the thread's pending status used to determine whether the
6991    thread is a fork parent stopped at a fork event.  */
6992
6993 static struct target_waitstatus *
6994 thread_pending_fork_status (struct thread_info *thread)
6995 {
6996   if (thread->suspend.waitstatus_pending_p)
6997     return &thread->suspend.waitstatus;
6998   else
6999     return &thread->pending_follow;
7000 }
7001
7002 /* Determine if THREAD is a pending fork parent thread.  */
7003
7004 static int
7005 is_pending_fork_parent_thread (struct thread_info *thread)
7006 {
7007   struct target_waitstatus *ws = thread_pending_fork_status (thread);
7008   int pid = -1;
7009
7010   return is_pending_fork_parent (ws, pid, thread->ptid);
7011 }
7012
7013 /* If CONTEXT contains any fork child threads that have not been
7014    reported yet, remove them from the CONTEXT list.  If such a
7015    thread exists it is because we are stopped at a fork catchpoint
7016    and have not yet called follow_fork, which will set up the
7017    host-side data structures for the new process.  */
7018
7019 void
7020 remote_target::remove_new_fork_children (threads_listing_context *context)
7021 {
7022   struct thread_info * thread;
7023   int pid = -1;
7024   struct notif_client *notif = &notif_client_stop;
7025
7026   /* For any threads stopped at a fork event, remove the corresponding
7027      fork child threads from the CONTEXT list.  */
7028   ALL_NON_EXITED_THREADS (thread)
7029     {
7030       struct target_waitstatus *ws = thread_pending_fork_status (thread);
7031
7032       if (is_pending_fork_parent (ws, pid, thread->ptid))
7033         context->remove_thread (ws->value.related_pid);
7034     }
7035
7036   /* Check for any pending fork events (not reported or processed yet)
7037      in process PID and remove those fork child threads from the
7038      CONTEXT list as well.  */
7039   remote_notif_get_pending_events (notif);
7040   for (auto &event : get_remote_state ()->stop_reply_queue)
7041     if (event->ws.kind == TARGET_WAITKIND_FORKED
7042         || event->ws.kind == TARGET_WAITKIND_VFORKED
7043         || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
7044       context->remove_thread (event->ws.value.related_pid);
7045 }
7046
7047 /* Check whether any event pending in the vStopped queue would prevent
7048    a global or process wildcard vCont action.  Clear
7049    *may_global_wildcard if we can't do a global wildcard (vCont;c),
7050    and clear the event inferior's may_wildcard_vcont flag if we can't
7051    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
7052
7053 void
7054 remote_target::check_pending_events_prevent_wildcard_vcont
7055   (int *may_global_wildcard)
7056 {
7057   struct notif_client *notif = &notif_client_stop;
7058
7059   remote_notif_get_pending_events (notif);
7060   for (auto &event : get_remote_state ()->stop_reply_queue)
7061     {
7062       if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7063           || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7064         continue;
7065
7066       if (event->ws.kind == TARGET_WAITKIND_FORKED
7067           || event->ws.kind == TARGET_WAITKIND_VFORKED)
7068         *may_global_wildcard = 0;
7069
7070       struct inferior *inf = find_inferior_ptid (event->ptid);
7071
7072       /* This may be the first time we heard about this process.
7073          Regardless, we must not do a global wildcard resume, otherwise
7074          we'd resume this process too.  */
7075       *may_global_wildcard = 0;
7076       if (inf != NULL)
7077         get_remote_inferior (inf)->may_wildcard_vcont = false;
7078     }
7079 }
7080
7081 /* Discard all pending stop replies of inferior INF.  */
7082
7083 void
7084 remote_target::discard_pending_stop_replies (struct inferior *inf)
7085 {
7086   struct stop_reply *reply;
7087   struct remote_state *rs = get_remote_state ();
7088   struct remote_notif_state *rns = rs->notif_state;
7089
7090   /* This function can be notified when an inferior exists.  When the
7091      target is not remote, the notification state is NULL.  */
7092   if (rs->remote_desc == NULL)
7093     return;
7094
7095   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7096
7097   /* Discard the in-flight notification.  */
7098   if (reply != NULL && reply->ptid.pid () == inf->pid)
7099     {
7100       stop_reply_xfree (reply);
7101       rns->pending_event[notif_client_stop.id] = NULL;
7102     }
7103
7104   /* Discard the stop replies we have already pulled with
7105      vStopped.  */
7106   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7107                               rs->stop_reply_queue.end (),
7108                               [=] (const stop_reply_up &event)
7109                               {
7110                                 return event->ptid.pid () == inf->pid;
7111                               });
7112   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7113 }
7114
7115 /* Discard the stop replies for RS in stop_reply_queue.  */
7116
7117 void
7118 remote_target::discard_pending_stop_replies_in_queue ()
7119 {
7120   remote_state *rs = get_remote_state ();
7121
7122   /* Discard the stop replies we have already pulled with
7123      vStopped.  */
7124   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7125                               rs->stop_reply_queue.end (),
7126                               [=] (const stop_reply_up &event)
7127                               {
7128                                 return event->rs == rs;
7129                               });
7130   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7131 }
7132
7133 /* Remove the first reply in 'stop_reply_queue' which matches
7134    PTID.  */
7135
7136 struct stop_reply *
7137 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7138 {
7139   remote_state *rs = get_remote_state ();
7140
7141   auto iter = std::find_if (rs->stop_reply_queue.begin (),
7142                             rs->stop_reply_queue.end (),
7143                             [=] (const stop_reply_up &event)
7144                             {
7145                               return event->ptid.matches (ptid);
7146                             });
7147   struct stop_reply *result;
7148   if (iter == rs->stop_reply_queue.end ())
7149     result = nullptr;
7150   else
7151     {
7152       result = iter->release ();
7153       rs->stop_reply_queue.erase (iter);
7154     }
7155
7156   if (notif_debug)
7157     fprintf_unfiltered (gdb_stdlog,
7158                         "notif: discard queued event: 'Stop' in %s\n",
7159                         target_pid_to_str (ptid));
7160
7161   return result;
7162 }
7163
7164 /* Look for a queued stop reply belonging to PTID.  If one is found,
7165    remove it from the queue, and return it.  Returns NULL if none is
7166    found.  If there are still queued events left to process, tell the
7167    event loop to get back to target_wait soon.  */
7168
7169 struct stop_reply *
7170 remote_target::queued_stop_reply (ptid_t ptid)
7171 {
7172   remote_state *rs = get_remote_state ();
7173   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7174
7175   if (!rs->stop_reply_queue.empty ())
7176     {
7177       /* There's still at least an event left.  */
7178       mark_async_event_handler (rs->remote_async_inferior_event_token);
7179     }
7180
7181   return r;
7182 }
7183
7184 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7185    know that we now have at least one queued event left to pass to the
7186    core side, tell the event loop to get back to target_wait soon.  */
7187
7188 void
7189 remote_target::push_stop_reply (struct stop_reply *new_event)
7190 {
7191   remote_state *rs = get_remote_state ();
7192   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7193
7194   if (notif_debug)
7195     fprintf_unfiltered (gdb_stdlog,
7196                         "notif: push 'Stop' %s to queue %d\n",
7197                         target_pid_to_str (new_event->ptid),
7198                         int (rs->stop_reply_queue.size ()));
7199
7200   mark_async_event_handler (rs->remote_async_inferior_event_token);
7201 }
7202
7203 /* Returns true if we have a stop reply for PTID.  */
7204
7205 int
7206 remote_target::peek_stop_reply (ptid_t ptid)
7207 {
7208   remote_state *rs = get_remote_state ();
7209   for (auto &event : rs->stop_reply_queue)
7210     if (ptid == event->ptid
7211         && event->ws.kind == TARGET_WAITKIND_STOPPED)
7212       return 1;
7213   return 0;
7214 }
7215
7216 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7217    starting with P and ending with PEND matches PREFIX.  */
7218
7219 static int
7220 strprefix (const char *p, const char *pend, const char *prefix)
7221 {
7222   for ( ; p < pend; p++, prefix++)
7223     if (*p != *prefix)
7224       return 0;
7225   return *prefix == '\0';
7226 }
7227
7228 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7229    result is stored in EVENT, or throws an error.  */
7230
7231 void
7232 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7233 {
7234   remote_arch_state *rsa = NULL;
7235   ULONGEST addr;
7236   const char *p;
7237   int skipregs = 0;
7238
7239   event->ptid = null_ptid;
7240   event->rs = get_remote_state ();
7241   event->ws.kind = TARGET_WAITKIND_IGNORE;
7242   event->ws.value.integer = 0;
7243   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7244   event->regcache = NULL;
7245   event->core = -1;
7246
7247   switch (buf[0])
7248     {
7249     case 'T':           /* Status with PC, SP, FP, ...  */
7250       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7251       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7252             ss = signal number
7253             n... = register number
7254             r... = register contents
7255       */
7256
7257       p = &buf[3];      /* after Txx */
7258       while (*p)
7259         {
7260           const char *p1;
7261           int fieldsize;
7262
7263           p1 = strchr (p, ':');
7264           if (p1 == NULL)
7265             error (_("Malformed packet(a) (missing colon): %s\n\
7266 Packet: '%s'\n"),
7267                    p, buf);
7268           if (p == p1)
7269             error (_("Malformed packet(a) (missing register number): %s\n\
7270 Packet: '%s'\n"),
7271                    p, buf);
7272
7273           /* Some "registers" are actually extended stop information.
7274              Note if you're adding a new entry here: GDB 7.9 and
7275              earlier assume that all register "numbers" that start
7276              with an hex digit are real register numbers.  Make sure
7277              the server only sends such a packet if it knows the
7278              client understands it.  */
7279
7280           if (strprefix (p, p1, "thread"))
7281             event->ptid = read_ptid (++p1, &p);
7282           else if (strprefix (p, p1, "syscall_entry"))
7283             {
7284               ULONGEST sysno;
7285
7286               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7287               p = unpack_varlen_hex (++p1, &sysno);
7288               event->ws.value.syscall_number = (int) sysno;
7289             }
7290           else if (strprefix (p, p1, "syscall_return"))
7291             {
7292               ULONGEST sysno;
7293
7294               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7295               p = unpack_varlen_hex (++p1, &sysno);
7296               event->ws.value.syscall_number = (int) sysno;
7297             }
7298           else if (strprefix (p, p1, "watch")
7299                    || strprefix (p, p1, "rwatch")
7300                    || strprefix (p, p1, "awatch"))
7301             {
7302               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7303               p = unpack_varlen_hex (++p1, &addr);
7304               event->watch_data_address = (CORE_ADDR) addr;
7305             }
7306           else if (strprefix (p, p1, "swbreak"))
7307             {
7308               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7309
7310               /* Make sure the stub doesn't forget to indicate support
7311                  with qSupported.  */
7312               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7313                 error (_("Unexpected swbreak stop reason"));
7314
7315               /* The value part is documented as "must be empty",
7316                  though we ignore it, in case we ever decide to make
7317                  use of it in a backward compatible way.  */
7318               p = strchrnul (p1 + 1, ';');
7319             }
7320           else if (strprefix (p, p1, "hwbreak"))
7321             {
7322               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7323
7324               /* Make sure the stub doesn't forget to indicate support
7325                  with qSupported.  */
7326               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7327                 error (_("Unexpected hwbreak stop reason"));
7328
7329               /* See above.  */
7330               p = strchrnul (p1 + 1, ';');
7331             }
7332           else if (strprefix (p, p1, "library"))
7333             {
7334               event->ws.kind = TARGET_WAITKIND_LOADED;
7335               p = strchrnul (p1 + 1, ';');
7336             }
7337           else if (strprefix (p, p1, "replaylog"))
7338             {
7339               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7340               /* p1 will indicate "begin" or "end", but it makes
7341                  no difference for now, so ignore it.  */
7342               p = strchrnul (p1 + 1, ';');
7343             }
7344           else if (strprefix (p, p1, "core"))
7345             {
7346               ULONGEST c;
7347
7348               p = unpack_varlen_hex (++p1, &c);
7349               event->core = c;
7350             }
7351           else if (strprefix (p, p1, "fork"))
7352             {
7353               event->ws.value.related_pid = read_ptid (++p1, &p);
7354               event->ws.kind = TARGET_WAITKIND_FORKED;
7355             }
7356           else if (strprefix (p, p1, "vfork"))
7357             {
7358               event->ws.value.related_pid = read_ptid (++p1, &p);
7359               event->ws.kind = TARGET_WAITKIND_VFORKED;
7360             }
7361           else if (strprefix (p, p1, "vforkdone"))
7362             {
7363               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7364               p = strchrnul (p1 + 1, ';');
7365             }
7366           else if (strprefix (p, p1, "exec"))
7367             {
7368               ULONGEST ignored;
7369               char pathname[PATH_MAX];
7370               int pathlen;
7371
7372               /* Determine the length of the execd pathname.  */
7373               p = unpack_varlen_hex (++p1, &ignored);
7374               pathlen = (p - p1) / 2;
7375
7376               /* Save the pathname for event reporting and for
7377                  the next run command.  */
7378               hex2bin (p1, (gdb_byte *) pathname, pathlen);
7379               pathname[pathlen] = '\0';
7380
7381               /* This is freed during event handling.  */
7382               event->ws.value.execd_pathname = xstrdup (pathname);
7383               event->ws.kind = TARGET_WAITKIND_EXECD;
7384
7385               /* Skip the registers included in this packet, since
7386                  they may be for an architecture different from the
7387                  one used by the original program.  */
7388               skipregs = 1;
7389             }
7390           else if (strprefix (p, p1, "create"))
7391             {
7392               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7393               p = strchrnul (p1 + 1, ';');
7394             }
7395           else
7396             {
7397               ULONGEST pnum;
7398               const char *p_temp;
7399
7400               if (skipregs)
7401                 {
7402                   p = strchrnul (p1 + 1, ';');
7403                   p++;
7404                   continue;
7405                 }
7406
7407               /* Maybe a real ``P'' register number.  */
7408               p_temp = unpack_varlen_hex (p, &pnum);
7409               /* If the first invalid character is the colon, we got a
7410                  register number.  Otherwise, it's an unknown stop
7411                  reason.  */
7412               if (p_temp == p1)
7413                 {
7414                   /* If we haven't parsed the event's thread yet, find
7415                      it now, in order to find the architecture of the
7416                      reported expedited registers.  */
7417                   if (event->ptid == null_ptid)
7418                     {
7419                       const char *thr = strstr (p1 + 1, ";thread:");
7420                       if (thr != NULL)
7421                         event->ptid = read_ptid (thr + strlen (";thread:"),
7422                                                  NULL);
7423                       else
7424                         {
7425                           /* Either the current thread hasn't changed,
7426                              or the inferior is not multi-threaded.
7427                              The event must be for the thread we last
7428                              set as (or learned as being) current.  */
7429                           event->ptid = event->rs->general_thread;
7430                         }
7431                     }
7432
7433                   if (rsa == NULL)
7434                     {
7435                       inferior *inf = (event->ptid == null_ptid
7436                                        ? NULL
7437                                        : find_inferior_ptid (event->ptid));
7438                       /* If this is the first time we learn anything
7439                          about this process, skip the registers
7440                          included in this packet, since we don't yet
7441                          know which architecture to use to parse them.
7442                          We'll determine the architecture later when
7443                          we process the stop reply and retrieve the
7444                          target description, via
7445                          remote_notice_new_inferior ->
7446                          post_create_inferior.  */
7447                       if (inf == NULL)
7448                         {
7449                           p = strchrnul (p1 + 1, ';');
7450                           p++;
7451                           continue;
7452                         }
7453
7454                       event->arch = inf->gdbarch;
7455                       rsa = event->rs->get_remote_arch_state (event->arch);
7456                     }
7457
7458                   packet_reg *reg
7459                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7460                   cached_reg_t cached_reg;
7461
7462                   if (reg == NULL)
7463                     error (_("Remote sent bad register number %s: %s\n\
7464 Packet: '%s'\n"),
7465                            hex_string (pnum), p, buf);
7466
7467                   cached_reg.num = reg->regnum;
7468                   cached_reg.data = (gdb_byte *)
7469                     xmalloc (register_size (event->arch, reg->regnum));
7470
7471                   p = p1 + 1;
7472                   fieldsize = hex2bin (p, cached_reg.data,
7473                                        register_size (event->arch, reg->regnum));
7474                   p += 2 * fieldsize;
7475                   if (fieldsize < register_size (event->arch, reg->regnum))
7476                     warning (_("Remote reply is too short: %s"), buf);
7477
7478                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7479                 }
7480               else
7481                 {
7482                   /* Not a number.  Silently skip unknown optional
7483                      info.  */
7484                   p = strchrnul (p1 + 1, ';');
7485                 }
7486             }
7487
7488           if (*p != ';')
7489             error (_("Remote register badly formatted: %s\nhere: %s"),
7490                    buf, p);
7491           ++p;
7492         }
7493
7494       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7495         break;
7496
7497       /* fall through */
7498     case 'S':           /* Old style status, just signal only.  */
7499       {
7500         int sig;
7501
7502         event->ws.kind = TARGET_WAITKIND_STOPPED;
7503         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7504         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7505           event->ws.value.sig = (enum gdb_signal) sig;
7506         else
7507           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7508       }
7509       break;
7510     case 'w':           /* Thread exited.  */
7511       {
7512         const char *p;
7513         ULONGEST value;
7514
7515         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7516         p = unpack_varlen_hex (&buf[1], &value);
7517         event->ws.value.integer = value;
7518         if (*p != ';')
7519           error (_("stop reply packet badly formatted: %s"), buf);
7520         event->ptid = read_ptid (++p, NULL);
7521         break;
7522       }
7523     case 'W':           /* Target exited.  */
7524     case 'X':
7525       {
7526         const char *p;
7527         int pid;
7528         ULONGEST value;
7529
7530         /* GDB used to accept only 2 hex chars here.  Stubs should
7531            only send more if they detect GDB supports multi-process
7532            support.  */
7533         p = unpack_varlen_hex (&buf[1], &value);
7534
7535         if (buf[0] == 'W')
7536           {
7537             /* The remote process exited.  */
7538             event->ws.kind = TARGET_WAITKIND_EXITED;
7539             event->ws.value.integer = value;
7540           }
7541         else
7542           {
7543             /* The remote process exited with a signal.  */
7544             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7545             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7546               event->ws.value.sig = (enum gdb_signal) value;
7547             else
7548               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7549           }
7550
7551         /* If no process is specified, assume inferior_ptid.  */
7552         pid = inferior_ptid.pid ();
7553         if (*p == '\0')
7554           ;
7555         else if (*p == ';')
7556           {
7557             p++;
7558
7559             if (*p == '\0')
7560               ;
7561             else if (startswith (p, "process:"))
7562               {
7563                 ULONGEST upid;
7564
7565                 p += sizeof ("process:") - 1;
7566                 unpack_varlen_hex (p, &upid);
7567                 pid = upid;
7568               }
7569             else
7570               error (_("unknown stop reply packet: %s"), buf);
7571           }
7572         else
7573           error (_("unknown stop reply packet: %s"), buf);
7574         event->ptid = ptid_t (pid);
7575       }
7576       break;
7577     case 'N':
7578       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7579       event->ptid = minus_one_ptid;
7580       break;
7581     }
7582
7583   if (target_is_non_stop_p () && event->ptid == null_ptid)
7584     error (_("No process or thread specified in stop reply: %s"), buf);
7585 }
7586
7587 /* When the stub wants to tell GDB about a new notification reply, it
7588    sends a notification (%Stop, for example).  Those can come it at
7589    any time, hence, we have to make sure that any pending
7590    putpkt/getpkt sequence we're making is finished, before querying
7591    the stub for more events with the corresponding ack command
7592    (vStopped, for example).  E.g., if we started a vStopped sequence
7593    immediately upon receiving the notification, something like this
7594    could happen:
7595
7596     1.1) --> Hg 1
7597     1.2) <-- OK
7598     1.3) --> g
7599     1.4) <-- %Stop
7600     1.5) --> vStopped
7601     1.6) <-- (registers reply to step #1.3)
7602
7603    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7604    query.
7605
7606    To solve this, whenever we parse a %Stop notification successfully,
7607    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7608    doing whatever we were doing:
7609
7610     2.1) --> Hg 1
7611     2.2) <-- OK
7612     2.3) --> g
7613     2.4) <-- %Stop
7614       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7615     2.5) <-- (registers reply to step #2.3)
7616
7617    Eventualy after step #2.5, we return to the event loop, which
7618    notices there's an event on the
7619    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7620    associated callback --- the function below.  At this point, we're
7621    always safe to start a vStopped sequence. :
7622
7623     2.6) --> vStopped
7624     2.7) <-- T05 thread:2
7625     2.8) --> vStopped
7626     2.9) --> OK
7627 */
7628
7629 void
7630 remote_target::remote_notif_get_pending_events (notif_client *nc)
7631 {
7632   struct remote_state *rs = get_remote_state ();
7633
7634   if (rs->notif_state->pending_event[nc->id] != NULL)
7635     {
7636       if (notif_debug)
7637         fprintf_unfiltered (gdb_stdlog,
7638                             "notif: process: '%s' ack pending event\n",
7639                             nc->name);
7640
7641       /* acknowledge */
7642       nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7643       rs->notif_state->pending_event[nc->id] = NULL;
7644
7645       while (1)
7646         {
7647           getpkt (&rs->buf, &rs->buf_size, 0);
7648           if (strcmp (rs->buf, "OK") == 0)
7649             break;
7650           else
7651             remote_notif_ack (this, nc, rs->buf);
7652         }
7653     }
7654   else
7655     {
7656       if (notif_debug)
7657         fprintf_unfiltered (gdb_stdlog,
7658                             "notif: process: '%s' no pending reply\n",
7659                             nc->name);
7660     }
7661 }
7662
7663 /* Wrapper around remote_target::remote_notif_get_pending_events to
7664    avoid having to export the whole remote_target class.  */
7665
7666 void
7667 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7668 {
7669   remote->remote_notif_get_pending_events (nc);
7670 }
7671
7672 /* Called when it is decided that STOP_REPLY holds the info of the
7673    event that is to be returned to the core.  This function always
7674    destroys STOP_REPLY.  */
7675
7676 ptid_t
7677 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7678                                    struct target_waitstatus *status)
7679 {
7680   ptid_t ptid;
7681
7682   *status = stop_reply->ws;
7683   ptid = stop_reply->ptid;
7684
7685   /* If no thread/process was reported by the stub, assume the current
7686      inferior.  */
7687   if (ptid == null_ptid)
7688     ptid = inferior_ptid;
7689
7690   if (status->kind != TARGET_WAITKIND_EXITED
7691       && status->kind != TARGET_WAITKIND_SIGNALLED
7692       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7693     {
7694       /* Expedited registers.  */
7695       if (stop_reply->regcache)
7696         {
7697           struct regcache *regcache
7698             = get_thread_arch_regcache (ptid, stop_reply->arch);
7699           cached_reg_t *reg;
7700           int ix;
7701
7702           for (ix = 0;
7703                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7704                ix++)
7705           {
7706             regcache->raw_supply (reg->num, reg->data);
7707             xfree (reg->data);
7708           }
7709
7710           VEC_free (cached_reg_t, stop_reply->regcache);
7711         }
7712
7713       remote_notice_new_inferior (ptid, 0);
7714       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7715       remote_thr->core = stop_reply->core;
7716       remote_thr->stop_reason = stop_reply->stop_reason;
7717       remote_thr->watch_data_address = stop_reply->watch_data_address;
7718       remote_thr->vcont_resumed = 0;
7719     }
7720
7721   stop_reply_xfree (stop_reply);
7722   return ptid;
7723 }
7724
7725 /* The non-stop mode version of target_wait.  */
7726
7727 ptid_t
7728 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7729 {
7730   struct remote_state *rs = get_remote_state ();
7731   struct stop_reply *stop_reply;
7732   int ret;
7733   int is_notif = 0;
7734
7735   /* If in non-stop mode, get out of getpkt even if a
7736      notification is received.  */
7737
7738   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7739                               0 /* forever */, &is_notif);
7740   while (1)
7741     {
7742       if (ret != -1 && !is_notif)
7743         switch (rs->buf[0])
7744           {
7745           case 'E':             /* Error of some sort.  */
7746             /* We're out of sync with the target now.  Did it continue
7747                or not?  We can't tell which thread it was in non-stop,
7748                so just ignore this.  */
7749             warning (_("Remote failure reply: %s"), rs->buf);
7750             break;
7751           case 'O':             /* Console output.  */
7752             remote_console_output (rs->buf + 1);
7753             break;
7754           default:
7755             warning (_("Invalid remote reply: %s"), rs->buf);
7756             break;
7757           }
7758
7759       /* Acknowledge a pending stop reply that may have arrived in the
7760          mean time.  */
7761       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7762         remote_notif_get_pending_events (&notif_client_stop);
7763
7764       /* If indeed we noticed a stop reply, we're done.  */
7765       stop_reply = queued_stop_reply (ptid);
7766       if (stop_reply != NULL)
7767         return process_stop_reply (stop_reply, status);
7768
7769       /* Still no event.  If we're just polling for an event, then
7770          return to the event loop.  */
7771       if (options & TARGET_WNOHANG)
7772         {
7773           status->kind = TARGET_WAITKIND_IGNORE;
7774           return minus_one_ptid;
7775         }
7776
7777       /* Otherwise do a blocking wait.  */
7778       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7779                                   1 /* forever */, &is_notif);
7780     }
7781 }
7782
7783 /* Wait until the remote machine stops, then return, storing status in
7784    STATUS just as `wait' would.  */
7785
7786 ptid_t
7787 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7788 {
7789   struct remote_state *rs = get_remote_state ();
7790   ptid_t event_ptid = null_ptid;
7791   char *buf;
7792   struct stop_reply *stop_reply;
7793
7794  again:
7795
7796   status->kind = TARGET_WAITKIND_IGNORE;
7797   status->value.integer = 0;
7798
7799   stop_reply = queued_stop_reply (ptid);
7800   if (stop_reply != NULL)
7801     return process_stop_reply (stop_reply, status);
7802
7803   if (rs->cached_wait_status)
7804     /* Use the cached wait status, but only once.  */
7805     rs->cached_wait_status = 0;
7806   else
7807     {
7808       int ret;
7809       int is_notif;
7810       int forever = ((options & TARGET_WNOHANG) == 0
7811                      && rs->wait_forever_enabled_p);
7812
7813       if (!rs->waiting_for_stop_reply)
7814         {
7815           status->kind = TARGET_WAITKIND_NO_RESUMED;
7816           return minus_one_ptid;
7817         }
7818
7819       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7820          _never_ wait for ever -> test on target_is_async_p().
7821          However, before we do that we need to ensure that the caller
7822          knows how to take the target into/out of async mode.  */
7823       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7824                                   forever, &is_notif);
7825
7826       /* GDB gets a notification.  Return to core as this event is
7827          not interesting.  */
7828       if (ret != -1 && is_notif)
7829         return minus_one_ptid;
7830
7831       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7832         return minus_one_ptid;
7833     }
7834
7835   buf = rs->buf;
7836
7837   /* Assume that the target has acknowledged Ctrl-C unless we receive
7838      an 'F' or 'O' packet.  */
7839   if (buf[0] != 'F' && buf[0] != 'O')
7840     rs->ctrlc_pending_p = 0;
7841
7842   switch (buf[0])
7843     {
7844     case 'E':           /* Error of some sort.  */
7845       /* We're out of sync with the target now.  Did it continue or
7846          not?  Not is more likely, so report a stop.  */
7847       rs->waiting_for_stop_reply = 0;
7848
7849       warning (_("Remote failure reply: %s"), buf);
7850       status->kind = TARGET_WAITKIND_STOPPED;
7851       status->value.sig = GDB_SIGNAL_0;
7852       break;
7853     case 'F':           /* File-I/O request.  */
7854       /* GDB may access the inferior memory while handling the File-I/O
7855          request, but we don't want GDB accessing memory while waiting
7856          for a stop reply.  See the comments in putpkt_binary.  Set
7857          waiting_for_stop_reply to 0 temporarily.  */
7858       rs->waiting_for_stop_reply = 0;
7859       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7860       rs->ctrlc_pending_p = 0;
7861       /* GDB handled the File-I/O request, and the target is running
7862          again.  Keep waiting for events.  */
7863       rs->waiting_for_stop_reply = 1;
7864       break;
7865     case 'N': case 'T': case 'S': case 'X': case 'W':
7866       {
7867         struct stop_reply *stop_reply;
7868
7869         /* There is a stop reply to handle.  */
7870         rs->waiting_for_stop_reply = 0;
7871
7872         stop_reply
7873           = (struct stop_reply *) remote_notif_parse (this,
7874                                                       &notif_client_stop,
7875                                                       rs->buf);
7876
7877         event_ptid = process_stop_reply (stop_reply, status);
7878         break;
7879       }
7880     case 'O':           /* Console output.  */
7881       remote_console_output (buf + 1);
7882       break;
7883     case '\0':
7884       if (rs->last_sent_signal != GDB_SIGNAL_0)
7885         {
7886           /* Zero length reply means that we tried 'S' or 'C' and the
7887              remote system doesn't support it.  */
7888           target_terminal::ours_for_output ();
7889           printf_filtered
7890             ("Can't send signals to this remote system.  %s not sent.\n",
7891              gdb_signal_to_name (rs->last_sent_signal));
7892           rs->last_sent_signal = GDB_SIGNAL_0;
7893           target_terminal::inferior ();
7894
7895           strcpy (buf, rs->last_sent_step ? "s" : "c");
7896           putpkt (buf);
7897           break;
7898         }
7899       /* fallthrough */
7900     default:
7901       warning (_("Invalid remote reply: %s"), buf);
7902       break;
7903     }
7904
7905   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7906     return minus_one_ptid;
7907   else if (status->kind == TARGET_WAITKIND_IGNORE)
7908     {
7909       /* Nothing interesting happened.  If we're doing a non-blocking
7910          poll, we're done.  Otherwise, go back to waiting.  */
7911       if (options & TARGET_WNOHANG)
7912         return minus_one_ptid;
7913       else
7914         goto again;
7915     }
7916   else if (status->kind != TARGET_WAITKIND_EXITED
7917            && status->kind != TARGET_WAITKIND_SIGNALLED)
7918     {
7919       if (event_ptid != null_ptid)
7920         record_currthread (rs, event_ptid);
7921       else
7922         event_ptid = inferior_ptid;
7923     }
7924   else
7925     /* A process exit.  Invalidate our notion of current thread.  */
7926     record_currthread (rs, minus_one_ptid);
7927
7928   return event_ptid;
7929 }
7930
7931 /* Wait until the remote machine stops, then return, storing status in
7932    STATUS just as `wait' would.  */
7933
7934 ptid_t
7935 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7936 {
7937   ptid_t event_ptid;
7938
7939   if (target_is_non_stop_p ())
7940     event_ptid = wait_ns (ptid, status, options);
7941   else
7942     event_ptid = wait_as (ptid, status, options);
7943
7944   if (target_is_async_p ())
7945     {
7946       remote_state *rs = get_remote_state ();
7947
7948       /* If there are are events left in the queue tell the event loop
7949          to return here.  */
7950       if (!rs->stop_reply_queue.empty ())
7951         mark_async_event_handler (rs->remote_async_inferior_event_token);
7952     }
7953
7954   return event_ptid;
7955 }
7956
7957 /* Fetch a single register using a 'p' packet.  */
7958
7959 int
7960 remote_target::fetch_register_using_p (struct regcache *regcache,
7961                                        packet_reg *reg)
7962 {
7963   struct gdbarch *gdbarch = regcache->arch ();
7964   struct remote_state *rs = get_remote_state ();
7965   char *buf, *p;
7966   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7967   int i;
7968
7969   if (packet_support (PACKET_p) == PACKET_DISABLE)
7970     return 0;
7971
7972   if (reg->pnum == -1)
7973     return 0;
7974
7975   p = rs->buf;
7976   *p++ = 'p';
7977   p += hexnumstr (p, reg->pnum);
7978   *p++ = '\0';
7979   putpkt (rs->buf);
7980   getpkt (&rs->buf, &rs->buf_size, 0);
7981
7982   buf = rs->buf;
7983
7984   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
7985     {
7986     case PACKET_OK:
7987       break;
7988     case PACKET_UNKNOWN:
7989       return 0;
7990     case PACKET_ERROR:
7991       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7992              gdbarch_register_name (regcache->arch (), 
7993                                     reg->regnum), 
7994              buf);
7995     }
7996
7997   /* If this register is unfetchable, tell the regcache.  */
7998   if (buf[0] == 'x')
7999     {
8000       regcache->raw_supply (reg->regnum, NULL);
8001       return 1;
8002     }
8003
8004   /* Otherwise, parse and supply the value.  */
8005   p = buf;
8006   i = 0;
8007   while (p[0] != 0)
8008     {
8009       if (p[1] == 0)
8010         error (_("fetch_register_using_p: early buf termination"));
8011
8012       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8013       p += 2;
8014     }
8015   regcache->raw_supply (reg->regnum, regp);
8016   return 1;
8017 }
8018
8019 /* Fetch the registers included in the target's 'g' packet.  */
8020
8021 int
8022 remote_target::send_g_packet ()
8023 {
8024   struct remote_state *rs = get_remote_state ();
8025   int buf_len;
8026
8027   xsnprintf (rs->buf, get_remote_packet_size (), "g");
8028   putpkt (rs->buf);
8029   getpkt (&rs->buf, &rs->buf_size, 0);
8030   if (packet_check_result (rs->buf) == PACKET_ERROR)
8031     error (_("Could not read registers; remote failure reply '%s'"),
8032            rs->buf);
8033
8034   /* We can get out of synch in various cases.  If the first character
8035      in the buffer is not a hex character, assume that has happened
8036      and try to fetch another packet to read.  */
8037   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8038          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8039          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8040          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
8041     {
8042       if (remote_debug)
8043         fprintf_unfiltered (gdb_stdlog,
8044                             "Bad register packet; fetching a new packet\n");
8045       getpkt (&rs->buf, &rs->buf_size, 0);
8046     }
8047
8048   buf_len = strlen (rs->buf);
8049
8050   /* Sanity check the received packet.  */
8051   if (buf_len % 2 != 0)
8052     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8053
8054   return buf_len / 2;
8055 }
8056
8057 void
8058 remote_target::process_g_packet (struct regcache *regcache)
8059 {
8060   struct gdbarch *gdbarch = regcache->arch ();
8061   struct remote_state *rs = get_remote_state ();
8062   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8063   int i, buf_len;
8064   char *p;
8065   char *regs;
8066
8067   buf_len = strlen (rs->buf);
8068
8069   /* Further sanity checks, with knowledge of the architecture.  */
8070   if (buf_len > 2 * rsa->sizeof_g_packet)
8071     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8072              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8073
8074   /* Save the size of the packet sent to us by the target.  It is used
8075      as a heuristic when determining the max size of packets that the
8076      target can safely receive.  */
8077   if (rsa->actual_register_packet_size == 0)
8078     rsa->actual_register_packet_size = buf_len;
8079
8080   /* If this is smaller than we guessed the 'g' packet would be,
8081      update our records.  A 'g' reply that doesn't include a register's
8082      value implies either that the register is not available, or that
8083      the 'p' packet must be used.  */
8084   if (buf_len < 2 * rsa->sizeof_g_packet)
8085     {
8086       long sizeof_g_packet = buf_len / 2;
8087
8088       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8089         {
8090           long offset = rsa->regs[i].offset;
8091           long reg_size = register_size (gdbarch, i);
8092
8093           if (rsa->regs[i].pnum == -1)
8094             continue;
8095
8096           if (offset >= sizeof_g_packet)
8097             rsa->regs[i].in_g_packet = 0;
8098           else if (offset + reg_size > sizeof_g_packet)
8099             error (_("Truncated register %d in remote 'g' packet"), i);
8100           else
8101             rsa->regs[i].in_g_packet = 1;
8102         }
8103
8104       /* Looks valid enough, we can assume this is the correct length
8105          for a 'g' packet.  It's important not to adjust
8106          rsa->sizeof_g_packet if we have truncated registers otherwise
8107          this "if" won't be run the next time the method is called
8108          with a packet of the same size and one of the internal errors
8109          below will trigger instead.  */
8110       rsa->sizeof_g_packet = sizeof_g_packet;
8111     }
8112
8113   regs = (char *) alloca (rsa->sizeof_g_packet);
8114
8115   /* Unimplemented registers read as all bits zero.  */
8116   memset (regs, 0, rsa->sizeof_g_packet);
8117
8118   /* Reply describes registers byte by byte, each byte encoded as two
8119      hex characters.  Suck them all up, then supply them to the
8120      register cacheing/storage mechanism.  */
8121
8122   p = rs->buf;
8123   for (i = 0; i < rsa->sizeof_g_packet; i++)
8124     {
8125       if (p[0] == 0 || p[1] == 0)
8126         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
8127         internal_error (__FILE__, __LINE__,
8128                         _("unexpected end of 'g' packet reply"));
8129
8130       if (p[0] == 'x' && p[1] == 'x')
8131         regs[i] = 0;            /* 'x' */
8132       else
8133         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8134       p += 2;
8135     }
8136
8137   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8138     {
8139       struct packet_reg *r = &rsa->regs[i];
8140       long reg_size = register_size (gdbarch, i);
8141
8142       if (r->in_g_packet)
8143         {
8144           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8145             /* This shouldn't happen - we adjusted in_g_packet above.  */
8146             internal_error (__FILE__, __LINE__,
8147                             _("unexpected end of 'g' packet reply"));
8148           else if (rs->buf[r->offset * 2] == 'x')
8149             {
8150               gdb_assert (r->offset * 2 < strlen (rs->buf));
8151               /* The register isn't available, mark it as such (at
8152                  the same time setting the value to zero).  */
8153               regcache->raw_supply (r->regnum, NULL);
8154             }
8155           else
8156             regcache->raw_supply (r->regnum, regs + r->offset);
8157         }
8158     }
8159 }
8160
8161 void
8162 remote_target::fetch_registers_using_g (struct regcache *regcache)
8163 {
8164   send_g_packet ();
8165   process_g_packet (regcache);
8166 }
8167
8168 /* Make the remote selected traceframe match GDB's selected
8169    traceframe.  */
8170
8171 void
8172 remote_target::set_remote_traceframe ()
8173 {
8174   int newnum;
8175   struct remote_state *rs = get_remote_state ();
8176
8177   if (rs->remote_traceframe_number == get_traceframe_number ())
8178     return;
8179
8180   /* Avoid recursion, remote_trace_find calls us again.  */
8181   rs->remote_traceframe_number = get_traceframe_number ();
8182
8183   newnum = target_trace_find (tfind_number,
8184                               get_traceframe_number (), 0, 0, NULL);
8185
8186   /* Should not happen.  If it does, all bets are off.  */
8187   if (newnum != get_traceframe_number ())
8188     warning (_("could not set remote traceframe"));
8189 }
8190
8191 void
8192 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8193 {
8194   struct gdbarch *gdbarch = regcache->arch ();
8195   struct remote_state *rs = get_remote_state ();
8196   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8197   int i;
8198
8199   set_remote_traceframe ();
8200   set_general_thread (regcache->ptid ());
8201
8202   if (regnum >= 0)
8203     {
8204       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8205
8206       gdb_assert (reg != NULL);
8207
8208       /* If this register might be in the 'g' packet, try that first -
8209          we are likely to read more than one register.  If this is the
8210          first 'g' packet, we might be overly optimistic about its
8211          contents, so fall back to 'p'.  */
8212       if (reg->in_g_packet)
8213         {
8214           fetch_registers_using_g (regcache);
8215           if (reg->in_g_packet)
8216             return;
8217         }
8218
8219       if (fetch_register_using_p (regcache, reg))
8220         return;
8221
8222       /* This register is not available.  */
8223       regcache->raw_supply (reg->regnum, NULL);
8224
8225       return;
8226     }
8227
8228   fetch_registers_using_g (regcache);
8229
8230   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8231     if (!rsa->regs[i].in_g_packet)
8232       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8233         {
8234           /* This register is not available.  */
8235           regcache->raw_supply (i, NULL);
8236         }
8237 }
8238
8239 /* Prepare to store registers.  Since we may send them all (using a
8240    'G' request), we have to read out the ones we don't want to change
8241    first.  */
8242
8243 void
8244 remote_target::prepare_to_store (struct regcache *regcache)
8245 {
8246   struct remote_state *rs = get_remote_state ();
8247   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8248   int i;
8249
8250   /* Make sure the entire registers array is valid.  */
8251   switch (packet_support (PACKET_P))
8252     {
8253     case PACKET_DISABLE:
8254     case PACKET_SUPPORT_UNKNOWN:
8255       /* Make sure all the necessary registers are cached.  */
8256       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8257         if (rsa->regs[i].in_g_packet)
8258           regcache->raw_update (rsa->regs[i].regnum);
8259       break;
8260     case PACKET_ENABLE:
8261       break;
8262     }
8263 }
8264
8265 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8266    packet was not recognized.  */
8267
8268 int
8269 remote_target::store_register_using_P (const struct regcache *regcache,
8270                                        packet_reg *reg)
8271 {
8272   struct gdbarch *gdbarch = regcache->arch ();
8273   struct remote_state *rs = get_remote_state ();
8274   /* Try storing a single register.  */
8275   char *buf = rs->buf;
8276   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8277   char *p;
8278
8279   if (packet_support (PACKET_P) == PACKET_DISABLE)
8280     return 0;
8281
8282   if (reg->pnum == -1)
8283     return 0;
8284
8285   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8286   p = buf + strlen (buf);
8287   regcache->raw_collect (reg->regnum, regp);
8288   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8289   putpkt (rs->buf);
8290   getpkt (&rs->buf, &rs->buf_size, 0);
8291
8292   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8293     {
8294     case PACKET_OK:
8295       return 1;
8296     case PACKET_ERROR:
8297       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8298              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8299     case PACKET_UNKNOWN:
8300       return 0;
8301     default:
8302       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8303     }
8304 }
8305
8306 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8307    contents of the register cache buffer.  FIXME: ignores errors.  */
8308
8309 void
8310 remote_target::store_registers_using_G (const struct regcache *regcache)
8311 {
8312   struct remote_state *rs = get_remote_state ();
8313   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8314   gdb_byte *regs;
8315   char *p;
8316
8317   /* Extract all the registers in the regcache copying them into a
8318      local buffer.  */
8319   {
8320     int i;
8321
8322     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8323     memset (regs, 0, rsa->sizeof_g_packet);
8324     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8325       {
8326         struct packet_reg *r = &rsa->regs[i];
8327
8328         if (r->in_g_packet)
8329           regcache->raw_collect (r->regnum, regs + r->offset);
8330       }
8331   }
8332
8333   /* Command describes registers byte by byte,
8334      each byte encoded as two hex characters.  */
8335   p = rs->buf;
8336   *p++ = 'G';
8337   bin2hex (regs, p, rsa->sizeof_g_packet);
8338   putpkt (rs->buf);
8339   getpkt (&rs->buf, &rs->buf_size, 0);
8340   if (packet_check_result (rs->buf) == PACKET_ERROR)
8341     error (_("Could not write registers; remote failure reply '%s'"), 
8342            rs->buf);
8343 }
8344
8345 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8346    of the register cache buffer.  FIXME: ignores errors.  */
8347
8348 void
8349 remote_target::store_registers (struct regcache *regcache, int regnum)
8350 {
8351   struct gdbarch *gdbarch = regcache->arch ();
8352   struct remote_state *rs = get_remote_state ();
8353   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8354   int i;
8355
8356   set_remote_traceframe ();
8357   set_general_thread (regcache->ptid ());
8358
8359   if (regnum >= 0)
8360     {
8361       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8362
8363       gdb_assert (reg != NULL);
8364
8365       /* Always prefer to store registers using the 'P' packet if
8366          possible; we often change only a small number of registers.
8367          Sometimes we change a larger number; we'd need help from a
8368          higher layer to know to use 'G'.  */
8369       if (store_register_using_P (regcache, reg))
8370         return;
8371
8372       /* For now, don't complain if we have no way to write the
8373          register.  GDB loses track of unavailable registers too
8374          easily.  Some day, this may be an error.  We don't have
8375          any way to read the register, either...  */
8376       if (!reg->in_g_packet)
8377         return;
8378
8379       store_registers_using_G (regcache);
8380       return;
8381     }
8382
8383   store_registers_using_G (regcache);
8384
8385   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8386     if (!rsa->regs[i].in_g_packet)
8387       if (!store_register_using_P (regcache, &rsa->regs[i]))
8388         /* See above for why we do not issue an error here.  */
8389         continue;
8390 }
8391 \f
8392
8393 /* Return the number of hex digits in num.  */
8394
8395 static int
8396 hexnumlen (ULONGEST num)
8397 {
8398   int i;
8399
8400   for (i = 0; num != 0; i++)
8401     num >>= 4;
8402
8403   return std::max (i, 1);
8404 }
8405
8406 /* Set BUF to the minimum number of hex digits representing NUM.  */
8407
8408 static int
8409 hexnumstr (char *buf, ULONGEST num)
8410 {
8411   int len = hexnumlen (num);
8412
8413   return hexnumnstr (buf, num, len);
8414 }
8415
8416
8417 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8418
8419 static int
8420 hexnumnstr (char *buf, ULONGEST num, int width)
8421 {
8422   int i;
8423
8424   buf[width] = '\0';
8425
8426   for (i = width - 1; i >= 0; i--)
8427     {
8428       buf[i] = "0123456789abcdef"[(num & 0xf)];
8429       num >>= 4;
8430     }
8431
8432   return width;
8433 }
8434
8435 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8436
8437 static CORE_ADDR
8438 remote_address_masked (CORE_ADDR addr)
8439 {
8440   unsigned int address_size = remote_address_size;
8441
8442   /* If "remoteaddresssize" was not set, default to target address size.  */
8443   if (!address_size)
8444     address_size = gdbarch_addr_bit (target_gdbarch ());
8445
8446   if (address_size > 0
8447       && address_size < (sizeof (ULONGEST) * 8))
8448     {
8449       /* Only create a mask when that mask can safely be constructed
8450          in a ULONGEST variable.  */
8451       ULONGEST mask = 1;
8452
8453       mask = (mask << address_size) - 1;
8454       addr &= mask;
8455     }
8456   return addr;
8457 }
8458
8459 /* Determine whether the remote target supports binary downloading.
8460    This is accomplished by sending a no-op memory write of zero length
8461    to the target at the specified address. It does not suffice to send
8462    the whole packet, since many stubs strip the eighth bit and
8463    subsequently compute a wrong checksum, which causes real havoc with
8464    remote_write_bytes.
8465
8466    NOTE: This can still lose if the serial line is not eight-bit
8467    clean.  In cases like this, the user should clear "remote
8468    X-packet".  */
8469
8470 void
8471 remote_target::check_binary_download (CORE_ADDR addr)
8472 {
8473   struct remote_state *rs = get_remote_state ();
8474
8475   switch (packet_support (PACKET_X))
8476     {
8477     case PACKET_DISABLE:
8478       break;
8479     case PACKET_ENABLE:
8480       break;
8481     case PACKET_SUPPORT_UNKNOWN:
8482       {
8483         char *p;
8484
8485         p = rs->buf;
8486         *p++ = 'X';
8487         p += hexnumstr (p, (ULONGEST) addr);
8488         *p++ = ',';
8489         p += hexnumstr (p, (ULONGEST) 0);
8490         *p++ = ':';
8491         *p = '\0';
8492
8493         putpkt_binary (rs->buf, (int) (p - rs->buf));
8494         getpkt (&rs->buf, &rs->buf_size, 0);
8495
8496         if (rs->buf[0] == '\0')
8497           {
8498             if (remote_debug)
8499               fprintf_unfiltered (gdb_stdlog,
8500                                   "binary downloading NOT "
8501                                   "supported by target\n");
8502             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8503           }
8504         else
8505           {
8506             if (remote_debug)
8507               fprintf_unfiltered (gdb_stdlog,
8508                                   "binary downloading supported by target\n");
8509             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8510           }
8511         break;
8512       }
8513     }
8514 }
8515
8516 /* Helper function to resize the payload in order to try to get a good
8517    alignment.  We try to write an amount of data such that the next write will
8518    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8519
8520 static int
8521 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8522 {
8523   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8524 }
8525
8526 /* Write memory data directly to the remote machine.
8527    This does not inform the data cache; the data cache uses this.
8528    HEADER is the starting part of the packet.
8529    MEMADDR is the address in the remote memory space.
8530    MYADDR is the address of the buffer in our space.
8531    LEN_UNITS is the number of addressable units to write.
8532    UNIT_SIZE is the length in bytes of an addressable unit.
8533    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8534    should send data as binary ('X'), or hex-encoded ('M').
8535
8536    The function creates packet of the form
8537        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8538
8539    where encoding of <DATA> is terminated by PACKET_FORMAT.
8540
8541    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8542    are omitted.
8543
8544    Return the transferred status, error or OK (an
8545    'enum target_xfer_status' value).  Save the number of addressable units
8546    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8547
8548    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8549    exchange between gdb and the stub could look like (?? in place of the
8550    checksum):
8551
8552    -> $m1000,4#??
8553    <- aaaabbbbccccdddd
8554
8555    -> $M1000,3:eeeeffffeeee#??
8556    <- OK
8557
8558    -> $m1000,4#??
8559    <- eeeeffffeeeedddd  */
8560
8561 target_xfer_status
8562 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8563                                        const gdb_byte *myaddr,
8564                                        ULONGEST len_units,
8565                                        int unit_size,
8566                                        ULONGEST *xfered_len_units,
8567                                        char packet_format, int use_length)
8568 {
8569   struct remote_state *rs = get_remote_state ();
8570   char *p;
8571   char *plen = NULL;
8572   int plenlen = 0;
8573   int todo_units;
8574   int units_written;
8575   int payload_capacity_bytes;
8576   int payload_length_bytes;
8577
8578   if (packet_format != 'X' && packet_format != 'M')
8579     internal_error (__FILE__, __LINE__,
8580                     _("remote_write_bytes_aux: bad packet format"));
8581
8582   if (len_units == 0)
8583     return TARGET_XFER_EOF;
8584
8585   payload_capacity_bytes = get_memory_write_packet_size ();
8586
8587   /* The packet buffer will be large enough for the payload;
8588      get_memory_packet_size ensures this.  */
8589   rs->buf[0] = '\0';
8590
8591   /* Compute the size of the actual payload by subtracting out the
8592      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8593
8594   payload_capacity_bytes -= strlen ("$,:#NN");
8595   if (!use_length)
8596     /* The comma won't be used.  */
8597     payload_capacity_bytes += 1;
8598   payload_capacity_bytes -= strlen (header);
8599   payload_capacity_bytes -= hexnumlen (memaddr);
8600
8601   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8602
8603   strcat (rs->buf, header);
8604   p = rs->buf + strlen (header);
8605
8606   /* Compute a best guess of the number of bytes actually transfered.  */
8607   if (packet_format == 'X')
8608     {
8609       /* Best guess at number of bytes that will fit.  */
8610       todo_units = std::min (len_units,
8611                              (ULONGEST) payload_capacity_bytes / unit_size);
8612       if (use_length)
8613         payload_capacity_bytes -= hexnumlen (todo_units);
8614       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8615     }
8616   else
8617     {
8618       /* Number of bytes that will fit.  */
8619       todo_units
8620         = std::min (len_units,
8621                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8622       if (use_length)
8623         payload_capacity_bytes -= hexnumlen (todo_units);
8624       todo_units = std::min (todo_units,
8625                              (payload_capacity_bytes / unit_size) / 2);
8626     }
8627
8628   if (todo_units <= 0)
8629     internal_error (__FILE__, __LINE__,
8630                     _("minimum packet size too small to write data"));
8631
8632   /* If we already need another packet, then try to align the end
8633      of this packet to a useful boundary.  */
8634   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8635     todo_units = align_for_efficient_write (todo_units, memaddr);
8636
8637   /* Append "<memaddr>".  */
8638   memaddr = remote_address_masked (memaddr);
8639   p += hexnumstr (p, (ULONGEST) memaddr);
8640
8641   if (use_length)
8642     {
8643       /* Append ",".  */
8644       *p++ = ',';
8645
8646       /* Append the length and retain its location and size.  It may need to be
8647          adjusted once the packet body has been created.  */
8648       plen = p;
8649       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8650       p += plenlen;
8651     }
8652
8653   /* Append ":".  */
8654   *p++ = ':';
8655   *p = '\0';
8656
8657   /* Append the packet body.  */
8658   if (packet_format == 'X')
8659     {
8660       /* Binary mode.  Send target system values byte by byte, in
8661          increasing byte addresses.  Only escape certain critical
8662          characters.  */
8663       payload_length_bytes =
8664           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8665                                 &units_written, payload_capacity_bytes);
8666
8667       /* If not all TODO units fit, then we'll need another packet.  Make
8668          a second try to keep the end of the packet aligned.  Don't do
8669          this if the packet is tiny.  */
8670       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8671         {
8672           int new_todo_units;
8673
8674           new_todo_units = align_for_efficient_write (units_written, memaddr);
8675
8676           if (new_todo_units != units_written)
8677             payload_length_bytes =
8678                 remote_escape_output (myaddr, new_todo_units, unit_size,
8679                                       (gdb_byte *) p, &units_written,
8680                                       payload_capacity_bytes);
8681         }
8682
8683       p += payload_length_bytes;
8684       if (use_length && units_written < todo_units)
8685         {
8686           /* Escape chars have filled up the buffer prematurely,
8687              and we have actually sent fewer units than planned.
8688              Fix-up the length field of the packet.  Use the same
8689              number of characters as before.  */
8690           plen += hexnumnstr (plen, (ULONGEST) units_written,
8691                               plenlen);
8692           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8693         }
8694     }
8695   else
8696     {
8697       /* Normal mode: Send target system values byte by byte, in
8698          increasing byte addresses.  Each byte is encoded as a two hex
8699          value.  */
8700       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8701       units_written = todo_units;
8702     }
8703
8704   putpkt_binary (rs->buf, (int) (p - rs->buf));
8705   getpkt (&rs->buf, &rs->buf_size, 0);
8706
8707   if (rs->buf[0] == 'E')
8708     return TARGET_XFER_E_IO;
8709
8710   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8711      send fewer units than we'd planned.  */
8712   *xfered_len_units = (ULONGEST) units_written;
8713   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8714 }
8715
8716 /* Write memory data directly to the remote machine.
8717    This does not inform the data cache; the data cache uses this.
8718    MEMADDR is the address in the remote memory space.
8719    MYADDR is the address of the buffer in our space.
8720    LEN is the number of bytes.
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.  Only transfer a single packet.  */
8725
8726 target_xfer_status
8727 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8728                                    ULONGEST len, int unit_size,
8729                                    ULONGEST *xfered_len)
8730 {
8731   const char *packet_format = NULL;
8732
8733   /* Check whether the target supports binary download.  */
8734   check_binary_download (memaddr);
8735
8736   switch (packet_support (PACKET_X))
8737     {
8738     case PACKET_ENABLE:
8739       packet_format = "X";
8740       break;
8741     case PACKET_DISABLE:
8742       packet_format = "M";
8743       break;
8744     case PACKET_SUPPORT_UNKNOWN:
8745       internal_error (__FILE__, __LINE__,
8746                       _("remote_write_bytes: bad internal state"));
8747     default:
8748       internal_error (__FILE__, __LINE__, _("bad switch"));
8749     }
8750
8751   return remote_write_bytes_aux (packet_format,
8752                                  memaddr, myaddr, len, unit_size, xfered_len,
8753                                  packet_format[0], 1);
8754 }
8755
8756 /* Read memory data directly from the remote machine.
8757    This does not use the data cache; the data cache uses this.
8758    MEMADDR is the address in the remote memory space.
8759    MYADDR is the address of the buffer in our space.
8760    LEN_UNITS is the number of addressable memory units to read..
8761    UNIT_SIZE is the length in bytes of an addressable unit.
8762
8763    Return the transferred status, error or OK (an
8764    'enum target_xfer_status' value).  Save the number of bytes
8765    transferred in *XFERED_LEN_UNITS.
8766
8767    See the comment of remote_write_bytes_aux for an example of
8768    memory read/write exchange between gdb and the stub.  */
8769
8770 target_xfer_status
8771 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8772                                     ULONGEST len_units,
8773                                     int unit_size, ULONGEST *xfered_len_units)
8774 {
8775   struct remote_state *rs = get_remote_state ();
8776   int buf_size_bytes;           /* Max size of packet output buffer.  */
8777   char *p;
8778   int todo_units;
8779   int decoded_bytes;
8780
8781   buf_size_bytes = get_memory_read_packet_size ();
8782   /* The packet buffer will be large enough for the payload;
8783      get_memory_packet_size ensures this.  */
8784
8785   /* Number of units that will fit.  */
8786   todo_units = std::min (len_units,
8787                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8788
8789   /* Construct "m"<memaddr>","<len>".  */
8790   memaddr = remote_address_masked (memaddr);
8791   p = rs->buf;
8792   *p++ = 'm';
8793   p += hexnumstr (p, (ULONGEST) memaddr);
8794   *p++ = ',';
8795   p += hexnumstr (p, (ULONGEST) todo_units);
8796   *p = '\0';
8797   putpkt (rs->buf);
8798   getpkt (&rs->buf, &rs->buf_size, 0);
8799   if (rs->buf[0] == 'E'
8800       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8801       && rs->buf[3] == '\0')
8802     return TARGET_XFER_E_IO;
8803   /* Reply describes memory byte by byte, each byte encoded as two hex
8804      characters.  */
8805   p = rs->buf;
8806   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8807   /* Return what we have.  Let higher layers handle partial reads.  */
8808   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8809   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8810 }
8811
8812 /* Using the set of read-only target sections of remote, read live
8813    read-only memory.
8814
8815    For interface/parameters/return description see target.h,
8816    to_xfer_partial.  */
8817
8818 target_xfer_status
8819 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8820                                                   ULONGEST memaddr,
8821                                                   ULONGEST len,
8822                                                   int unit_size,
8823                                                   ULONGEST *xfered_len)
8824 {
8825   struct target_section *secp;
8826   struct target_section_table *table;
8827
8828   secp = target_section_by_addr (this, memaddr);
8829   if (secp != NULL
8830       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8831                                  secp->the_bfd_section)
8832           & SEC_READONLY))
8833     {
8834       struct target_section *p;
8835       ULONGEST memend = memaddr + len;
8836
8837       table = target_get_section_table (this);
8838
8839       for (p = table->sections; p < table->sections_end; p++)
8840         {
8841           if (memaddr >= p->addr)
8842             {
8843               if (memend <= p->endaddr)
8844                 {
8845                   /* Entire transfer is within this section.  */
8846                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8847                                               xfered_len);
8848                 }
8849               else if (memaddr >= p->endaddr)
8850                 {
8851                   /* This section ends before the transfer starts.  */
8852                   continue;
8853                 }
8854               else
8855                 {
8856                   /* This section overlaps the transfer.  Just do half.  */
8857                   len = p->endaddr - memaddr;
8858                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8859                                               xfered_len);
8860                 }
8861             }
8862         }
8863     }
8864
8865   return TARGET_XFER_EOF;
8866 }
8867
8868 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8869    first if the requested memory is unavailable in traceframe.
8870    Otherwise, fall back to remote_read_bytes_1.  */
8871
8872 target_xfer_status
8873 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8874                                   gdb_byte *myaddr, ULONGEST len, int unit_size,
8875                                   ULONGEST *xfered_len)
8876 {
8877   if (len == 0)
8878     return TARGET_XFER_EOF;
8879
8880   if (get_traceframe_number () != -1)
8881     {
8882       std::vector<mem_range> available;
8883
8884       /* If we fail to get the set of available memory, then the
8885          target does not support querying traceframe info, and so we
8886          attempt reading from the traceframe anyway (assuming the
8887          target implements the old QTro packet then).  */
8888       if (traceframe_available_memory (&available, memaddr, len))
8889         {
8890           if (available.empty () || available[0].start != memaddr)
8891             {
8892               enum target_xfer_status res;
8893
8894               /* Don't read into the traceframe's available
8895                  memory.  */
8896               if (!available.empty ())
8897                 {
8898                   LONGEST oldlen = len;
8899
8900                   len = available[0].start - memaddr;
8901                   gdb_assert (len <= oldlen);
8902                 }
8903
8904               /* This goes through the topmost target again.  */
8905               res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8906                                                        len, unit_size, xfered_len);
8907               if (res == TARGET_XFER_OK)
8908                 return TARGET_XFER_OK;
8909               else
8910                 {
8911                   /* No use trying further, we know some memory starting
8912                      at MEMADDR isn't available.  */
8913                   *xfered_len = len;
8914                   return (*xfered_len != 0) ?
8915                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8916                 }
8917             }
8918
8919           /* Don't try to read more than how much is available, in
8920              case the target implements the deprecated QTro packet to
8921              cater for older GDBs (the target's knowledge of read-only
8922              sections may be outdated by now).  */
8923           len = available[0].length;
8924         }
8925     }
8926
8927   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8928 }
8929
8930 \f
8931
8932 /* Sends a packet with content determined by the printf format string
8933    FORMAT and the remaining arguments, then gets the reply.  Returns
8934    whether the packet was a success, a failure, or unknown.  */
8935
8936 packet_result
8937 remote_target::remote_send_printf (const char *format, ...)
8938 {
8939   struct remote_state *rs = get_remote_state ();
8940   int max_size = get_remote_packet_size ();
8941   va_list ap;
8942
8943   va_start (ap, format);
8944
8945   rs->buf[0] = '\0';
8946   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
8947     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8948
8949   if (putpkt (rs->buf) < 0)
8950     error (_("Communication problem with target."));
8951
8952   rs->buf[0] = '\0';
8953   getpkt (&rs->buf, &rs->buf_size, 0);
8954
8955   return packet_check_result (rs->buf);
8956 }
8957
8958 /* Flash writing can take quite some time.  We'll set
8959    effectively infinite timeout for flash operations.
8960    In future, we'll need to decide on a better approach.  */
8961 static const int remote_flash_timeout = 1000;
8962
8963 void
8964 remote_target::flash_erase (ULONGEST address, LONGEST length)
8965 {
8966   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8967   enum packet_result ret;
8968   scoped_restore restore_timeout
8969     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8970
8971   ret = remote_send_printf ("vFlashErase:%s,%s",
8972                             phex (address, addr_size),
8973                             phex (length, 4));
8974   switch (ret)
8975     {
8976     case PACKET_UNKNOWN:
8977       error (_("Remote target does not support flash erase"));
8978     case PACKET_ERROR:
8979       error (_("Error erasing flash with vFlashErase packet"));
8980     default:
8981       break;
8982     }
8983 }
8984
8985 target_xfer_status
8986 remote_target::remote_flash_write (ULONGEST address,
8987                                    ULONGEST length, ULONGEST *xfered_len,
8988                                    const gdb_byte *data)
8989 {
8990   scoped_restore restore_timeout
8991     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8992   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8993                                  xfered_len,'X', 0);
8994 }
8995
8996 void
8997 remote_target::flash_done ()
8998 {
8999   int ret;
9000
9001   scoped_restore restore_timeout
9002     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9003
9004   ret = remote_send_printf ("vFlashDone");
9005
9006   switch (ret)
9007     {
9008     case PACKET_UNKNOWN:
9009       error (_("Remote target does not support vFlashDone"));
9010     case PACKET_ERROR:
9011       error (_("Error finishing flash operation"));
9012     default:
9013       break;
9014     }
9015 }
9016
9017 void
9018 remote_target::files_info ()
9019 {
9020   puts_filtered ("Debugging a target over a serial line.\n");
9021 }
9022 \f
9023 /* Stuff for dealing with the packets which are part of this protocol.
9024    See comment at top of file for details.  */
9025
9026 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9027    error to higher layers.  Called when a serial error is detected.
9028    The exception message is STRING, followed by a colon and a blank,
9029    the system error message for errno at function entry and final dot
9030    for output compatibility with throw_perror_with_name.  */
9031
9032 static void
9033 unpush_and_perror (const char *string)
9034 {
9035   int saved_errno = errno;
9036
9037   remote_unpush_target ();
9038   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9039                safe_strerror (saved_errno));
9040 }
9041
9042 /* Read a single character from the remote end.  The current quit
9043    handler is overridden to avoid quitting in the middle of packet
9044    sequence, as that would break communication with the remote server.
9045    See remote_serial_quit_handler for more detail.  */
9046
9047 int
9048 remote_target::readchar (int timeout)
9049 {
9050   int ch;
9051   struct remote_state *rs = get_remote_state ();
9052
9053   {
9054     scoped_restore restore_quit_target
9055       = make_scoped_restore (&curr_quit_handler_target, this);
9056     scoped_restore restore_quit
9057       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9058
9059     rs->got_ctrlc_during_io = 0;
9060
9061     ch = serial_readchar (rs->remote_desc, timeout);
9062
9063     if (rs->got_ctrlc_during_io)
9064       set_quit_flag ();
9065   }
9066
9067   if (ch >= 0)
9068     return ch;
9069
9070   switch ((enum serial_rc) ch)
9071     {
9072     case SERIAL_EOF:
9073       remote_unpush_target ();
9074       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9075       /* no return */
9076     case SERIAL_ERROR:
9077       unpush_and_perror (_("Remote communication error.  "
9078                            "Target disconnected."));
9079       /* no return */
9080     case SERIAL_TIMEOUT:
9081       break;
9082     }
9083   return ch;
9084 }
9085
9086 /* Wrapper for serial_write that closes the target and throws if
9087    writing fails.  The current quit handler is overridden to avoid
9088    quitting in the middle of packet sequence, as that would break
9089    communication with the remote server.  See
9090    remote_serial_quit_handler for more detail.  */
9091
9092 void
9093 remote_target::remote_serial_write (const char *str, int len)
9094 {
9095   struct remote_state *rs = get_remote_state ();
9096
9097   scoped_restore restore_quit_target
9098     = make_scoped_restore (&curr_quit_handler_target, this);
9099   scoped_restore restore_quit
9100     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9101
9102   rs->got_ctrlc_during_io = 0;
9103
9104   if (serial_write (rs->remote_desc, str, len))
9105     {
9106       unpush_and_perror (_("Remote communication error.  "
9107                            "Target disconnected."));
9108     }
9109
9110   if (rs->got_ctrlc_during_io)
9111     set_quit_flag ();
9112 }
9113
9114 /* Return a string representing an escaped version of BUF, of len N.
9115    E.g. \n is converted to \\n, \t to \\t, etc.  */
9116
9117 static std::string
9118 escape_buffer (const char *buf, int n)
9119 {
9120   string_file stb;
9121
9122   stb.putstrn (buf, n, '\\');
9123   return std::move (stb.string ());
9124 }
9125
9126 /* Display a null-terminated packet on stdout, for debugging, using C
9127    string notation.  */
9128
9129 static void
9130 print_packet (const char *buf)
9131 {
9132   puts_filtered ("\"");
9133   fputstr_filtered (buf, '"', gdb_stdout);
9134   puts_filtered ("\"");
9135 }
9136
9137 int
9138 remote_target::putpkt (const char *buf)
9139 {
9140   return putpkt_binary (buf, strlen (buf));
9141 }
9142
9143 /* Wrapper around remote_target::putpkt to avoid exporting
9144    remote_target.  */
9145
9146 int
9147 putpkt (remote_target *remote, const char *buf)
9148 {
9149   return remote->putpkt (buf);
9150 }
9151
9152 /* Send a packet to the remote machine, with error checking.  The data
9153    of the packet is in BUF.  The string in BUF can be at most
9154    get_remote_packet_size () - 5 to account for the $, # and checksum,
9155    and for a possible /0 if we are debugging (remote_debug) and want
9156    to print the sent packet as a string.  */
9157
9158 int
9159 remote_target::putpkt_binary (const char *buf, int cnt)
9160 {
9161   struct remote_state *rs = get_remote_state ();
9162   int i;
9163   unsigned char csum = 0;
9164   gdb::def_vector<char> data (cnt + 6);
9165   char *buf2 = data.data ();
9166
9167   int ch;
9168   int tcount = 0;
9169   char *p;
9170
9171   /* Catch cases like trying to read memory or listing threads while
9172      we're waiting for a stop reply.  The remote server wouldn't be
9173      ready to handle this request, so we'd hang and timeout.  We don't
9174      have to worry about this in synchronous mode, because in that
9175      case it's not possible to issue a command while the target is
9176      running.  This is not a problem in non-stop mode, because in that
9177      case, the stub is always ready to process serial input.  */
9178   if (!target_is_non_stop_p ()
9179       && target_is_async_p ()
9180       && rs->waiting_for_stop_reply)
9181     {
9182       error (_("Cannot execute this command while the target is running.\n"
9183                "Use the \"interrupt\" command to stop the target\n"
9184                "and then try again."));
9185     }
9186
9187   /* We're sending out a new packet.  Make sure we don't look at a
9188      stale cached response.  */
9189   rs->cached_wait_status = 0;
9190
9191   /* Copy the packet into buffer BUF2, encapsulating it
9192      and giving it a checksum.  */
9193
9194   p = buf2;
9195   *p++ = '$';
9196
9197   for (i = 0; i < cnt; i++)
9198     {
9199       csum += buf[i];
9200       *p++ = buf[i];
9201     }
9202   *p++ = '#';
9203   *p++ = tohex ((csum >> 4) & 0xf);
9204   *p++ = tohex (csum & 0xf);
9205
9206   /* Send it over and over until we get a positive ack.  */
9207
9208   while (1)
9209     {
9210       int started_error_output = 0;
9211
9212       if (remote_debug)
9213         {
9214           *p = '\0';
9215
9216           int len = (int) (p - buf2);
9217
9218           std::string str
9219             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9220
9221           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9222
9223           if (len > REMOTE_DEBUG_MAX_CHAR)
9224             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9225                                 len - REMOTE_DEBUG_MAX_CHAR);
9226
9227           fprintf_unfiltered (gdb_stdlog, "...");
9228
9229           gdb_flush (gdb_stdlog);
9230         }
9231       remote_serial_write (buf2, p - buf2);
9232
9233       /* If this is a no acks version of the remote protocol, send the
9234          packet and move on.  */
9235       if (rs->noack_mode)
9236         break;
9237
9238       /* Read until either a timeout occurs (-2) or '+' is read.
9239          Handle any notification that arrives in the mean time.  */
9240       while (1)
9241         {
9242           ch = readchar (remote_timeout);
9243
9244           if (remote_debug)
9245             {
9246               switch (ch)
9247                 {
9248                 case '+':
9249                 case '-':
9250                 case SERIAL_TIMEOUT:
9251                 case '$':
9252                 case '%':
9253                   if (started_error_output)
9254                     {
9255                       putchar_unfiltered ('\n');
9256                       started_error_output = 0;
9257                     }
9258                 }
9259             }
9260
9261           switch (ch)
9262             {
9263             case '+':
9264               if (remote_debug)
9265                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9266               return 1;
9267             case '-':
9268               if (remote_debug)
9269                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9270               /* FALLTHROUGH */
9271             case SERIAL_TIMEOUT:
9272               tcount++;
9273               if (tcount > 3)
9274                 return 0;
9275               break;            /* Retransmit buffer.  */
9276             case '$':
9277               {
9278                 if (remote_debug)
9279                   fprintf_unfiltered (gdb_stdlog,
9280                                       "Packet instead of Ack, ignoring it\n");
9281                 /* It's probably an old response sent because an ACK
9282                    was lost.  Gobble up the packet and ack it so it
9283                    doesn't get retransmitted when we resend this
9284                    packet.  */
9285                 skip_frame ();
9286                 remote_serial_write ("+", 1);
9287                 continue;       /* Now, go look for +.  */
9288               }
9289
9290             case '%':
9291               {
9292                 int val;
9293
9294                 /* If we got a notification, handle it, and go back to looking
9295                    for an ack.  */
9296                 /* We've found the start of a notification.  Now
9297                    collect the data.  */
9298                 val = read_frame (&rs->buf, &rs->buf_size);
9299                 if (val >= 0)
9300                   {
9301                     if (remote_debug)
9302                       {
9303                         std::string str = escape_buffer (rs->buf, val);
9304
9305                         fprintf_unfiltered (gdb_stdlog,
9306                                             "  Notification received: %s\n",
9307                                             str.c_str ());
9308                       }
9309                     handle_notification (rs->notif_state, rs->buf);
9310                     /* We're in sync now, rewait for the ack.  */
9311                     tcount = 0;
9312                   }
9313                 else
9314                   {
9315                     if (remote_debug)
9316                       {
9317                         if (!started_error_output)
9318                           {
9319                             started_error_output = 1;
9320                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9321                           }
9322                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9323                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9324                       }
9325                   }
9326                 continue;
9327               }
9328               /* fall-through */
9329             default:
9330               if (remote_debug)
9331                 {
9332                   if (!started_error_output)
9333                     {
9334                       started_error_output = 1;
9335                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9336                     }
9337                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9338                 }
9339               continue;
9340             }
9341           break;                /* Here to retransmit.  */
9342         }
9343
9344 #if 0
9345       /* This is wrong.  If doing a long backtrace, the user should be
9346          able to get out next time we call QUIT, without anything as
9347          violent as interrupt_query.  If we want to provide a way out of
9348          here without getting to the next QUIT, it should be based on
9349          hitting ^C twice as in remote_wait.  */
9350       if (quit_flag)
9351         {
9352           quit_flag = 0;
9353           interrupt_query ();
9354         }
9355 #endif
9356     }
9357
9358   return 0;
9359 }
9360
9361 /* Come here after finding the start of a frame when we expected an
9362    ack.  Do our best to discard the rest of this packet.  */
9363
9364 void
9365 remote_target::skip_frame ()
9366 {
9367   int c;
9368
9369   while (1)
9370     {
9371       c = readchar (remote_timeout);
9372       switch (c)
9373         {
9374         case SERIAL_TIMEOUT:
9375           /* Nothing we can do.  */
9376           return;
9377         case '#':
9378           /* Discard the two bytes of checksum and stop.  */
9379           c = readchar (remote_timeout);
9380           if (c >= 0)
9381             c = readchar (remote_timeout);
9382
9383           return;
9384         case '*':               /* Run length encoding.  */
9385           /* Discard the repeat count.  */
9386           c = readchar (remote_timeout);
9387           if (c < 0)
9388             return;
9389           break;
9390         default:
9391           /* A regular character.  */
9392           break;
9393         }
9394     }
9395 }
9396
9397 /* Come here after finding the start of the frame.  Collect the rest
9398    into *BUF, verifying the checksum, length, and handling run-length
9399    compression.  NUL terminate the buffer.  If there is not enough room,
9400    expand *BUF using xrealloc.
9401
9402    Returns -1 on error, number of characters in buffer (ignoring the
9403    trailing NULL) on success. (could be extended to return one of the
9404    SERIAL status indications).  */
9405
9406 long
9407 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9408 {
9409   unsigned char csum;
9410   long bc;
9411   int c;
9412   char *buf = *buf_p;
9413   struct remote_state *rs = get_remote_state ();
9414
9415   csum = 0;
9416   bc = 0;
9417
9418   while (1)
9419     {
9420       c = readchar (remote_timeout);
9421       switch (c)
9422         {
9423         case SERIAL_TIMEOUT:
9424           if (remote_debug)
9425             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9426           return -1;
9427         case '$':
9428           if (remote_debug)
9429             fputs_filtered ("Saw new packet start in middle of old one\n",
9430                             gdb_stdlog);
9431           return -1;            /* Start a new packet, count retries.  */
9432         case '#':
9433           {
9434             unsigned char pktcsum;
9435             int check_0 = 0;
9436             int check_1 = 0;
9437
9438             buf[bc] = '\0';
9439
9440             check_0 = readchar (remote_timeout);
9441             if (check_0 >= 0)
9442               check_1 = readchar (remote_timeout);
9443
9444             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9445               {
9446                 if (remote_debug)
9447                   fputs_filtered ("Timeout in checksum, retrying\n",
9448                                   gdb_stdlog);
9449                 return -1;
9450               }
9451             else if (check_0 < 0 || check_1 < 0)
9452               {
9453                 if (remote_debug)
9454                   fputs_filtered ("Communication error in checksum\n",
9455                                   gdb_stdlog);
9456                 return -1;
9457               }
9458
9459             /* Don't recompute the checksum; with no ack packets we
9460                don't have any way to indicate a packet retransmission
9461                is necessary.  */
9462             if (rs->noack_mode)
9463               return bc;
9464
9465             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9466             if (csum == pktcsum)
9467               return bc;
9468
9469             if (remote_debug)
9470               {
9471                 std::string str = escape_buffer (buf, bc);
9472
9473                 fprintf_unfiltered (gdb_stdlog,
9474                                     "Bad checksum, sentsum=0x%x, "
9475                                     "csum=0x%x, buf=%s\n",
9476                                     pktcsum, csum, str.c_str ());
9477               }
9478             /* Number of characters in buffer ignoring trailing
9479                NULL.  */
9480             return -1;
9481           }
9482         case '*':               /* Run length encoding.  */
9483           {
9484             int repeat;
9485
9486             csum += c;
9487             c = readchar (remote_timeout);
9488             csum += c;
9489             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9490
9491             /* The character before ``*'' is repeated.  */
9492
9493             if (repeat > 0 && repeat <= 255 && bc > 0)
9494               {
9495                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9496                   {
9497                     /* Make some more room in the buffer.  */
9498                     *sizeof_buf += repeat;
9499                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9500                     buf = *buf_p;
9501                   }
9502
9503                 memset (&buf[bc], buf[bc - 1], repeat);
9504                 bc += repeat;
9505                 continue;
9506               }
9507
9508             buf[bc] = '\0';
9509             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9510             return -1;
9511           }
9512         default:
9513           if (bc >= *sizeof_buf - 1)
9514             {
9515               /* Make some more room in the buffer.  */
9516               *sizeof_buf *= 2;
9517               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9518               buf = *buf_p;
9519             }
9520
9521           buf[bc++] = c;
9522           csum += c;
9523           continue;
9524         }
9525     }
9526 }
9527
9528 /* Read a packet from the remote machine, with error checking, and
9529    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9530    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9531    rather than timing out; this is used (in synchronous mode) to wait
9532    for a target that is is executing user code to stop.  */
9533 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9534    don't have to change all the calls to getpkt to deal with the
9535    return value, because at the moment I don't know what the right
9536    thing to do it for those.  */
9537
9538 void
9539 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9540 {
9541   getpkt_sane (buf, sizeof_buf, forever);
9542 }
9543
9544
9545 /* Read a packet from the remote machine, with error checking, and
9546    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9547    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9548    rather than timing out; this is used (in synchronous mode) to wait
9549    for a target that is is executing user code to stop.  If FOREVER ==
9550    0, this function is allowed to time out gracefully and return an
9551    indication of this to the caller.  Otherwise return the number of
9552    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9553    enough reason to return to the caller.  *IS_NOTIF is an output
9554    boolean that indicates whether *BUF holds a notification or not
9555    (a regular packet).  */
9556
9557 int
9558 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9559                                        int forever, int expecting_notif,
9560                                        int *is_notif)
9561 {
9562   struct remote_state *rs = get_remote_state ();
9563   int c;
9564   int tries;
9565   int timeout;
9566   int val = -1;
9567
9568   /* We're reading a new response.  Make sure we don't look at a
9569      previously cached response.  */
9570   rs->cached_wait_status = 0;
9571
9572   strcpy (*buf, "timeout");
9573
9574   if (forever)
9575     timeout = watchdog > 0 ? watchdog : -1;
9576   else if (expecting_notif)
9577     timeout = 0; /* There should already be a char in the buffer.  If
9578                     not, bail out.  */
9579   else
9580     timeout = remote_timeout;
9581
9582 #define MAX_TRIES 3
9583
9584   /* Process any number of notifications, and then return when
9585      we get a packet.  */
9586   for (;;)
9587     {
9588       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9589          times.  */
9590       for (tries = 1; tries <= MAX_TRIES; tries++)
9591         {
9592           /* This can loop forever if the remote side sends us
9593              characters continuously, but if it pauses, we'll get
9594              SERIAL_TIMEOUT from readchar because of timeout.  Then
9595              we'll count that as a retry.
9596
9597              Note that even when forever is set, we will only wait
9598              forever prior to the start of a packet.  After that, we
9599              expect characters to arrive at a brisk pace.  They should
9600              show up within remote_timeout intervals.  */
9601           do
9602             c = readchar (timeout);
9603           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9604
9605           if (c == SERIAL_TIMEOUT)
9606             {
9607               if (expecting_notif)
9608                 return -1; /* Don't complain, it's normal to not get
9609                               anything in this case.  */
9610
9611               if (forever)      /* Watchdog went off?  Kill the target.  */
9612                 {
9613                   remote_unpush_target ();
9614                   throw_error (TARGET_CLOSE_ERROR,
9615                                _("Watchdog timeout has expired.  "
9616                                  "Target detached."));
9617                 }
9618               if (remote_debug)
9619                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9620             }
9621           else
9622             {
9623               /* We've found the start of a packet or notification.
9624                  Now collect the data.  */
9625               val = read_frame (buf, sizeof_buf);
9626               if (val >= 0)
9627                 break;
9628             }
9629
9630           remote_serial_write ("-", 1);
9631         }
9632
9633       if (tries > MAX_TRIES)
9634         {
9635           /* We have tried hard enough, and just can't receive the
9636              packet/notification.  Give up.  */
9637           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9638
9639           /* Skip the ack char if we're in no-ack mode.  */
9640           if (!rs->noack_mode)
9641             remote_serial_write ("+", 1);
9642           return -1;
9643         }
9644
9645       /* If we got an ordinary packet, return that to our caller.  */
9646       if (c == '$')
9647         {
9648           if (remote_debug)
9649             {
9650               std::string str
9651                 = escape_buffer (*buf,
9652                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9653
9654               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9655                                   str.c_str ());
9656
9657               if (val > REMOTE_DEBUG_MAX_CHAR)
9658                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9659                                     val - REMOTE_DEBUG_MAX_CHAR);
9660
9661               fprintf_unfiltered (gdb_stdlog, "\n");
9662             }
9663
9664           /* Skip the ack char if we're in no-ack mode.  */
9665           if (!rs->noack_mode)
9666             remote_serial_write ("+", 1);
9667           if (is_notif != NULL)
9668             *is_notif = 0;
9669           return val;
9670         }
9671
9672        /* If we got a notification, handle it, and go back to looking
9673          for a packet.  */
9674       else
9675         {
9676           gdb_assert (c == '%');
9677
9678           if (remote_debug)
9679             {
9680               std::string str = escape_buffer (*buf, val);
9681
9682               fprintf_unfiltered (gdb_stdlog,
9683                                   "  Notification received: %s\n",
9684                                   str.c_str ());
9685             }
9686           if (is_notif != NULL)
9687             *is_notif = 1;
9688
9689           handle_notification (rs->notif_state, *buf);
9690
9691           /* Notifications require no acknowledgement.  */
9692
9693           if (expecting_notif)
9694             return val;
9695         }
9696     }
9697 }
9698
9699 int
9700 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9701 {
9702   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9703 }
9704
9705 int
9706 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9707                                      int *is_notif)
9708 {
9709   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9710                                  is_notif);
9711 }
9712
9713 /* Kill any new fork children of process PID that haven't been
9714    processed by follow_fork.  */
9715
9716 void
9717 remote_target::kill_new_fork_children (int pid)
9718 {
9719   remote_state *rs = get_remote_state ();
9720   struct thread_info *thread;
9721   struct notif_client *notif = &notif_client_stop;
9722
9723   /* Kill the fork child threads of any threads in process PID
9724      that are stopped at a fork event.  */
9725   ALL_NON_EXITED_THREADS (thread)
9726     {
9727       struct target_waitstatus *ws = &thread->pending_follow;
9728
9729       if (is_pending_fork_parent (ws, pid, thread->ptid))
9730         {
9731           int child_pid = ws->value.related_pid.pid ();
9732           int res;
9733
9734           res = remote_vkill (child_pid);
9735           if (res != 0)
9736             error (_("Can't kill fork child process %d"), child_pid);
9737         }
9738     }
9739
9740   /* Check for any pending fork events (not reported or processed yet)
9741      in process PID and kill those fork child threads as well.  */
9742   remote_notif_get_pending_events (notif);
9743   for (auto &event : rs->stop_reply_queue)
9744     if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9745       {
9746         int child_pid = event->ws.value.related_pid.pid ();
9747         int res;
9748
9749         res = remote_vkill (child_pid);
9750         if (res != 0)
9751           error (_("Can't kill fork child process %d"), child_pid);
9752       }
9753 }
9754
9755 \f
9756 /* Target hook to kill the current inferior.  */
9757
9758 void
9759 remote_target::kill ()
9760 {
9761   int res = -1;
9762   int pid = inferior_ptid.pid ();
9763   struct remote_state *rs = get_remote_state ();
9764
9765   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9766     {
9767       /* If we're stopped while forking and we haven't followed yet,
9768          kill the child task.  We need to do this before killing the
9769          parent task because if this is a vfork then the parent will
9770          be sleeping.  */
9771       kill_new_fork_children (pid);
9772
9773       res = remote_vkill (pid);
9774       if (res == 0)
9775         {
9776           target_mourn_inferior (inferior_ptid);
9777           return;
9778         }
9779     }
9780
9781   /* If we are in 'target remote' mode and we are killing the only
9782      inferior, then we will tell gdbserver to exit and unpush the
9783      target.  */
9784   if (res == -1 && !remote_multi_process_p (rs)
9785       && number_of_live_inferiors () == 1)
9786     {
9787       remote_kill_k ();
9788
9789       /* We've killed the remote end, we get to mourn it.  If we are
9790          not in extended mode, mourning the inferior also unpushes
9791          remote_ops from the target stack, which closes the remote
9792          connection.  */
9793       target_mourn_inferior (inferior_ptid);
9794
9795       return;
9796     }
9797
9798   error (_("Can't kill process"));
9799 }
9800
9801 /* Send a kill request to the target using the 'vKill' packet.  */
9802
9803 int
9804 remote_target::remote_vkill (int pid)
9805 {
9806   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9807     return -1;
9808
9809   remote_state *rs = get_remote_state ();
9810
9811   /* Tell the remote target to detach.  */
9812   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9813   putpkt (rs->buf);
9814   getpkt (&rs->buf, &rs->buf_size, 0);
9815
9816   switch (packet_ok (rs->buf,
9817                      &remote_protocol_packets[PACKET_vKill]))
9818     {
9819     case PACKET_OK:
9820       return 0;
9821     case PACKET_ERROR:
9822       return 1;
9823     case PACKET_UNKNOWN:
9824       return -1;
9825     default:
9826       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9827     }
9828 }
9829
9830 /* Send a kill request to the target using the 'k' packet.  */
9831
9832 void
9833 remote_target::remote_kill_k ()
9834 {
9835   /* Catch errors so the user can quit from gdb even when we
9836      aren't on speaking terms with the remote system.  */
9837   TRY
9838     {
9839       putpkt ("k");
9840     }
9841   CATCH (ex, RETURN_MASK_ERROR)
9842     {
9843       if (ex.error == TARGET_CLOSE_ERROR)
9844         {
9845           /* If we got an (EOF) error that caused the target
9846              to go away, then we're done, that's what we wanted.
9847              "k" is susceptible to cause a premature EOF, given
9848              that the remote server isn't actually required to
9849              reply to "k", and it can happen that it doesn't
9850              even get to reply ACK to the "k".  */
9851           return;
9852         }
9853
9854       /* Otherwise, something went wrong.  We didn't actually kill
9855          the target.  Just propagate the exception, and let the
9856          user or higher layers decide what to do.  */
9857       throw_exception (ex);
9858     }
9859   END_CATCH
9860 }
9861
9862 void
9863 remote_target::mourn_inferior ()
9864 {
9865   struct remote_state *rs = get_remote_state ();
9866
9867   /* We're no longer interested in notification events of an inferior
9868      that exited or was killed/detached.  */
9869   discard_pending_stop_replies (current_inferior ());
9870
9871   /* In 'target remote' mode with one inferior, we close the connection.  */
9872   if (!rs->extended && number_of_live_inferiors () <= 1)
9873     {
9874       unpush_target (this);
9875
9876       /* remote_close takes care of doing most of the clean up.  */
9877       generic_mourn_inferior ();
9878       return;
9879     }
9880
9881   /* In case we got here due to an error, but we're going to stay
9882      connected.  */
9883   rs->waiting_for_stop_reply = 0;
9884
9885   /* If the current general thread belonged to the process we just
9886      detached from or has exited, the remote side current general
9887      thread becomes undefined.  Considering a case like this:
9888
9889      - We just got here due to a detach.
9890      - The process that we're detaching from happens to immediately
9891        report a global breakpoint being hit in non-stop mode, in the
9892        same thread we had selected before.
9893      - GDB attaches to this process again.
9894      - This event happens to be the next event we handle.
9895
9896      GDB would consider that the current general thread didn't need to
9897      be set on the stub side (with Hg), since for all it knew,
9898      GENERAL_THREAD hadn't changed.
9899
9900      Notice that although in all-stop mode, the remote server always
9901      sets the current thread to the thread reporting the stop event,
9902      that doesn't happen in non-stop mode; in non-stop, the stub *must
9903      not* change the current thread when reporting a breakpoint hit,
9904      due to the decoupling of event reporting and event handling.
9905
9906      To keep things simple, we always invalidate our notion of the
9907      current thread.  */
9908   record_currthread (rs, minus_one_ptid);
9909
9910   /* Call common code to mark the inferior as not running.  */
9911   generic_mourn_inferior ();
9912
9913   if (!have_inferiors ())
9914     {
9915       if (!remote_multi_process_p (rs))
9916         {
9917           /* Check whether the target is running now - some remote stubs
9918              automatically restart after kill.  */
9919           putpkt ("?");
9920           getpkt (&rs->buf, &rs->buf_size, 0);
9921
9922           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9923             {
9924               /* Assume that the target has been restarted.  Set
9925                  inferior_ptid so that bits of core GDB realizes
9926                  there's something here, e.g., so that the user can
9927                  say "kill" again.  */
9928               inferior_ptid = magic_null_ptid;
9929             }
9930         }
9931     }
9932 }
9933
9934 bool
9935 extended_remote_target::supports_disable_randomization ()
9936 {
9937   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9938 }
9939
9940 void
9941 remote_target::extended_remote_disable_randomization (int val)
9942 {
9943   struct remote_state *rs = get_remote_state ();
9944   char *reply;
9945
9946   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
9947              val);
9948   putpkt (rs->buf);
9949   reply = remote_get_noisy_reply ();
9950   if (*reply == '\0')
9951     error (_("Target does not support QDisableRandomization."));
9952   if (strcmp (reply, "OK") != 0)
9953     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9954 }
9955
9956 int
9957 remote_target::extended_remote_run (const std::string &args)
9958 {
9959   struct remote_state *rs = get_remote_state ();
9960   int len;
9961   const char *remote_exec_file = get_remote_exec_file ();
9962
9963   /* If the user has disabled vRun support, or we have detected that
9964      support is not available, do not try it.  */
9965   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9966     return -1;
9967
9968   strcpy (rs->buf, "vRun;");
9969   len = strlen (rs->buf);
9970
9971   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9972     error (_("Remote file name too long for run packet"));
9973   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
9974                       strlen (remote_exec_file));
9975
9976   if (!args.empty ())
9977     {
9978       int i;
9979
9980       gdb_argv argv (args.c_str ());
9981       for (i = 0; argv[i] != NULL; i++)
9982         {
9983           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9984             error (_("Argument list too long for run packet"));
9985           rs->buf[len++] = ';';
9986           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
9987                               strlen (argv[i]));
9988         }
9989     }
9990
9991   rs->buf[len++] = '\0';
9992
9993   putpkt (rs->buf);
9994   getpkt (&rs->buf, &rs->buf_size, 0);
9995
9996   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9997     {
9998     case PACKET_OK:
9999       /* We have a wait response.  All is well.  */
10000       return 0;
10001     case PACKET_UNKNOWN:
10002       return -1;
10003     case PACKET_ERROR:
10004       if (remote_exec_file[0] == '\0')
10005         error (_("Running the default executable on the remote target failed; "
10006                  "try \"set remote exec-file\"?"));
10007       else
10008         error (_("Running \"%s\" on the remote target failed"),
10009                remote_exec_file);
10010     default:
10011       gdb_assert_not_reached (_("bad switch"));
10012     }
10013 }
10014
10015 /* Helper function to send set/unset environment packets.  ACTION is
10016    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
10017    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
10018    sent.  */
10019
10020 void
10021 remote_target::send_environment_packet (const char *action,
10022                                         const char *packet,
10023                                         const char *value)
10024 {
10025   remote_state *rs = get_remote_state ();
10026
10027   /* Convert the environment variable to an hex string, which
10028      is the best format to be transmitted over the wire.  */
10029   std::string encoded_value = bin2hex ((const gdb_byte *) value,
10030                                          strlen (value));
10031
10032   xsnprintf (rs->buf, get_remote_packet_size (),
10033              "%s:%s", packet, encoded_value.c_str ());
10034
10035   putpkt (rs->buf);
10036   getpkt (&rs->buf, &rs->buf_size, 0);
10037   if (strcmp (rs->buf, "OK") != 0)
10038     warning (_("Unable to %s environment variable '%s' on remote."),
10039              action, value);
10040 }
10041
10042 /* Helper function to handle the QEnvironment* packets.  */
10043
10044 void
10045 remote_target::extended_remote_environment_support ()
10046 {
10047   remote_state *rs = get_remote_state ();
10048
10049   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10050     {
10051       putpkt ("QEnvironmentReset");
10052       getpkt (&rs->buf, &rs->buf_size, 0);
10053       if (strcmp (rs->buf, "OK") != 0)
10054         warning (_("Unable to reset environment on remote."));
10055     }
10056
10057   gdb_environ *e = &current_inferior ()->environment;
10058
10059   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10060     for (const std::string &el : e->user_set_env ())
10061       send_environment_packet ("set", "QEnvironmentHexEncoded",
10062                                el.c_str ());
10063
10064   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10065     for (const std::string &el : e->user_unset_env ())
10066       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10067 }
10068
10069 /* Helper function to set the current working directory for the
10070    inferior in the remote target.  */
10071
10072 void
10073 remote_target::extended_remote_set_inferior_cwd ()
10074 {
10075   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10076     {
10077       const char *inferior_cwd = get_inferior_cwd ();
10078       remote_state *rs = get_remote_state ();
10079
10080       if (inferior_cwd != NULL)
10081         {
10082           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10083                                          strlen (inferior_cwd));
10084
10085           xsnprintf (rs->buf, get_remote_packet_size (),
10086                      "QSetWorkingDir:%s", hexpath.c_str ());
10087         }
10088       else
10089         {
10090           /* An empty inferior_cwd means that the user wants us to
10091              reset the remote server's inferior's cwd.  */
10092           xsnprintf (rs->buf, get_remote_packet_size (),
10093                      "QSetWorkingDir:");
10094         }
10095
10096       putpkt (rs->buf);
10097       getpkt (&rs->buf, &rs->buf_size, 0);
10098       if (packet_ok (rs->buf,
10099                      &remote_protocol_packets[PACKET_QSetWorkingDir])
10100           != PACKET_OK)
10101         error (_("\
10102 Remote replied unexpectedly while setting the inferior's working\n\
10103 directory: %s"),
10104                rs->buf);
10105
10106     }
10107 }
10108
10109 /* In the extended protocol we want to be able to do things like
10110    "run" and have them basically work as expected.  So we need
10111    a special create_inferior function.  We support changing the
10112    executable file and the command line arguments, but not the
10113    environment.  */
10114
10115 void
10116 extended_remote_target::create_inferior (const char *exec_file,
10117                                          const std::string &args,
10118                                          char **env, int from_tty)
10119 {
10120   int run_worked;
10121   char *stop_reply;
10122   struct remote_state *rs = get_remote_state ();
10123   const char *remote_exec_file = get_remote_exec_file ();
10124
10125   /* If running asynchronously, register the target file descriptor
10126      with the event loop.  */
10127   if (target_can_async_p ())
10128     target_async (1);
10129
10130   /* Disable address space randomization if requested (and supported).  */
10131   if (supports_disable_randomization ())
10132     extended_remote_disable_randomization (disable_randomization);
10133
10134   /* If startup-with-shell is on, we inform gdbserver to start the
10135      remote inferior using a shell.  */
10136   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10137     {
10138       xsnprintf (rs->buf, get_remote_packet_size (),
10139                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10140       putpkt (rs->buf);
10141       getpkt (&rs->buf, &rs->buf_size, 0);
10142       if (strcmp (rs->buf, "OK") != 0)
10143         error (_("\
10144 Remote replied unexpectedly while setting startup-with-shell: %s"),
10145                rs->buf);
10146     }
10147
10148   extended_remote_environment_support ();
10149
10150   extended_remote_set_inferior_cwd ();
10151
10152   /* Now restart the remote server.  */
10153   run_worked = extended_remote_run (args) != -1;
10154   if (!run_worked)
10155     {
10156       /* vRun was not supported.  Fail if we need it to do what the
10157          user requested.  */
10158       if (remote_exec_file[0])
10159         error (_("Remote target does not support \"set remote exec-file\""));
10160       if (!args.empty ())
10161         error (_("Remote target does not support \"set args\" or run ARGS"));
10162
10163       /* Fall back to "R".  */
10164       extended_remote_restart ();
10165     }
10166
10167   if (!have_inferiors ())
10168     {
10169       /* Clean up from the last time we ran, before we mark the target
10170          running again.  This will mark breakpoints uninserted, and
10171          get_offsets may insert breakpoints.  */
10172       init_thread_list ();
10173       init_wait_for_inferior ();
10174     }
10175
10176   /* vRun's success return is a stop reply.  */
10177   stop_reply = run_worked ? rs->buf : NULL;
10178   add_current_inferior_and_thread (stop_reply);
10179
10180   /* Get updated offsets, if the stub uses qOffsets.  */
10181   get_offsets ();
10182 }
10183 \f
10184
10185 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10186    the list of conditions (in agent expression bytecode format), if any, the
10187    target needs to evaluate.  The output is placed into the packet buffer
10188    started from BUF and ended at BUF_END.  */
10189
10190 static int
10191 remote_add_target_side_condition (struct gdbarch *gdbarch,
10192                                   struct bp_target_info *bp_tgt, char *buf,
10193                                   char *buf_end)
10194 {
10195   if (bp_tgt->conditions.empty ())
10196     return 0;
10197
10198   buf += strlen (buf);
10199   xsnprintf (buf, buf_end - buf, "%s", ";");
10200   buf++;
10201
10202   /* Send conditions to the target.  */
10203   for (agent_expr *aexpr : bp_tgt->conditions)
10204     {
10205       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10206       buf += strlen (buf);
10207       for (int i = 0; i < aexpr->len; ++i)
10208         buf = pack_hex_byte (buf, aexpr->buf[i]);
10209       *buf = '\0';
10210     }
10211   return 0;
10212 }
10213
10214 static void
10215 remote_add_target_side_commands (struct gdbarch *gdbarch,
10216                                  struct bp_target_info *bp_tgt, char *buf)
10217 {
10218   if (bp_tgt->tcommands.empty ())
10219     return;
10220
10221   buf += strlen (buf);
10222
10223   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10224   buf += strlen (buf);
10225
10226   /* Concatenate all the agent expressions that are commands into the
10227      cmds parameter.  */
10228   for (agent_expr *aexpr : bp_tgt->tcommands)
10229     {
10230       sprintf (buf, "X%x,", aexpr->len);
10231       buf += strlen (buf);
10232       for (int i = 0; i < aexpr->len; ++i)
10233         buf = pack_hex_byte (buf, aexpr->buf[i]);
10234       *buf = '\0';
10235     }
10236 }
10237
10238 /* Insert a breakpoint.  On targets that have software breakpoint
10239    support, we ask the remote target to do the work; on targets
10240    which don't, we insert a traditional memory breakpoint.  */
10241
10242 int
10243 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10244                                   struct bp_target_info *bp_tgt)
10245 {
10246   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10247      If it succeeds, then set the support to PACKET_ENABLE.  If it
10248      fails, and the user has explicitly requested the Z support then
10249      report an error, otherwise, mark it disabled and go on.  */
10250
10251   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10252     {
10253       CORE_ADDR addr = bp_tgt->reqstd_address;
10254       struct remote_state *rs;
10255       char *p, *endbuf;
10256
10257       /* Make sure the remote is pointing at the right process, if
10258          necessary.  */
10259       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10260         set_general_process ();
10261
10262       rs = get_remote_state ();
10263       p = rs->buf;
10264       endbuf = rs->buf + get_remote_packet_size ();
10265
10266       *(p++) = 'Z';
10267       *(p++) = '0';
10268       *(p++) = ',';
10269       addr = (ULONGEST) remote_address_masked (addr);
10270       p += hexnumstr (p, addr);
10271       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10272
10273       if (supports_evaluation_of_breakpoint_conditions ())
10274         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10275
10276       if (can_run_breakpoint_commands ())
10277         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10278
10279       putpkt (rs->buf);
10280       getpkt (&rs->buf, &rs->buf_size, 0);
10281
10282       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10283         {
10284         case PACKET_ERROR:
10285           return -1;
10286         case PACKET_OK:
10287           return 0;
10288         case PACKET_UNKNOWN:
10289           break;
10290         }
10291     }
10292
10293   /* If this breakpoint has target-side commands but this stub doesn't
10294      support Z0 packets, throw error.  */
10295   if (!bp_tgt->tcommands.empty ())
10296     throw_error (NOT_SUPPORTED_ERROR, _("\
10297 Target doesn't support breakpoints that have target side commands."));
10298
10299   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10300 }
10301
10302 int
10303 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10304                                   struct bp_target_info *bp_tgt,
10305                                   enum remove_bp_reason reason)
10306 {
10307   CORE_ADDR addr = bp_tgt->placed_address;
10308   struct remote_state *rs = get_remote_state ();
10309
10310   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10311     {
10312       char *p = rs->buf;
10313       char *endbuf = rs->buf + get_remote_packet_size ();
10314
10315       /* Make sure the remote is pointing at the right process, if
10316          necessary.  */
10317       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10318         set_general_process ();
10319
10320       *(p++) = 'z';
10321       *(p++) = '0';
10322       *(p++) = ',';
10323
10324       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10325       p += hexnumstr (p, addr);
10326       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10327
10328       putpkt (rs->buf);
10329       getpkt (&rs->buf, &rs->buf_size, 0);
10330
10331       return (rs->buf[0] == 'E');
10332     }
10333
10334   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10335 }
10336
10337 static enum Z_packet_type
10338 watchpoint_to_Z_packet (int type)
10339 {
10340   switch (type)
10341     {
10342     case hw_write:
10343       return Z_PACKET_WRITE_WP;
10344       break;
10345     case hw_read:
10346       return Z_PACKET_READ_WP;
10347       break;
10348     case hw_access:
10349       return Z_PACKET_ACCESS_WP;
10350       break;
10351     default:
10352       internal_error (__FILE__, __LINE__,
10353                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10354     }
10355 }
10356
10357 int
10358 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10359                                   enum target_hw_bp_type type, struct expression *cond)
10360 {
10361   struct remote_state *rs = get_remote_state ();
10362   char *endbuf = rs->buf + get_remote_packet_size ();
10363   char *p;
10364   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10365
10366   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10367     return 1;
10368
10369   /* Make sure the remote is pointing at the right process, if
10370      necessary.  */
10371   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10372     set_general_process ();
10373
10374   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10375   p = strchr (rs->buf, '\0');
10376   addr = remote_address_masked (addr);
10377   p += hexnumstr (p, (ULONGEST) addr);
10378   xsnprintf (p, endbuf - p, ",%x", len);
10379
10380   putpkt (rs->buf);
10381   getpkt (&rs->buf, &rs->buf_size, 0);
10382
10383   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10384     {
10385     case PACKET_ERROR:
10386       return -1;
10387     case PACKET_UNKNOWN:
10388       return 1;
10389     case PACKET_OK:
10390       return 0;
10391     }
10392   internal_error (__FILE__, __LINE__,
10393                   _("remote_insert_watchpoint: reached end of function"));
10394 }
10395
10396 bool
10397 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10398                                              CORE_ADDR start, int length)
10399 {
10400   CORE_ADDR diff = remote_address_masked (addr - start);
10401
10402   return diff < length;
10403 }
10404
10405
10406 int
10407 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10408                                   enum target_hw_bp_type type, struct expression *cond)
10409 {
10410   struct remote_state *rs = get_remote_state ();
10411   char *endbuf = rs->buf + get_remote_packet_size ();
10412   char *p;
10413   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10414
10415   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10416     return -1;
10417
10418   /* Make sure the remote is pointing at the right process, if
10419      necessary.  */
10420   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10421     set_general_process ();
10422
10423   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10424   p = strchr (rs->buf, '\0');
10425   addr = remote_address_masked (addr);
10426   p += hexnumstr (p, (ULONGEST) addr);
10427   xsnprintf (p, endbuf - p, ",%x", len);
10428   putpkt (rs->buf);
10429   getpkt (&rs->buf, &rs->buf_size, 0);
10430
10431   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10432     {
10433     case PACKET_ERROR:
10434     case PACKET_UNKNOWN:
10435       return -1;
10436     case PACKET_OK:
10437       return 0;
10438     }
10439   internal_error (__FILE__, __LINE__,
10440                   _("remote_remove_watchpoint: reached end of function"));
10441 }
10442
10443
10444 int remote_hw_watchpoint_limit = -1;
10445 int remote_hw_watchpoint_length_limit = -1;
10446 int remote_hw_breakpoint_limit = -1;
10447
10448 int
10449 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10450 {
10451   if (remote_hw_watchpoint_length_limit == 0)
10452     return 0;
10453   else if (remote_hw_watchpoint_length_limit < 0)
10454     return 1;
10455   else if (len <= remote_hw_watchpoint_length_limit)
10456     return 1;
10457   else
10458     return 0;
10459 }
10460
10461 int
10462 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10463 {
10464   if (type == bp_hardware_breakpoint)
10465     {
10466       if (remote_hw_breakpoint_limit == 0)
10467         return 0;
10468       else if (remote_hw_breakpoint_limit < 0)
10469         return 1;
10470       else if (cnt <= remote_hw_breakpoint_limit)
10471         return 1;
10472     }
10473   else
10474     {
10475       if (remote_hw_watchpoint_limit == 0)
10476         return 0;
10477       else if (remote_hw_watchpoint_limit < 0)
10478         return 1;
10479       else if (ot)
10480         return -1;
10481       else if (cnt <= remote_hw_watchpoint_limit)
10482         return 1;
10483     }
10484   return -1;
10485 }
10486
10487 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10488
10489 bool
10490 remote_target::stopped_by_sw_breakpoint ()
10491 {
10492   struct thread_info *thread = inferior_thread ();
10493
10494   return (thread->priv != NULL
10495           && (get_remote_thread_info (thread)->stop_reason
10496               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10497 }
10498
10499 /* The to_supports_stopped_by_sw_breakpoint method of target
10500    remote.  */
10501
10502 bool
10503 remote_target::supports_stopped_by_sw_breakpoint ()
10504 {
10505   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10506 }
10507
10508 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10509
10510 bool
10511 remote_target::stopped_by_hw_breakpoint ()
10512 {
10513   struct thread_info *thread = inferior_thread ();
10514
10515   return (thread->priv != NULL
10516           && (get_remote_thread_info (thread)->stop_reason
10517               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10518 }
10519
10520 /* The to_supports_stopped_by_hw_breakpoint method of target
10521    remote.  */
10522
10523 bool
10524 remote_target::supports_stopped_by_hw_breakpoint ()
10525 {
10526   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10527 }
10528
10529 bool
10530 remote_target::stopped_by_watchpoint ()
10531 {
10532   struct thread_info *thread = inferior_thread ();
10533
10534   return (thread->priv != NULL
10535           && (get_remote_thread_info (thread)->stop_reason
10536               == TARGET_STOPPED_BY_WATCHPOINT));
10537 }
10538
10539 bool
10540 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10541 {
10542   struct thread_info *thread = inferior_thread ();
10543
10544   if (thread->priv != NULL
10545       && (get_remote_thread_info (thread)->stop_reason
10546           == TARGET_STOPPED_BY_WATCHPOINT))
10547     {
10548       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10549       return true;
10550     }
10551
10552   return false;
10553 }
10554
10555
10556 int
10557 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10558                                      struct bp_target_info *bp_tgt)
10559 {
10560   CORE_ADDR addr = bp_tgt->reqstd_address;
10561   struct remote_state *rs;
10562   char *p, *endbuf;
10563   char *message;
10564
10565   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10566     return -1;
10567
10568   /* Make sure the remote is pointing at the right process, if
10569      necessary.  */
10570   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10571     set_general_process ();
10572
10573   rs = get_remote_state ();
10574   p = rs->buf;
10575   endbuf = rs->buf + get_remote_packet_size ();
10576
10577   *(p++) = 'Z';
10578   *(p++) = '1';
10579   *(p++) = ',';
10580
10581   addr = remote_address_masked (addr);
10582   p += hexnumstr (p, (ULONGEST) addr);
10583   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10584
10585   if (supports_evaluation_of_breakpoint_conditions ())
10586     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10587
10588   if (can_run_breakpoint_commands ())
10589     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10590
10591   putpkt (rs->buf);
10592   getpkt (&rs->buf, &rs->buf_size, 0);
10593
10594   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10595     {
10596     case PACKET_ERROR:
10597       if (rs->buf[1] == '.')
10598         {
10599           message = strchr (rs->buf + 2, '.');
10600           if (message)
10601             error (_("Remote failure reply: %s"), message + 1);
10602         }
10603       return -1;
10604     case PACKET_UNKNOWN:
10605       return -1;
10606     case PACKET_OK:
10607       return 0;
10608     }
10609   internal_error (__FILE__, __LINE__,
10610                   _("remote_insert_hw_breakpoint: reached end of function"));
10611 }
10612
10613
10614 int
10615 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10616                                      struct bp_target_info *bp_tgt)
10617 {
10618   CORE_ADDR addr;
10619   struct remote_state *rs = get_remote_state ();
10620   char *p = rs->buf;
10621   char *endbuf = rs->buf + get_remote_packet_size ();
10622
10623   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10624     return -1;
10625
10626   /* Make sure the remote is pointing at the right process, if
10627      necessary.  */
10628   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10629     set_general_process ();
10630
10631   *(p++) = 'z';
10632   *(p++) = '1';
10633   *(p++) = ',';
10634
10635   addr = remote_address_masked (bp_tgt->placed_address);
10636   p += hexnumstr (p, (ULONGEST) addr);
10637   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10638
10639   putpkt (rs->buf);
10640   getpkt (&rs->buf, &rs->buf_size, 0);
10641
10642   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10643     {
10644     case PACKET_ERROR:
10645     case PACKET_UNKNOWN:
10646       return -1;
10647     case PACKET_OK:
10648       return 0;
10649     }
10650   internal_error (__FILE__, __LINE__,
10651                   _("remote_remove_hw_breakpoint: reached end of function"));
10652 }
10653
10654 /* Verify memory using the "qCRC:" request.  */
10655
10656 int
10657 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10658 {
10659   struct remote_state *rs = get_remote_state ();
10660   unsigned long host_crc, target_crc;
10661   char *tmp;
10662
10663   /* It doesn't make sense to use qCRC if the remote target is
10664      connected but not running.  */
10665   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10666     {
10667       enum packet_result result;
10668
10669       /* Make sure the remote is pointing at the right process.  */
10670       set_general_process ();
10671
10672       /* FIXME: assumes lma can fit into long.  */
10673       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10674                  (long) lma, (long) size);
10675       putpkt (rs->buf);
10676
10677       /* Be clever; compute the host_crc before waiting for target
10678          reply.  */
10679       host_crc = xcrc32 (data, size, 0xffffffff);
10680
10681       getpkt (&rs->buf, &rs->buf_size, 0);
10682
10683       result = packet_ok (rs->buf,
10684                           &remote_protocol_packets[PACKET_qCRC]);
10685       if (result == PACKET_ERROR)
10686         return -1;
10687       else if (result == PACKET_OK)
10688         {
10689           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10690             target_crc = target_crc * 16 + fromhex (*tmp);
10691
10692           return (host_crc == target_crc);
10693         }
10694     }
10695
10696   return simple_verify_memory (this, data, lma, size);
10697 }
10698
10699 /* compare-sections command
10700
10701    With no arguments, compares each loadable section in the exec bfd
10702    with the same memory range on the target, and reports mismatches.
10703    Useful for verifying the image on the target against the exec file.  */
10704
10705 static void
10706 compare_sections_command (const char *args, int from_tty)
10707 {
10708   asection *s;
10709   const char *sectname;
10710   bfd_size_type size;
10711   bfd_vma lma;
10712   int matched = 0;
10713   int mismatched = 0;
10714   int res;
10715   int read_only = 0;
10716
10717   if (!exec_bfd)
10718     error (_("command cannot be used without an exec file"));
10719
10720   if (args != NULL && strcmp (args, "-r") == 0)
10721     {
10722       read_only = 1;
10723       args = NULL;
10724     }
10725
10726   for (s = exec_bfd->sections; s; s = s->next)
10727     {
10728       if (!(s->flags & SEC_LOAD))
10729         continue;               /* Skip non-loadable section.  */
10730
10731       if (read_only && (s->flags & SEC_READONLY) == 0)
10732         continue;               /* Skip writeable sections */
10733
10734       size = bfd_get_section_size (s);
10735       if (size == 0)
10736         continue;               /* Skip zero-length section.  */
10737
10738       sectname = bfd_get_section_name (exec_bfd, s);
10739       if (args && strcmp (args, sectname) != 0)
10740         continue;               /* Not the section selected by user.  */
10741
10742       matched = 1;              /* Do this section.  */
10743       lma = s->lma;
10744
10745       gdb::byte_vector sectdata (size);
10746       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10747
10748       res = target_verify_memory (sectdata.data (), lma, size);
10749
10750       if (res == -1)
10751         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10752                paddress (target_gdbarch (), lma),
10753                paddress (target_gdbarch (), lma + size));
10754
10755       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10756                        paddress (target_gdbarch (), lma),
10757                        paddress (target_gdbarch (), lma + size));
10758       if (res)
10759         printf_filtered ("matched.\n");
10760       else
10761         {
10762           printf_filtered ("MIS-MATCHED!\n");
10763           mismatched++;
10764         }
10765     }
10766   if (mismatched > 0)
10767     warning (_("One or more sections of the target image does not match\n\
10768 the loaded file\n"));
10769   if (args && !matched)
10770     printf_filtered (_("No loaded section named '%s'.\n"), args);
10771 }
10772
10773 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10774    into remote target.  The number of bytes written to the remote
10775    target is returned, or -1 for error.  */
10776
10777 target_xfer_status
10778 remote_target::remote_write_qxfer (const char *object_name,
10779                                    const char *annex, const gdb_byte *writebuf,
10780                                    ULONGEST offset, LONGEST len,
10781                                    ULONGEST *xfered_len,
10782                                    struct packet_config *packet)
10783 {
10784   int i, buf_len;
10785   ULONGEST n;
10786   struct remote_state *rs = get_remote_state ();
10787   int max_size = get_memory_write_packet_size (); 
10788
10789   if (packet_config_support (packet) == PACKET_DISABLE)
10790     return TARGET_XFER_E_IO;
10791
10792   /* Insert header.  */
10793   i = snprintf (rs->buf, max_size, 
10794                 "qXfer:%s:write:%s:%s:",
10795                 object_name, annex ? annex : "",
10796                 phex_nz (offset, sizeof offset));
10797   max_size -= (i + 1);
10798
10799   /* Escape as much data as fits into rs->buf.  */
10800   buf_len = remote_escape_output 
10801     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10802
10803   if (putpkt_binary (rs->buf, i + buf_len) < 0
10804       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10805       || packet_ok (rs->buf, packet) != PACKET_OK)
10806     return TARGET_XFER_E_IO;
10807
10808   unpack_varlen_hex (rs->buf, &n);
10809
10810   *xfered_len = n;
10811   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10812 }
10813
10814 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10815    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10816    number of bytes read is returned, or 0 for EOF, or -1 for error.
10817    The number of bytes read may be less than LEN without indicating an
10818    EOF.  PACKET is checked and updated to indicate whether the remote
10819    target supports this object.  */
10820
10821 target_xfer_status
10822 remote_target::remote_read_qxfer (const char *object_name,
10823                                   const char *annex,
10824                                   gdb_byte *readbuf, ULONGEST offset,
10825                                   LONGEST len,
10826                                   ULONGEST *xfered_len,
10827                                   struct packet_config *packet)
10828 {
10829   struct remote_state *rs = get_remote_state ();
10830   LONGEST i, n, packet_len;
10831
10832   if (packet_config_support (packet) == PACKET_DISABLE)
10833     return TARGET_XFER_E_IO;
10834
10835   /* Check whether we've cached an end-of-object packet that matches
10836      this request.  */
10837   if (rs->finished_object)
10838     {
10839       if (strcmp (object_name, rs->finished_object) == 0
10840           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10841           && offset == rs->finished_offset)
10842         return TARGET_XFER_EOF;
10843
10844
10845       /* Otherwise, we're now reading something different.  Discard
10846          the cache.  */
10847       xfree (rs->finished_object);
10848       xfree (rs->finished_annex);
10849       rs->finished_object = NULL;
10850       rs->finished_annex = NULL;
10851     }
10852
10853   /* Request only enough to fit in a single packet.  The actual data
10854      may not, since we don't know how much of it will need to be escaped;
10855      the target is free to respond with slightly less data.  We subtract
10856      five to account for the response type and the protocol frame.  */
10857   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10858   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10859             object_name, annex ? annex : "",
10860             phex_nz (offset, sizeof offset),
10861             phex_nz (n, sizeof n));
10862   i = putpkt (rs->buf);
10863   if (i < 0)
10864     return TARGET_XFER_E_IO;
10865
10866   rs->buf[0] = '\0';
10867   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10868   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10869     return TARGET_XFER_E_IO;
10870
10871   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10872     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10873
10874   /* 'm' means there is (or at least might be) more data after this
10875      batch.  That does not make sense unless there's at least one byte
10876      of data in this reply.  */
10877   if (rs->buf[0] == 'm' && packet_len == 1)
10878     error (_("Remote qXfer reply contained no data."));
10879
10880   /* Got some data.  */
10881   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10882                              packet_len - 1, readbuf, n);
10883
10884   /* 'l' is an EOF marker, possibly including a final block of data,
10885      or possibly empty.  If we have the final block of a non-empty
10886      object, record this fact to bypass a subsequent partial read.  */
10887   if (rs->buf[0] == 'l' && offset + i > 0)
10888     {
10889       rs->finished_object = xstrdup (object_name);
10890       rs->finished_annex = xstrdup (annex ? annex : "");
10891       rs->finished_offset = offset + i;
10892     }
10893
10894   if (i == 0)
10895     return TARGET_XFER_EOF;
10896   else
10897     {
10898       *xfered_len = i;
10899       return TARGET_XFER_OK;
10900     }
10901 }
10902
10903 enum target_xfer_status
10904 remote_target::xfer_partial (enum target_object object,
10905                              const char *annex, gdb_byte *readbuf,
10906                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10907                              ULONGEST *xfered_len)
10908 {
10909   struct remote_state *rs;
10910   int i;
10911   char *p2;
10912   char query_type;
10913   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10914
10915   set_remote_traceframe ();
10916   set_general_thread (inferior_ptid);
10917
10918   rs = get_remote_state ();
10919
10920   /* Handle memory using the standard memory routines.  */
10921   if (object == TARGET_OBJECT_MEMORY)
10922     {
10923       /* If the remote target is connected but not running, we should
10924          pass this request down to a lower stratum (e.g. the executable
10925          file).  */
10926       if (!target_has_execution)
10927         return TARGET_XFER_EOF;
10928
10929       if (writebuf != NULL)
10930         return remote_write_bytes (offset, writebuf, len, unit_size,
10931                                    xfered_len);
10932       else
10933         return remote_read_bytes (offset, readbuf, len, unit_size,
10934                                   xfered_len);
10935     }
10936
10937   /* Handle SPU memory using qxfer packets.  */
10938   if (object == TARGET_OBJECT_SPU)
10939     {
10940       if (readbuf)
10941         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10942                                   xfered_len, &remote_protocol_packets
10943                                   [PACKET_qXfer_spu_read]);
10944       else
10945         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10946                                    xfered_len, &remote_protocol_packets
10947                                    [PACKET_qXfer_spu_write]);
10948     }
10949
10950   /* Handle extra signal info using qxfer packets.  */
10951   if (object == TARGET_OBJECT_SIGNAL_INFO)
10952     {
10953       if (readbuf)
10954         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10955                                   xfered_len, &remote_protocol_packets
10956                                   [PACKET_qXfer_siginfo_read]);
10957       else
10958         return remote_write_qxfer ("siginfo", annex,
10959                                    writebuf, offset, len, xfered_len,
10960                                    &remote_protocol_packets
10961                                    [PACKET_qXfer_siginfo_write]);
10962     }
10963
10964   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10965     {
10966       if (readbuf)
10967         return remote_read_qxfer ("statictrace", annex,
10968                                   readbuf, offset, len, xfered_len,
10969                                   &remote_protocol_packets
10970                                   [PACKET_qXfer_statictrace_read]);
10971       else
10972         return TARGET_XFER_E_IO;
10973     }
10974
10975   /* Only handle flash writes.  */
10976   if (writebuf != NULL)
10977     {
10978       switch (object)
10979         {
10980         case TARGET_OBJECT_FLASH:
10981           return remote_flash_write (offset, len, xfered_len,
10982                                      writebuf);
10983
10984         default:
10985           return TARGET_XFER_E_IO;
10986         }
10987     }
10988
10989   /* Map pre-existing objects onto letters.  DO NOT do this for new
10990      objects!!!  Instead specify new query packets.  */
10991   switch (object)
10992     {
10993     case TARGET_OBJECT_AVR:
10994       query_type = 'R';
10995       break;
10996
10997     case TARGET_OBJECT_AUXV:
10998       gdb_assert (annex == NULL);
10999       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11000                                 xfered_len,
11001                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
11002
11003     case TARGET_OBJECT_AVAILABLE_FEATURES:
11004       return remote_read_qxfer
11005         ("features", annex, readbuf, offset, len, xfered_len,
11006          &remote_protocol_packets[PACKET_qXfer_features]);
11007
11008     case TARGET_OBJECT_LIBRARIES:
11009       return remote_read_qxfer
11010         ("libraries", annex, readbuf, offset, len, xfered_len,
11011          &remote_protocol_packets[PACKET_qXfer_libraries]);
11012
11013     case TARGET_OBJECT_LIBRARIES_SVR4:
11014       return remote_read_qxfer
11015         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11016          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11017
11018     case TARGET_OBJECT_MEMORY_MAP:
11019       gdb_assert (annex == NULL);
11020       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11021                                  xfered_len,
11022                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11023
11024     case TARGET_OBJECT_OSDATA:
11025       /* Should only get here if we're connected.  */
11026       gdb_assert (rs->remote_desc);
11027       return remote_read_qxfer
11028         ("osdata", annex, readbuf, offset, len, xfered_len,
11029         &remote_protocol_packets[PACKET_qXfer_osdata]);
11030
11031     case TARGET_OBJECT_THREADS:
11032       gdb_assert (annex == NULL);
11033       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11034                                 xfered_len,
11035                                 &remote_protocol_packets[PACKET_qXfer_threads]);
11036
11037     case TARGET_OBJECT_TRACEFRAME_INFO:
11038       gdb_assert (annex == NULL);
11039       return remote_read_qxfer
11040         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11041          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11042
11043     case TARGET_OBJECT_FDPIC:
11044       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11045                                 xfered_len,
11046                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11047
11048     case TARGET_OBJECT_OPENVMS_UIB:
11049       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11050                                 xfered_len,
11051                                 &remote_protocol_packets[PACKET_qXfer_uib]);
11052
11053     case TARGET_OBJECT_BTRACE:
11054       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11055                                 xfered_len,
11056         &remote_protocol_packets[PACKET_qXfer_btrace]);
11057
11058     case TARGET_OBJECT_BTRACE_CONF:
11059       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11060                                 len, xfered_len,
11061         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11062
11063     case TARGET_OBJECT_EXEC_FILE:
11064       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11065                                 len, xfered_len,
11066         &remote_protocol_packets[PACKET_qXfer_exec_file]);
11067
11068     default:
11069       return TARGET_XFER_E_IO;
11070     }
11071
11072   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
11073      large enough let the caller deal with it.  */
11074   if (len < get_remote_packet_size ())
11075     return TARGET_XFER_E_IO;
11076   len = get_remote_packet_size ();
11077
11078   /* Except for querying the minimum buffer size, target must be open.  */
11079   if (!rs->remote_desc)
11080     error (_("remote query is only available after target open"));
11081
11082   gdb_assert (annex != NULL);
11083   gdb_assert (readbuf != NULL);
11084
11085   p2 = rs->buf;
11086   *p2++ = 'q';
11087   *p2++ = query_type;
11088
11089   /* We used one buffer char for the remote protocol q command and
11090      another for the query type.  As the remote protocol encapsulation
11091      uses 4 chars plus one extra in case we are debugging
11092      (remote_debug), we have PBUFZIZ - 7 left to pack the query
11093      string.  */
11094   i = 0;
11095   while (annex[i] && (i < (get_remote_packet_size () - 8)))
11096     {
11097       /* Bad caller may have sent forbidden characters.  */
11098       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11099       *p2++ = annex[i];
11100       i++;
11101     }
11102   *p2 = '\0';
11103   gdb_assert (annex[i] == '\0');
11104
11105   i = putpkt (rs->buf);
11106   if (i < 0)
11107     return TARGET_XFER_E_IO;
11108
11109   getpkt (&rs->buf, &rs->buf_size, 0);
11110   strcpy ((char *) readbuf, rs->buf);
11111
11112   *xfered_len = strlen ((char *) readbuf);
11113   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11114 }
11115
11116 /* Implementation of to_get_memory_xfer_limit.  */
11117
11118 ULONGEST
11119 remote_target::get_memory_xfer_limit ()
11120 {
11121   return get_memory_write_packet_size ();
11122 }
11123
11124 int
11125 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11126                               const gdb_byte *pattern, ULONGEST pattern_len,
11127                               CORE_ADDR *found_addrp)
11128 {
11129   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11130   struct remote_state *rs = get_remote_state ();
11131   int max_size = get_memory_write_packet_size ();
11132   struct packet_config *packet =
11133     &remote_protocol_packets[PACKET_qSearch_memory];
11134   /* Number of packet bytes used to encode the pattern;
11135      this could be more than PATTERN_LEN due to escape characters.  */
11136   int escaped_pattern_len;
11137   /* Amount of pattern that was encodable in the packet.  */
11138   int used_pattern_len;
11139   int i;
11140   int found;
11141   ULONGEST found_addr;
11142
11143   /* Don't go to the target if we don't have to.  This is done before
11144      checking packet_config_support to avoid the possibility that a
11145      success for this edge case means the facility works in
11146      general.  */
11147   if (pattern_len > search_space_len)
11148     return 0;
11149   if (pattern_len == 0)
11150     {
11151       *found_addrp = start_addr;
11152       return 1;
11153     }
11154
11155   /* If we already know the packet isn't supported, fall back to the simple
11156      way of searching memory.  */
11157
11158   if (packet_config_support (packet) == PACKET_DISABLE)
11159     {
11160       /* Target doesn't provided special support, fall back and use the
11161          standard support (copy memory and do the search here).  */
11162       return simple_search_memory (this, start_addr, search_space_len,
11163                                    pattern, pattern_len, found_addrp);
11164     }
11165
11166   /* Make sure the remote is pointing at the right process.  */
11167   set_general_process ();
11168
11169   /* Insert header.  */
11170   i = snprintf (rs->buf, max_size, 
11171                 "qSearch:memory:%s;%s;",
11172                 phex_nz (start_addr, addr_size),
11173                 phex_nz (search_space_len, sizeof (search_space_len)));
11174   max_size -= (i + 1);
11175
11176   /* Escape as much data as fits into rs->buf.  */
11177   escaped_pattern_len =
11178     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11179                           &used_pattern_len, max_size);
11180
11181   /* Bail if the pattern is too large.  */
11182   if (used_pattern_len != pattern_len)
11183     error (_("Pattern is too large to transmit to remote target."));
11184
11185   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11186       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11187       || packet_ok (rs->buf, packet) != PACKET_OK)
11188     {
11189       /* The request may not have worked because the command is not
11190          supported.  If so, fall back to the simple way.  */
11191       if (packet_config_support (packet) == PACKET_DISABLE)
11192         {
11193           return simple_search_memory (this, start_addr, search_space_len,
11194                                        pattern, pattern_len, found_addrp);
11195         }
11196       return -1;
11197     }
11198
11199   if (rs->buf[0] == '0')
11200     found = 0;
11201   else if (rs->buf[0] == '1')
11202     {
11203       found = 1;
11204       if (rs->buf[1] != ',')
11205         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11206       unpack_varlen_hex (rs->buf + 2, &found_addr);
11207       *found_addrp = found_addr;
11208     }
11209   else
11210     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11211
11212   return found;
11213 }
11214
11215 void
11216 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11217 {
11218   struct remote_state *rs = get_remote_state ();
11219   char *p = rs->buf;
11220
11221   if (!rs->remote_desc)
11222     error (_("remote rcmd is only available after target open"));
11223
11224   /* Send a NULL command across as an empty command.  */
11225   if (command == NULL)
11226     command = "";
11227
11228   /* The query prefix.  */
11229   strcpy (rs->buf, "qRcmd,");
11230   p = strchr (rs->buf, '\0');
11231
11232   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11233       > get_remote_packet_size ())
11234     error (_("\"monitor\" command ``%s'' is too long."), command);
11235
11236   /* Encode the actual command.  */
11237   bin2hex ((const gdb_byte *) command, p, strlen (command));
11238
11239   if (putpkt (rs->buf) < 0)
11240     error (_("Communication problem with target."));
11241
11242   /* get/display the response */
11243   while (1)
11244     {
11245       char *buf;
11246
11247       /* XXX - see also remote_get_noisy_reply().  */
11248       QUIT;                     /* Allow user to bail out with ^C.  */
11249       rs->buf[0] = '\0';
11250       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11251         { 
11252           /* Timeout.  Continue to (try to) read responses.
11253              This is better than stopping with an error, assuming the stub
11254              is still executing the (long) monitor command.
11255              If needed, the user can interrupt gdb using C-c, obtaining
11256              an effect similar to stop on timeout.  */
11257           continue;
11258         }
11259       buf = rs->buf;
11260       if (buf[0] == '\0')
11261         error (_("Target does not support this command."));
11262       if (buf[0] == 'O' && buf[1] != 'K')
11263         {
11264           remote_console_output (buf + 1); /* 'O' message from stub.  */
11265           continue;
11266         }
11267       if (strcmp (buf, "OK") == 0)
11268         break;
11269       if (strlen (buf) == 3 && buf[0] == 'E'
11270           && isdigit (buf[1]) && isdigit (buf[2]))
11271         {
11272           error (_("Protocol error with Rcmd"));
11273         }
11274       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11275         {
11276           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11277
11278           fputc_unfiltered (c, outbuf);
11279         }
11280       break;
11281     }
11282 }
11283
11284 std::vector<mem_region>
11285 remote_target::memory_map ()
11286 {
11287   std::vector<mem_region> result;
11288   gdb::optional<gdb::char_vector> text
11289     = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11290
11291   if (text)
11292     result = parse_memory_map (text->data ());
11293
11294   return result;
11295 }
11296
11297 static void
11298 packet_command (const char *args, int from_tty)
11299 {
11300   remote_target *remote = get_current_remote_target ();
11301
11302   if (remote == nullptr)
11303     error (_("command can only be used with remote target"));
11304
11305   remote->packet_command (args, from_tty);
11306 }
11307
11308 void
11309 remote_target::packet_command (const char *args, int from_tty)
11310 {
11311   if (!args)
11312     error (_("remote-packet command requires packet text as argument"));
11313
11314   puts_filtered ("sending: ");
11315   print_packet (args);
11316   puts_filtered ("\n");
11317   putpkt (args);
11318
11319   remote_state *rs = get_remote_state ();
11320
11321   getpkt (&rs->buf, &rs->buf_size, 0);
11322   puts_filtered ("received: ");
11323   print_packet (rs->buf);
11324   puts_filtered ("\n");
11325 }
11326
11327 #if 0
11328 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11329
11330 static void display_thread_info (struct gdb_ext_thread_info *info);
11331
11332 static void threadset_test_cmd (char *cmd, int tty);
11333
11334 static void threadalive_test (char *cmd, int tty);
11335
11336 static void threadlist_test_cmd (char *cmd, int tty);
11337
11338 int get_and_display_threadinfo (threadref *ref);
11339
11340 static void threadinfo_test_cmd (char *cmd, int tty);
11341
11342 static int thread_display_step (threadref *ref, void *context);
11343
11344 static void threadlist_update_test_cmd (char *cmd, int tty);
11345
11346 static void init_remote_threadtests (void);
11347
11348 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11349
11350 static void
11351 threadset_test_cmd (const char *cmd, int tty)
11352 {
11353   int sample_thread = SAMPLE_THREAD;
11354
11355   printf_filtered (_("Remote threadset test\n"));
11356   set_general_thread (sample_thread);
11357 }
11358
11359
11360 static void
11361 threadalive_test (const char *cmd, int tty)
11362 {
11363   int sample_thread = SAMPLE_THREAD;
11364   int pid = inferior_ptid.pid ();
11365   ptid_t ptid = ptid_t (pid, sample_thread, 0);
11366
11367   if (remote_thread_alive (ptid))
11368     printf_filtered ("PASS: Thread alive test\n");
11369   else
11370     printf_filtered ("FAIL: Thread alive test\n");
11371 }
11372
11373 void output_threadid (char *title, threadref *ref);
11374
11375 void
11376 output_threadid (char *title, threadref *ref)
11377 {
11378   char hexid[20];
11379
11380   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11381   hexid[16] = 0;
11382   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11383 }
11384
11385 static void
11386 threadlist_test_cmd (const char *cmd, int tty)
11387 {
11388   int startflag = 1;
11389   threadref nextthread;
11390   int done, result_count;
11391   threadref threadlist[3];
11392
11393   printf_filtered ("Remote Threadlist test\n");
11394   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11395                               &result_count, &threadlist[0]))
11396     printf_filtered ("FAIL: threadlist test\n");
11397   else
11398     {
11399       threadref *scan = threadlist;
11400       threadref *limit = scan + result_count;
11401
11402       while (scan < limit)
11403         output_threadid (" thread ", scan++);
11404     }
11405 }
11406
11407 void
11408 display_thread_info (struct gdb_ext_thread_info *info)
11409 {
11410   output_threadid ("Threadid: ", &info->threadid);
11411   printf_filtered ("Name: %s\n ", info->shortname);
11412   printf_filtered ("State: %s\n", info->display);
11413   printf_filtered ("other: %s\n\n", info->more_display);
11414 }
11415
11416 int
11417 get_and_display_threadinfo (threadref *ref)
11418 {
11419   int result;
11420   int set;
11421   struct gdb_ext_thread_info threadinfo;
11422
11423   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11424     | TAG_MOREDISPLAY | TAG_DISPLAY;
11425   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11426     display_thread_info (&threadinfo);
11427   return result;
11428 }
11429
11430 static void
11431 threadinfo_test_cmd (const char *cmd, int tty)
11432 {
11433   int athread = SAMPLE_THREAD;
11434   threadref thread;
11435   int set;
11436
11437   int_to_threadref (&thread, athread);
11438   printf_filtered ("Remote Threadinfo test\n");
11439   if (!get_and_display_threadinfo (&thread))
11440     printf_filtered ("FAIL cannot get thread info\n");
11441 }
11442
11443 static int
11444 thread_display_step (threadref *ref, void *context)
11445 {
11446   /* output_threadid(" threadstep ",ref); *//* simple test */
11447   return get_and_display_threadinfo (ref);
11448 }
11449
11450 static void
11451 threadlist_update_test_cmd (const char *cmd, int tty)
11452 {
11453   printf_filtered ("Remote Threadlist update test\n");
11454   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11455 }
11456
11457 static void
11458 init_remote_threadtests (void)
11459 {
11460   add_com ("tlist", class_obscure, threadlist_test_cmd,
11461            _("Fetch and print the remote list of "
11462              "thread identifiers, one pkt only"));
11463   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11464            _("Fetch and display info about one thread"));
11465   add_com ("tset", class_obscure, threadset_test_cmd,
11466            _("Test setting to a different thread"));
11467   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11468            _("Iterate through updating all remote thread info"));
11469   add_com ("talive", class_obscure, threadalive_test,
11470            _(" Remote thread alive test "));
11471 }
11472
11473 #endif /* 0 */
11474
11475 /* Convert a thread ID to a string.  Returns the string in a static
11476    buffer.  */
11477
11478 const char *
11479 remote_target::pid_to_str (ptid_t ptid)
11480 {
11481   static char buf[64];
11482   struct remote_state *rs = get_remote_state ();
11483
11484   if (ptid == null_ptid)
11485     return normal_pid_to_str (ptid);
11486   else if (ptid.is_pid ())
11487     {
11488       /* Printing an inferior target id.  */
11489
11490       /* When multi-process extensions are off, there's no way in the
11491          remote protocol to know the remote process id, if there's any
11492          at all.  There's one exception --- when we're connected with
11493          target extended-remote, and we manually attached to a process
11494          with "attach PID".  We don't record anywhere a flag that
11495          allows us to distinguish that case from the case of
11496          connecting with extended-remote and the stub already being
11497          attached to a process, and reporting yes to qAttached, hence
11498          no smart special casing here.  */
11499       if (!remote_multi_process_p (rs))
11500         {
11501           xsnprintf (buf, sizeof buf, "Remote target");
11502           return buf;
11503         }
11504
11505       return normal_pid_to_str (ptid);
11506     }
11507   else
11508     {
11509       if (magic_null_ptid == ptid)
11510         xsnprintf (buf, sizeof buf, "Thread <main>");
11511       else if (remote_multi_process_p (rs))
11512         if (ptid.lwp () == 0)
11513           return normal_pid_to_str (ptid);
11514         else
11515           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11516                      ptid.pid (), ptid.lwp ());
11517       else
11518         xsnprintf (buf, sizeof buf, "Thread %ld",
11519                    ptid.lwp ());
11520       return buf;
11521     }
11522 }
11523
11524 /* Get the address of the thread local variable in OBJFILE which is
11525    stored at OFFSET within the thread local storage for thread PTID.  */
11526
11527 CORE_ADDR
11528 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11529                                          CORE_ADDR offset)
11530 {
11531   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11532     {
11533       struct remote_state *rs = get_remote_state ();
11534       char *p = rs->buf;
11535       char *endp = rs->buf + get_remote_packet_size ();
11536       enum packet_result result;
11537
11538       strcpy (p, "qGetTLSAddr:");
11539       p += strlen (p);
11540       p = write_ptid (p, endp, ptid);
11541       *p++ = ',';
11542       p += hexnumstr (p, offset);
11543       *p++ = ',';
11544       p += hexnumstr (p, lm);
11545       *p++ = '\0';
11546
11547       putpkt (rs->buf);
11548       getpkt (&rs->buf, &rs->buf_size, 0);
11549       result = packet_ok (rs->buf,
11550                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11551       if (result == PACKET_OK)
11552         {
11553           ULONGEST result;
11554
11555           unpack_varlen_hex (rs->buf, &result);
11556           return result;
11557         }
11558       else if (result == PACKET_UNKNOWN)
11559         throw_error (TLS_GENERIC_ERROR,
11560                      _("Remote target doesn't support qGetTLSAddr packet"));
11561       else
11562         throw_error (TLS_GENERIC_ERROR,
11563                      _("Remote target failed to process qGetTLSAddr request"));
11564     }
11565   else
11566     throw_error (TLS_GENERIC_ERROR,
11567                  _("TLS not supported or disabled on this target"));
11568   /* Not reached.  */
11569   return 0;
11570 }
11571
11572 /* Provide thread local base, i.e. Thread Information Block address.
11573    Returns 1 if ptid is found and thread_local_base is non zero.  */
11574
11575 bool
11576 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11577 {
11578   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11579     {
11580       struct remote_state *rs = get_remote_state ();
11581       char *p = rs->buf;
11582       char *endp = rs->buf + get_remote_packet_size ();
11583       enum packet_result result;
11584
11585       strcpy (p, "qGetTIBAddr:");
11586       p += strlen (p);
11587       p = write_ptid (p, endp, ptid);
11588       *p++ = '\0';
11589
11590       putpkt (rs->buf);
11591       getpkt (&rs->buf, &rs->buf_size, 0);
11592       result = packet_ok (rs->buf,
11593                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11594       if (result == PACKET_OK)
11595         {
11596           ULONGEST result;
11597
11598           unpack_varlen_hex (rs->buf, &result);
11599           if (addr)
11600             *addr = (CORE_ADDR) result;
11601           return true;
11602         }
11603       else if (result == PACKET_UNKNOWN)
11604         error (_("Remote target doesn't support qGetTIBAddr packet"));
11605       else
11606         error (_("Remote target failed to process qGetTIBAddr request"));
11607     }
11608   else
11609     error (_("qGetTIBAddr not supported or disabled on this target"));
11610   /* Not reached.  */
11611   return false;
11612 }
11613
11614 /* Support for inferring a target description based on the current
11615    architecture and the size of a 'g' packet.  While the 'g' packet
11616    can have any size (since optional registers can be left off the
11617    end), some sizes are easily recognizable given knowledge of the
11618    approximate architecture.  */
11619
11620 struct remote_g_packet_guess
11621 {
11622   int bytes;
11623   const struct target_desc *tdesc;
11624 };
11625 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11626 DEF_VEC_O(remote_g_packet_guess_s);
11627
11628 struct remote_g_packet_data
11629 {
11630   VEC(remote_g_packet_guess_s) *guesses;
11631 };
11632
11633 static struct gdbarch_data *remote_g_packet_data_handle;
11634
11635 static void *
11636 remote_g_packet_data_init (struct obstack *obstack)
11637 {
11638   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11639 }
11640
11641 void
11642 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11643                                 const struct target_desc *tdesc)
11644 {
11645   struct remote_g_packet_data *data
11646     = ((struct remote_g_packet_data *)
11647        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11648   struct remote_g_packet_guess new_guess, *guess;
11649   int ix;
11650
11651   gdb_assert (tdesc != NULL);
11652
11653   for (ix = 0;
11654        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11655        ix++)
11656     if (guess->bytes == bytes)
11657       internal_error (__FILE__, __LINE__,
11658                       _("Duplicate g packet description added for size %d"),
11659                       bytes);
11660
11661   new_guess.bytes = bytes;
11662   new_guess.tdesc = tdesc;
11663   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11664 }
11665
11666 /* Return 1 if remote_read_description would do anything on this target
11667    and architecture, 0 otherwise.  */
11668
11669 static int
11670 remote_read_description_p (struct target_ops *target)
11671 {
11672   struct remote_g_packet_data *data
11673     = ((struct remote_g_packet_data *)
11674        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11675
11676   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11677     return 1;
11678
11679   return 0;
11680 }
11681
11682 const struct target_desc *
11683 remote_target::read_description ()
11684 {
11685   struct remote_g_packet_data *data
11686     = ((struct remote_g_packet_data *)
11687        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11688
11689   /* Do not try this during initial connection, when we do not know
11690      whether there is a running but stopped thread.  */
11691   if (!target_has_execution || inferior_ptid == null_ptid)
11692     return beneath ()->read_description ();
11693
11694   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11695     {
11696       struct remote_g_packet_guess *guess;
11697       int ix;
11698       int bytes = send_g_packet ();
11699
11700       for (ix = 0;
11701            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11702            ix++)
11703         if (guess->bytes == bytes)
11704           return guess->tdesc;
11705
11706       /* We discard the g packet.  A minor optimization would be to
11707          hold on to it, and fill the register cache once we have selected
11708          an architecture, but it's too tricky to do safely.  */
11709     }
11710
11711   return beneath ()->read_description ();
11712 }
11713
11714 /* Remote file transfer support.  This is host-initiated I/O, not
11715    target-initiated; for target-initiated, see remote-fileio.c.  */
11716
11717 /* If *LEFT is at least the length of STRING, copy STRING to
11718    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11719    decrease *LEFT.  Otherwise raise an error.  */
11720
11721 static void
11722 remote_buffer_add_string (char **buffer, int *left, const char *string)
11723 {
11724   int len = strlen (string);
11725
11726   if (len > *left)
11727     error (_("Packet too long for target."));
11728
11729   memcpy (*buffer, string, len);
11730   *buffer += len;
11731   *left -= len;
11732
11733   /* NUL-terminate the buffer as a convenience, if there is
11734      room.  */
11735   if (*left)
11736     **buffer = '\0';
11737 }
11738
11739 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11740    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11741    decrease *LEFT.  Otherwise raise an error.  */
11742
11743 static void
11744 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11745                          int len)
11746 {
11747   if (2 * len > *left)
11748     error (_("Packet too long for target."));
11749
11750   bin2hex (bytes, *buffer, len);
11751   *buffer += 2 * len;
11752   *left -= 2 * len;
11753
11754   /* NUL-terminate the buffer as a convenience, if there is
11755      room.  */
11756   if (*left)
11757     **buffer = '\0';
11758 }
11759
11760 /* If *LEFT is large enough, convert VALUE to hex and add it to
11761    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11762    decrease *LEFT.  Otherwise raise an error.  */
11763
11764 static void
11765 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11766 {
11767   int len = hexnumlen (value);
11768
11769   if (len > *left)
11770     error (_("Packet too long for target."));
11771
11772   hexnumstr (*buffer, value);
11773   *buffer += len;
11774   *left -= len;
11775
11776   /* NUL-terminate the buffer as a convenience, if there is
11777      room.  */
11778   if (*left)
11779     **buffer = '\0';
11780 }
11781
11782 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11783    value, *REMOTE_ERRNO to the remote error number or zero if none
11784    was included, and *ATTACHMENT to point to the start of the annex
11785    if any.  The length of the packet isn't needed here; there may
11786    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11787
11788    Return 0 if the packet could be parsed, -1 if it could not.  If
11789    -1 is returned, the other variables may not be initialized.  */
11790
11791 static int
11792 remote_hostio_parse_result (char *buffer, int *retcode,
11793                             int *remote_errno, char **attachment)
11794 {
11795   char *p, *p2;
11796
11797   *remote_errno = 0;
11798   *attachment = NULL;
11799
11800   if (buffer[0] != 'F')
11801     return -1;
11802
11803   errno = 0;
11804   *retcode = strtol (&buffer[1], &p, 16);
11805   if (errno != 0 || p == &buffer[1])
11806     return -1;
11807
11808   /* Check for ",errno".  */
11809   if (*p == ',')
11810     {
11811       errno = 0;
11812       *remote_errno = strtol (p + 1, &p2, 16);
11813       if (errno != 0 || p + 1 == p2)
11814         return -1;
11815       p = p2;
11816     }
11817
11818   /* Check for ";attachment".  If there is no attachment, the
11819      packet should end here.  */
11820   if (*p == ';')
11821     {
11822       *attachment = p + 1;
11823       return 0;
11824     }
11825   else if (*p == '\0')
11826     return 0;
11827   else
11828     return -1;
11829 }
11830
11831 /* Send a prepared I/O packet to the target and read its response.
11832    The prepared packet is in the global RS->BUF before this function
11833    is called, and the answer is there when we return.
11834
11835    COMMAND_BYTES is the length of the request to send, which may include
11836    binary data.  WHICH_PACKET is the packet configuration to check
11837    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11838    is set to the error number and -1 is returned.  Otherwise the value
11839    returned by the function is returned.
11840
11841    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11842    attachment is expected; an error will be reported if there's a
11843    mismatch.  If one is found, *ATTACHMENT will be set to point into
11844    the packet buffer and *ATTACHMENT_LEN will be set to the
11845    attachment's length.  */
11846
11847 int
11848 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11849                                            int *remote_errno, char **attachment,
11850                                            int *attachment_len)
11851 {
11852   struct remote_state *rs = get_remote_state ();
11853   int ret, bytes_read;
11854   char *attachment_tmp;
11855
11856   if (packet_support (which_packet) == PACKET_DISABLE)
11857     {
11858       *remote_errno = FILEIO_ENOSYS;
11859       return -1;
11860     }
11861
11862   putpkt_binary (rs->buf, command_bytes);
11863   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11864
11865   /* If it timed out, something is wrong.  Don't try to parse the
11866      buffer.  */
11867   if (bytes_read < 0)
11868     {
11869       *remote_errno = FILEIO_EINVAL;
11870       return -1;
11871     }
11872
11873   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11874     {
11875     case PACKET_ERROR:
11876       *remote_errno = FILEIO_EINVAL;
11877       return -1;
11878     case PACKET_UNKNOWN:
11879       *remote_errno = FILEIO_ENOSYS;
11880       return -1;
11881     case PACKET_OK:
11882       break;
11883     }
11884
11885   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11886                                   &attachment_tmp))
11887     {
11888       *remote_errno = FILEIO_EINVAL;
11889       return -1;
11890     }
11891
11892   /* Make sure we saw an attachment if and only if we expected one.  */
11893   if ((attachment_tmp == NULL && attachment != NULL)
11894       || (attachment_tmp != NULL && attachment == NULL))
11895     {
11896       *remote_errno = FILEIO_EINVAL;
11897       return -1;
11898     }
11899
11900   /* If an attachment was found, it must point into the packet buffer;
11901      work out how many bytes there were.  */
11902   if (attachment_tmp != NULL)
11903     {
11904       *attachment = attachment_tmp;
11905       *attachment_len = bytes_read - (*attachment - rs->buf);
11906     }
11907
11908   return ret;
11909 }
11910
11911 /* See declaration.h.  */
11912
11913 void
11914 readahead_cache::invalidate ()
11915 {
11916   this->fd = -1;
11917 }
11918
11919 /* See declaration.h.  */
11920
11921 void
11922 readahead_cache::invalidate_fd (int fd)
11923 {
11924   if (this->fd == fd)
11925     this->fd = -1;
11926 }
11927
11928 /* Set the filesystem remote_hostio functions that take FILENAME
11929    arguments will use.  Return 0 on success, or -1 if an error
11930    occurs (and set *REMOTE_ERRNO).  */
11931
11932 int
11933 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11934                                              int *remote_errno)
11935 {
11936   struct remote_state *rs = get_remote_state ();
11937   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11938   char *p = rs->buf;
11939   int left = get_remote_packet_size () - 1;
11940   char arg[9];
11941   int ret;
11942
11943   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11944     return 0;
11945
11946   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11947     return 0;
11948
11949   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11950
11951   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11952   remote_buffer_add_string (&p, &left, arg);
11953
11954   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
11955                                     remote_errno, NULL, NULL);
11956
11957   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11958     return 0;
11959
11960   if (ret == 0)
11961     rs->fs_pid = required_pid;
11962
11963   return ret;
11964 }
11965
11966 /* Implementation of to_fileio_open.  */
11967
11968 int
11969 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11970                                    int flags, int mode, int warn_if_slow,
11971                                    int *remote_errno)
11972 {
11973   struct remote_state *rs = get_remote_state ();
11974   char *p = rs->buf;
11975   int left = get_remote_packet_size () - 1;
11976
11977   if (warn_if_slow)
11978     {
11979       static int warning_issued = 0;
11980
11981       printf_unfiltered (_("Reading %s from remote target...\n"),
11982                          filename);
11983
11984       if (!warning_issued)
11985         {
11986           warning (_("File transfers from remote targets can be slow."
11987                      " Use \"set sysroot\" to access files locally"
11988                      " instead."));
11989           warning_issued = 1;
11990         }
11991     }
11992
11993   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11994     return -1;
11995
11996   remote_buffer_add_string (&p, &left, "vFile:open:");
11997
11998   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11999                            strlen (filename));
12000   remote_buffer_add_string (&p, &left, ",");
12001
12002   remote_buffer_add_int (&p, &left, flags);
12003   remote_buffer_add_string (&p, &left, ",");
12004
12005   remote_buffer_add_int (&p, &left, mode);
12006
12007   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12008                                      remote_errno, NULL, NULL);
12009 }
12010
12011 int
12012 remote_target::fileio_open (struct inferior *inf, const char *filename,
12013                             int flags, int mode, int warn_if_slow,
12014                             int *remote_errno)
12015 {
12016   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12017                              remote_errno);
12018 }
12019
12020 /* Implementation of to_fileio_pwrite.  */
12021
12022 int
12023 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12024                                      ULONGEST offset, int *remote_errno)
12025 {
12026   struct remote_state *rs = get_remote_state ();
12027   char *p = rs->buf;
12028   int left = get_remote_packet_size ();
12029   int out_len;
12030
12031   rs->readahead_cache.invalidate_fd (fd);
12032
12033   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12034
12035   remote_buffer_add_int (&p, &left, fd);
12036   remote_buffer_add_string (&p, &left, ",");
12037
12038   remote_buffer_add_int (&p, &left, offset);
12039   remote_buffer_add_string (&p, &left, ",");
12040
12041   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12042                              get_remote_packet_size () - (p - rs->buf));
12043
12044   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12045                                      remote_errno, NULL, NULL);
12046 }
12047
12048 int
12049 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12050                               ULONGEST offset, int *remote_errno)
12051 {
12052   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12053 }
12054
12055 /* Helper for the implementation of to_fileio_pread.  Read the file
12056    from the remote side with vFile:pread.  */
12057
12058 int
12059 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12060                                           ULONGEST offset, int *remote_errno)
12061 {
12062   struct remote_state *rs = get_remote_state ();
12063   char *p = rs->buf;
12064   char *attachment;
12065   int left = get_remote_packet_size ();
12066   int ret, attachment_len;
12067   int read_len;
12068
12069   remote_buffer_add_string (&p, &left, "vFile:pread:");
12070
12071   remote_buffer_add_int (&p, &left, fd);
12072   remote_buffer_add_string (&p, &left, ",");
12073
12074   remote_buffer_add_int (&p, &left, len);
12075   remote_buffer_add_string (&p, &left, ",");
12076
12077   remote_buffer_add_int (&p, &left, offset);
12078
12079   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12080                                     remote_errno, &attachment,
12081                                     &attachment_len);
12082
12083   if (ret < 0)
12084     return ret;
12085
12086   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12087                                     read_buf, len);
12088   if (read_len != ret)
12089     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12090
12091   return ret;
12092 }
12093
12094 /* See declaration.h.  */
12095
12096 int
12097 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12098                         ULONGEST offset)
12099 {
12100   if (this->fd == fd
12101       && this->offset <= offset
12102       && offset < this->offset + this->bufsize)
12103     {
12104       ULONGEST max = this->offset + this->bufsize;
12105
12106       if (offset + len > max)
12107         len = max - offset;
12108
12109       memcpy (read_buf, this->buf + offset - this->offset, len);
12110       return len;
12111     }
12112
12113   return 0;
12114 }
12115
12116 /* Implementation of to_fileio_pread.  */
12117
12118 int
12119 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12120                                     ULONGEST offset, int *remote_errno)
12121 {
12122   int ret;
12123   struct remote_state *rs = get_remote_state ();
12124   readahead_cache *cache = &rs->readahead_cache;
12125
12126   ret = cache->pread (fd, read_buf, len, offset);
12127   if (ret > 0)
12128     {
12129       cache->hit_count++;
12130
12131       if (remote_debug)
12132         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12133                             pulongest (cache->hit_count));
12134       return ret;
12135     }
12136
12137   cache->miss_count++;
12138   if (remote_debug)
12139     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12140                         pulongest (cache->miss_count));
12141
12142   cache->fd = fd;
12143   cache->offset = offset;
12144   cache->bufsize = get_remote_packet_size ();
12145   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12146
12147   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12148                                    cache->offset, remote_errno);
12149   if (ret <= 0)
12150     {
12151       cache->invalidate_fd (fd);
12152       return ret;
12153     }
12154
12155   cache->bufsize = ret;
12156   return cache->pread (fd, read_buf, len, offset);
12157 }
12158
12159 int
12160 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12161                              ULONGEST offset, int *remote_errno)
12162 {
12163   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12164 }
12165
12166 /* Implementation of to_fileio_close.  */
12167
12168 int
12169 remote_target::remote_hostio_close (int fd, int *remote_errno)
12170 {
12171   struct remote_state *rs = get_remote_state ();
12172   char *p = rs->buf;
12173   int left = get_remote_packet_size () - 1;
12174
12175   rs->readahead_cache.invalidate_fd (fd);
12176
12177   remote_buffer_add_string (&p, &left, "vFile:close:");
12178
12179   remote_buffer_add_int (&p, &left, fd);
12180
12181   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12182                                      remote_errno, NULL, NULL);
12183 }
12184
12185 int
12186 remote_target::fileio_close (int fd, int *remote_errno)
12187 {
12188   return remote_hostio_close (fd, remote_errno);
12189 }
12190
12191 /* Implementation of to_fileio_unlink.  */
12192
12193 int
12194 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12195                                      int *remote_errno)
12196 {
12197   struct remote_state *rs = get_remote_state ();
12198   char *p = rs->buf;
12199   int left = get_remote_packet_size () - 1;
12200
12201   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12202     return -1;
12203
12204   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12205
12206   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12207                            strlen (filename));
12208
12209   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12210                                      remote_errno, NULL, NULL);
12211 }
12212
12213 int
12214 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12215                               int *remote_errno)
12216 {
12217   return remote_hostio_unlink (inf, filename, remote_errno);
12218 }
12219
12220 /* Implementation of to_fileio_readlink.  */
12221
12222 gdb::optional<std::string>
12223 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12224                                 int *remote_errno)
12225 {
12226   struct remote_state *rs = get_remote_state ();
12227   char *p = rs->buf;
12228   char *attachment;
12229   int left = get_remote_packet_size ();
12230   int len, attachment_len;
12231   int read_len;
12232
12233   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12234     return {};
12235
12236   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12237
12238   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12239                            strlen (filename));
12240
12241   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12242                                     remote_errno, &attachment,
12243                                     &attachment_len);
12244
12245   if (len < 0)
12246     return {};
12247
12248   std::string ret (len, '\0');
12249
12250   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12251                                     (gdb_byte *) &ret[0], len);
12252   if (read_len != len)
12253     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12254
12255   return ret;
12256 }
12257
12258 /* Implementation of to_fileio_fstat.  */
12259
12260 int
12261 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12262 {
12263   struct remote_state *rs = get_remote_state ();
12264   char *p = rs->buf;
12265   int left = get_remote_packet_size ();
12266   int attachment_len, ret;
12267   char *attachment;
12268   struct fio_stat fst;
12269   int read_len;
12270
12271   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12272
12273   remote_buffer_add_int (&p, &left, fd);
12274
12275   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12276                                     remote_errno, &attachment,
12277                                     &attachment_len);
12278   if (ret < 0)
12279     {
12280       if (*remote_errno != FILEIO_ENOSYS)
12281         return ret;
12282
12283       /* Strictly we should return -1, ENOSYS here, but when
12284          "set sysroot remote:" was implemented in August 2008
12285          BFD's need for a stat function was sidestepped with
12286          this hack.  This was not remedied until March 2015
12287          so we retain the previous behavior to avoid breaking
12288          compatibility.
12289
12290          Note that the memset is a March 2015 addition; older
12291          GDBs set st_size *and nothing else* so the structure
12292          would have garbage in all other fields.  This might
12293          break something but retaining the previous behavior
12294          here would be just too wrong.  */
12295
12296       memset (st, 0, sizeof (struct stat));
12297       st->st_size = INT_MAX;
12298       return 0;
12299     }
12300
12301   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12302                                     (gdb_byte *) &fst, sizeof (fst));
12303
12304   if (read_len != ret)
12305     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12306
12307   if (read_len != sizeof (fst))
12308     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12309            read_len, (int) sizeof (fst));
12310
12311   remote_fileio_to_host_stat (&fst, st);
12312
12313   return 0;
12314 }
12315
12316 /* Implementation of to_filesystem_is_local.  */
12317
12318 bool
12319 remote_target::filesystem_is_local ()
12320 {
12321   /* Valgrind GDB presents itself as a remote target but works
12322      on the local filesystem: it does not implement remote get
12323      and users are not expected to set a sysroot.  To handle
12324      this case we treat the remote filesystem as local if the
12325      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12326      does not support vFile:open.  */
12327   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12328     {
12329       enum packet_support ps = packet_support (PACKET_vFile_open);
12330
12331       if (ps == PACKET_SUPPORT_UNKNOWN)
12332         {
12333           int fd, remote_errno;
12334
12335           /* Try opening a file to probe support.  The supplied
12336              filename is irrelevant, we only care about whether
12337              the stub recognizes the packet or not.  */
12338           fd = remote_hostio_open (NULL, "just probing",
12339                                    FILEIO_O_RDONLY, 0700, 0,
12340                                    &remote_errno);
12341
12342           if (fd >= 0)
12343             remote_hostio_close (fd, &remote_errno);
12344
12345           ps = packet_support (PACKET_vFile_open);
12346         }
12347
12348       if (ps == PACKET_DISABLE)
12349         {
12350           static int warning_issued = 0;
12351
12352           if (!warning_issued)
12353             {
12354               warning (_("remote target does not support file"
12355                          " transfer, attempting to access files"
12356                          " from local filesystem."));
12357               warning_issued = 1;
12358             }
12359
12360           return true;
12361         }
12362     }
12363
12364   return false;
12365 }
12366
12367 static int
12368 remote_fileio_errno_to_host (int errnum)
12369 {
12370   switch (errnum)
12371     {
12372       case FILEIO_EPERM:
12373         return EPERM;
12374       case FILEIO_ENOENT:
12375         return ENOENT;
12376       case FILEIO_EINTR:
12377         return EINTR;
12378       case FILEIO_EIO:
12379         return EIO;
12380       case FILEIO_EBADF:
12381         return EBADF;
12382       case FILEIO_EACCES:
12383         return EACCES;
12384       case FILEIO_EFAULT:
12385         return EFAULT;
12386       case FILEIO_EBUSY:
12387         return EBUSY;
12388       case FILEIO_EEXIST:
12389         return EEXIST;
12390       case FILEIO_ENODEV:
12391         return ENODEV;
12392       case FILEIO_ENOTDIR:
12393         return ENOTDIR;
12394       case FILEIO_EISDIR:
12395         return EISDIR;
12396       case FILEIO_EINVAL:
12397         return EINVAL;
12398       case FILEIO_ENFILE:
12399         return ENFILE;
12400       case FILEIO_EMFILE:
12401         return EMFILE;
12402       case FILEIO_EFBIG:
12403         return EFBIG;
12404       case FILEIO_ENOSPC:
12405         return ENOSPC;
12406       case FILEIO_ESPIPE:
12407         return ESPIPE;
12408       case FILEIO_EROFS:
12409         return EROFS;
12410       case FILEIO_ENOSYS:
12411         return ENOSYS;
12412       case FILEIO_ENAMETOOLONG:
12413         return ENAMETOOLONG;
12414     }
12415   return -1;
12416 }
12417
12418 static char *
12419 remote_hostio_error (int errnum)
12420 {
12421   int host_error = remote_fileio_errno_to_host (errnum);
12422
12423   if (host_error == -1)
12424     error (_("Unknown remote I/O error %d"), errnum);
12425   else
12426     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12427 }
12428
12429 /* A RAII wrapper around a remote file descriptor.  */
12430
12431 class scoped_remote_fd
12432 {
12433 public:
12434   scoped_remote_fd (remote_target *remote, int fd)
12435     : m_remote (remote), m_fd (fd)
12436   {
12437   }
12438
12439   ~scoped_remote_fd ()
12440   {
12441     if (m_fd != -1)
12442       {
12443         try
12444           {
12445             int remote_errno;
12446             m_remote->remote_hostio_close (m_fd, &remote_errno);
12447           }
12448         catch (...)
12449           {
12450             /* Swallow exception before it escapes the dtor.  If
12451                something goes wrong, likely the connection is gone,
12452                and there's nothing else that can be done.  */
12453           }
12454       }
12455   }
12456
12457   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12458
12459   /* Release ownership of the file descriptor, and return it.  */
12460   int release () noexcept
12461   {
12462     int fd = m_fd;
12463     m_fd = -1;
12464     return fd;
12465   }
12466
12467   /* Return the owned file descriptor.  */
12468   int get () const noexcept
12469   {
12470     return m_fd;
12471   }
12472
12473 private:
12474   /* The remote target.  */
12475   remote_target *m_remote;
12476
12477   /* The owned remote I/O file descriptor.  */
12478   int m_fd;
12479 };
12480
12481 void
12482 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12483 {
12484   remote_target *remote = get_current_remote_target ();
12485
12486   if (remote == nullptr)
12487     error (_("command can only be used with remote target"));
12488
12489   remote->remote_file_put (local_file, remote_file, from_tty);
12490 }
12491
12492 void
12493 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12494                                 int from_tty)
12495 {
12496   int retcode, remote_errno, bytes, io_size;
12497   int bytes_in_buffer;
12498   int saw_eof;
12499   ULONGEST offset;
12500
12501   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12502   if (file == NULL)
12503     perror_with_name (local_file);
12504
12505   scoped_remote_fd fd
12506     (this, remote_hostio_open (NULL,
12507                                remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12508                                              | FILEIO_O_TRUNC),
12509                                0700, 0, &remote_errno));
12510   if (fd.get () == -1)
12511     remote_hostio_error (remote_errno);
12512
12513   /* Send up to this many bytes at once.  They won't all fit in the
12514      remote packet limit, so we'll transfer slightly fewer.  */
12515   io_size = get_remote_packet_size ();
12516   gdb::byte_vector buffer (io_size);
12517
12518   bytes_in_buffer = 0;
12519   saw_eof = 0;
12520   offset = 0;
12521   while (bytes_in_buffer || !saw_eof)
12522     {
12523       if (!saw_eof)
12524         {
12525           bytes = fread (buffer.data () + bytes_in_buffer, 1,
12526                          io_size - bytes_in_buffer,
12527                          file.get ());
12528           if (bytes == 0)
12529             {
12530               if (ferror (file.get ()))
12531                 error (_("Error reading %s."), local_file);
12532               else
12533                 {
12534                   /* EOF.  Unless there is something still in the
12535                      buffer from the last iteration, we are done.  */
12536                   saw_eof = 1;
12537                   if (bytes_in_buffer == 0)
12538                     break;
12539                 }
12540             }
12541         }
12542       else
12543         bytes = 0;
12544
12545       bytes += bytes_in_buffer;
12546       bytes_in_buffer = 0;
12547
12548       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12549                                       offset, &remote_errno);
12550
12551       if (retcode < 0)
12552         remote_hostio_error (remote_errno);
12553       else if (retcode == 0)
12554         error (_("Remote write of %d bytes returned 0!"), bytes);
12555       else if (retcode < bytes)
12556         {
12557           /* Short write.  Save the rest of the read data for the next
12558              write.  */
12559           bytes_in_buffer = bytes - retcode;
12560           memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12561         }
12562
12563       offset += retcode;
12564     }
12565
12566   if (remote_hostio_close (fd.release (), &remote_errno))
12567     remote_hostio_error (remote_errno);
12568
12569   if (from_tty)
12570     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12571 }
12572
12573 void
12574 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12575 {
12576   remote_target *remote = get_current_remote_target ();
12577
12578   if (remote == nullptr)
12579     error (_("command can only be used with remote target"));
12580
12581   remote->remote_file_get (remote_file, local_file, from_tty);
12582 }
12583
12584 void
12585 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12586                                 int from_tty)
12587 {
12588   int remote_errno, bytes, io_size;
12589   ULONGEST offset;
12590
12591   scoped_remote_fd fd
12592     (this, remote_hostio_open (NULL,
12593                                remote_file, FILEIO_O_RDONLY, 0, 0,
12594                                &remote_errno));
12595   if (fd.get () == -1)
12596     remote_hostio_error (remote_errno);
12597
12598   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12599   if (file == NULL)
12600     perror_with_name (local_file);
12601
12602   /* Send up to this many bytes at once.  They won't all fit in the
12603      remote packet limit, so we'll transfer slightly fewer.  */
12604   io_size = get_remote_packet_size ();
12605   gdb::byte_vector buffer (io_size);
12606
12607   offset = 0;
12608   while (1)
12609     {
12610       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12611                                    &remote_errno);
12612       if (bytes == 0)
12613         /* Success, but no bytes, means end-of-file.  */
12614         break;
12615       if (bytes == -1)
12616         remote_hostio_error (remote_errno);
12617
12618       offset += bytes;
12619
12620       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12621       if (bytes == 0)
12622         perror_with_name (local_file);
12623     }
12624
12625   if (remote_hostio_close (fd.release (), &remote_errno))
12626     remote_hostio_error (remote_errno);
12627
12628   if (from_tty)
12629     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12630 }
12631
12632 void
12633 remote_file_delete (const char *remote_file, int from_tty)
12634 {
12635   remote_target *remote = get_current_remote_target ();
12636
12637   if (remote == nullptr)
12638     error (_("command can only be used with remote target"));
12639
12640   remote->remote_file_delete (remote_file, from_tty);
12641 }
12642
12643 void
12644 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12645 {
12646   int retcode, remote_errno;
12647
12648   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12649   if (retcode == -1)
12650     remote_hostio_error (remote_errno);
12651
12652   if (from_tty)
12653     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12654 }
12655
12656 static void
12657 remote_put_command (const char *args, int from_tty)
12658 {
12659   if (args == NULL)
12660     error_no_arg (_("file to put"));
12661
12662   gdb_argv argv (args);
12663   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12664     error (_("Invalid parameters to remote put"));
12665
12666   remote_file_put (argv[0], argv[1], from_tty);
12667 }
12668
12669 static void
12670 remote_get_command (const char *args, int from_tty)
12671 {
12672   if (args == NULL)
12673     error_no_arg (_("file to get"));
12674
12675   gdb_argv argv (args);
12676   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12677     error (_("Invalid parameters to remote get"));
12678
12679   remote_file_get (argv[0], argv[1], from_tty);
12680 }
12681
12682 static void
12683 remote_delete_command (const char *args, int from_tty)
12684 {
12685   if (args == NULL)
12686     error_no_arg (_("file to delete"));
12687
12688   gdb_argv argv (args);
12689   if (argv[0] == NULL || argv[1] != NULL)
12690     error (_("Invalid parameters to remote delete"));
12691
12692   remote_file_delete (argv[0], from_tty);
12693 }
12694
12695 static void
12696 remote_command (const char *args, int from_tty)
12697 {
12698   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12699 }
12700
12701 bool
12702 remote_target::can_execute_reverse ()
12703 {
12704   if (packet_support (PACKET_bs) == PACKET_ENABLE
12705       || packet_support (PACKET_bc) == PACKET_ENABLE)
12706     return true;
12707   else
12708     return false;
12709 }
12710
12711 bool
12712 remote_target::supports_non_stop ()
12713 {
12714   return true;
12715 }
12716
12717 bool
12718 remote_target::supports_disable_randomization ()
12719 {
12720   /* Only supported in extended mode.  */
12721   return false;
12722 }
12723
12724 bool
12725 remote_target::supports_multi_process ()
12726 {
12727   struct remote_state *rs = get_remote_state ();
12728
12729   return remote_multi_process_p (rs);
12730 }
12731
12732 static int
12733 remote_supports_cond_tracepoints ()
12734 {
12735   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12736 }
12737
12738 bool
12739 remote_target::supports_evaluation_of_breakpoint_conditions ()
12740 {
12741   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12742 }
12743
12744 static int
12745 remote_supports_fast_tracepoints ()
12746 {
12747   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12748 }
12749
12750 static int
12751 remote_supports_static_tracepoints ()
12752 {
12753   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12754 }
12755
12756 static int
12757 remote_supports_install_in_trace ()
12758 {
12759   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12760 }
12761
12762 bool
12763 remote_target::supports_enable_disable_tracepoint ()
12764 {
12765   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12766           == PACKET_ENABLE);
12767 }
12768
12769 bool
12770 remote_target::supports_string_tracing ()
12771 {
12772   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12773 }
12774
12775 bool
12776 remote_target::can_run_breakpoint_commands ()
12777 {
12778   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12779 }
12780
12781 void
12782 remote_target::trace_init ()
12783 {
12784   struct remote_state *rs = get_remote_state ();
12785
12786   putpkt ("QTinit");
12787   remote_get_noisy_reply ();
12788   if (strcmp (rs->buf, "OK") != 0)
12789     error (_("Target does not support this command."));
12790 }
12791
12792 /* Recursive routine to walk through command list including loops, and
12793    download packets for each command.  */
12794
12795 void
12796 remote_target::remote_download_command_source (int num, ULONGEST addr,
12797                                                struct command_line *cmds)
12798 {
12799   struct remote_state *rs = get_remote_state ();
12800   struct command_line *cmd;
12801
12802   for (cmd = cmds; cmd; cmd = cmd->next)
12803     {
12804       QUIT;     /* Allow user to bail out with ^C.  */
12805       strcpy (rs->buf, "QTDPsrc:");
12806       encode_source_string (num, addr, "cmd", cmd->line,
12807                             rs->buf + strlen (rs->buf),
12808                             rs->buf_size - strlen (rs->buf));
12809       putpkt (rs->buf);
12810       remote_get_noisy_reply ();
12811       if (strcmp (rs->buf, "OK"))
12812         warning (_("Target does not support source download."));
12813
12814       if (cmd->control_type == while_control
12815           || cmd->control_type == while_stepping_control)
12816         {
12817           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12818
12819           QUIT; /* Allow user to bail out with ^C.  */
12820           strcpy (rs->buf, "QTDPsrc:");
12821           encode_source_string (num, addr, "cmd", "end",
12822                                 rs->buf + strlen (rs->buf),
12823                                 rs->buf_size - strlen (rs->buf));
12824           putpkt (rs->buf);
12825           remote_get_noisy_reply ();
12826           if (strcmp (rs->buf, "OK"))
12827             warning (_("Target does not support source download."));
12828         }
12829     }
12830 }
12831
12832 void
12833 remote_target::download_tracepoint (struct bp_location *loc)
12834 {
12835   CORE_ADDR tpaddr;
12836   char addrbuf[40];
12837   std::vector<std::string> tdp_actions;
12838   std::vector<std::string> stepping_actions;
12839   char *pkt;
12840   struct breakpoint *b = loc->owner;
12841   struct tracepoint *t = (struct tracepoint *) b;
12842   struct remote_state *rs = get_remote_state ();
12843   int ret;
12844   const char *err_msg = _("Tracepoint packet too large for target.");
12845   size_t size_left;
12846
12847   /* We use a buffer other than rs->buf because we'll build strings
12848      across multiple statements, and other statements in between could
12849      modify rs->buf.  */
12850   gdb::char_vector buf (get_remote_packet_size ());
12851
12852   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12853
12854   tpaddr = loc->address;
12855   sprintf_vma (addrbuf, tpaddr);
12856   ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
12857                   b->number, addrbuf, /* address */
12858                   (b->enable_state == bp_enabled ? 'E' : 'D'),
12859                   t->step_count, t->pass_count);
12860
12861   if (ret < 0 || ret >= buf.size ())
12862     error ("%s", err_msg);
12863
12864   /* Fast tracepoints are mostly handled by the target, but we can
12865      tell the target how big of an instruction block should be moved
12866      around.  */
12867   if (b->type == bp_fast_tracepoint)
12868     {
12869       /* Only test for support at download time; we may not know
12870          target capabilities at definition time.  */
12871       if (remote_supports_fast_tracepoints ())
12872         {
12873           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12874                                                 NULL))
12875             {
12876               size_left = buf.size () - strlen (buf.data ());
12877               ret = snprintf (buf.data () + strlen (buf.data ()),
12878                               size_left, ":F%x",
12879                               gdb_insn_length (loc->gdbarch, tpaddr));
12880
12881               if (ret < 0 || ret >= size_left)
12882                 error ("%s", err_msg);
12883             }
12884           else
12885             /* If it passed validation at definition but fails now,
12886                something is very wrong.  */
12887             internal_error (__FILE__, __LINE__,
12888                             _("Fast tracepoint not "
12889                               "valid during download"));
12890         }
12891       else
12892         /* Fast tracepoints are functionally identical to regular
12893            tracepoints, so don't take lack of support as a reason to
12894            give up on the trace run.  */
12895         warning (_("Target does not support fast tracepoints, "
12896                    "downloading %d as regular tracepoint"), b->number);
12897     }
12898   else if (b->type == bp_static_tracepoint)
12899     {
12900       /* Only test for support at download time; we may not know
12901          target capabilities at definition time.  */
12902       if (remote_supports_static_tracepoints ())
12903         {
12904           struct static_tracepoint_marker marker;
12905
12906           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12907             {
12908               size_left = buf.size () - strlen (buf.data ());
12909               ret = snprintf (buf.data () + strlen (buf.data ()),
12910                               size_left, ":S");
12911
12912               if (ret < 0 || ret >= size_left)
12913                 error ("%s", err_msg);
12914             }
12915           else
12916             error (_("Static tracepoint not valid during download"));
12917         }
12918       else
12919         /* Fast tracepoints are functionally identical to regular
12920            tracepoints, so don't take lack of support as a reason
12921            to give up on the trace run.  */
12922         error (_("Target does not support static tracepoints"));
12923     }
12924   /* If the tracepoint has a conditional, make it into an agent
12925      expression and append to the definition.  */
12926   if (loc->cond)
12927     {
12928       /* Only test support at download time, we may not know target
12929          capabilities at definition time.  */
12930       if (remote_supports_cond_tracepoints ())
12931         {
12932           agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
12933                                                    loc->cond.get ());
12934
12935           size_left = buf.size () - strlen (buf.data ());
12936
12937           ret = snprintf (buf.data () + strlen (buf.data ()),
12938                           size_left, ":X%x,", aexpr->len);
12939
12940           if (ret < 0 || ret >= size_left)
12941             error ("%s", err_msg);
12942
12943           size_left = buf.size () - strlen (buf.data ());
12944
12945           /* Two bytes to encode each aexpr byte, plus the terminating
12946              null byte.  */
12947           if (aexpr->len * 2 + 1 > size_left)
12948             error ("%s", err_msg);
12949
12950           pkt = buf.data () + strlen (buf.data ());
12951
12952           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12953             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12954           *pkt = '\0';
12955         }
12956       else
12957         warning (_("Target does not support conditional tracepoints, "
12958                    "ignoring tp %d cond"), b->number);
12959     }
12960
12961   if (b->commands || *default_collect)
12962     {
12963       size_left = buf.size () - strlen (buf.data ());
12964
12965       ret = snprintf (buf.data () + strlen (buf.data ()),
12966                       size_left, "-");
12967
12968       if (ret < 0 || ret >= size_left)
12969         error ("%s", err_msg);
12970     }
12971
12972   putpkt (buf.data ());
12973   remote_get_noisy_reply ();
12974   if (strcmp (rs->buf, "OK"))
12975     error (_("Target does not support tracepoints."));
12976
12977   /* do_single_steps (t); */
12978   for (auto action_it = tdp_actions.begin ();
12979        action_it != tdp_actions.end (); action_it++)
12980     {
12981       QUIT;     /* Allow user to bail out with ^C.  */
12982
12983       bool has_more = ((action_it + 1) != tdp_actions.end ()
12984                        || !stepping_actions.empty ());
12985
12986       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
12987                       b->number, addrbuf, /* address */
12988                       action_it->c_str (),
12989                       has_more ? '-' : 0);
12990
12991       if (ret < 0 || ret >= buf.size ())
12992         error ("%s", err_msg);
12993
12994       putpkt (buf.data ());
12995       remote_get_noisy_reply ();
12996       if (strcmp (rs->buf, "OK"))
12997         error (_("Error on target while setting tracepoints."));
12998     }
12999
13000   for (auto action_it = stepping_actions.begin ();
13001        action_it != stepping_actions.end (); action_it++)
13002     {
13003       QUIT;     /* Allow user to bail out with ^C.  */
13004
13005       bool is_first = action_it == stepping_actions.begin ();
13006       bool has_more = (action_it + 1) != stepping_actions.end ();
13007
13008       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
13009                       b->number, addrbuf, /* address */
13010                       is_first ? "S" : "",
13011                       action_it->c_str (),
13012                       has_more ? "-" : "");
13013
13014       if (ret < 0 || ret >= buf.size ())
13015         error ("%s", err_msg);
13016
13017       putpkt (buf.data ());
13018       remote_get_noisy_reply ();
13019       if (strcmp (rs->buf, "OK"))
13020         error (_("Error on target while setting tracepoints."));
13021     }
13022
13023   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13024     {
13025       if (b->location != NULL)
13026         {
13027           ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13028
13029           if (ret < 0 || ret >= buf.size ())
13030             error ("%s", err_msg);
13031
13032           encode_source_string (b->number, loc->address, "at",
13033                                 event_location_to_string (b->location.get ()),
13034                                 buf.data () + strlen (buf.data ()),
13035                                 buf.size () - strlen (buf.data ()));
13036           putpkt (buf.data ());
13037           remote_get_noisy_reply ();
13038           if (strcmp (rs->buf, "OK"))
13039             warning (_("Target does not support source download."));
13040         }
13041       if (b->cond_string)
13042         {
13043           ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
13044
13045           if (ret < 0 || ret >= buf.size ())
13046             error ("%s", err_msg);
13047
13048           encode_source_string (b->number, loc->address,
13049                                 "cond", b->cond_string,
13050                                 buf.data () + strlen (buf.data ()),
13051                                 buf.size () - strlen (buf.data ()));
13052           putpkt (buf.data ());
13053           remote_get_noisy_reply ();
13054           if (strcmp (rs->buf, "OK"))
13055             warning (_("Target does not support source download."));
13056         }
13057       remote_download_command_source (b->number, loc->address,
13058                                       breakpoint_commands (b));
13059     }
13060 }
13061
13062 bool
13063 remote_target::can_download_tracepoint ()
13064 {
13065   struct remote_state *rs = get_remote_state ();
13066   struct trace_status *ts;
13067   int status;
13068
13069   /* Don't try to install tracepoints until we've relocated our
13070      symbols, and fetched and merged the target's tracepoint list with
13071      ours.  */
13072   if (rs->starting_up)
13073     return false;
13074
13075   ts = current_trace_status ();
13076   status = get_trace_status (ts);
13077
13078   if (status == -1 || !ts->running_known || !ts->running)
13079     return false;
13080
13081   /* If we are in a tracing experiment, but remote stub doesn't support
13082      installing tracepoint in trace, we have to return.  */
13083   if (!remote_supports_install_in_trace ())
13084     return false;
13085
13086   return true;
13087 }
13088
13089
13090 void
13091 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13092 {
13093   struct remote_state *rs = get_remote_state ();
13094   char *p;
13095
13096   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
13097              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13098              tsv.builtin);
13099   p = rs->buf + strlen (rs->buf);
13100   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
13101     error (_("Trace state variable name too long for tsv definition packet"));
13102   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13103   *p++ = '\0';
13104   putpkt (rs->buf);
13105   remote_get_noisy_reply ();
13106   if (*rs->buf == '\0')
13107     error (_("Target does not support this command."));
13108   if (strcmp (rs->buf, "OK") != 0)
13109     error (_("Error on target while downloading trace state variable."));
13110 }
13111
13112 void
13113 remote_target::enable_tracepoint (struct bp_location *location)
13114 {
13115   struct remote_state *rs = get_remote_state ();
13116   char addr_buf[40];
13117
13118   sprintf_vma (addr_buf, location->address);
13119   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13120              location->owner->number, addr_buf);
13121   putpkt (rs->buf);
13122   remote_get_noisy_reply ();
13123   if (*rs->buf == '\0')
13124     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13125   if (strcmp (rs->buf, "OK") != 0)
13126     error (_("Error on target while enabling tracepoint."));
13127 }
13128
13129 void
13130 remote_target::disable_tracepoint (struct bp_location *location)
13131 {
13132   struct remote_state *rs = get_remote_state ();
13133   char addr_buf[40];
13134
13135   sprintf_vma (addr_buf, location->address);
13136   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13137              location->owner->number, addr_buf);
13138   putpkt (rs->buf);
13139   remote_get_noisy_reply ();
13140   if (*rs->buf == '\0')
13141     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13142   if (strcmp (rs->buf, "OK") != 0)
13143     error (_("Error on target while disabling tracepoint."));
13144 }
13145
13146 void
13147 remote_target::trace_set_readonly_regions ()
13148 {
13149   asection *s;
13150   bfd *abfd = NULL;
13151   bfd_size_type size;
13152   bfd_vma vma;
13153   int anysecs = 0;
13154   int offset = 0;
13155
13156   if (!exec_bfd)
13157     return;                     /* No information to give.  */
13158
13159   struct remote_state *rs = get_remote_state ();
13160
13161   strcpy (rs->buf, "QTro");
13162   offset = strlen (rs->buf);
13163   for (s = exec_bfd->sections; s; s = s->next)
13164     {
13165       char tmp1[40], tmp2[40];
13166       int sec_length;
13167
13168       if ((s->flags & SEC_LOAD) == 0 ||
13169       /*  (s->flags & SEC_CODE) == 0 || */
13170           (s->flags & SEC_READONLY) == 0)
13171         continue;
13172
13173       anysecs = 1;
13174       vma = bfd_get_section_vma (abfd, s);
13175       size = bfd_get_section_size (s);
13176       sprintf_vma (tmp1, vma);
13177       sprintf_vma (tmp2, vma + size);
13178       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13179       if (offset + sec_length + 1 > rs->buf_size)
13180         {
13181           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13182             warning (_("\
13183 Too many sections for read-only sections definition packet."));
13184           break;
13185         }
13186       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13187                  tmp1, tmp2);
13188       offset += sec_length;
13189     }
13190   if (anysecs)
13191     {
13192       putpkt (rs->buf);
13193       getpkt (&rs->buf, &rs->buf_size, 0);
13194     }
13195 }
13196
13197 void
13198 remote_target::trace_start ()
13199 {
13200   struct remote_state *rs = get_remote_state ();
13201
13202   putpkt ("QTStart");
13203   remote_get_noisy_reply ();
13204   if (*rs->buf == '\0')
13205     error (_("Target does not support this command."));
13206   if (strcmp (rs->buf, "OK") != 0)
13207     error (_("Bogus reply from target: %s"), rs->buf);
13208 }
13209
13210 int
13211 remote_target::get_trace_status (struct trace_status *ts)
13212 {
13213   /* Initialize it just to avoid a GCC false warning.  */
13214   char *p = NULL;
13215   /* FIXME we need to get register block size some other way.  */
13216   extern int trace_regblock_size;
13217   enum packet_result result;
13218   struct remote_state *rs = get_remote_state ();
13219
13220   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13221     return -1;
13222
13223   trace_regblock_size
13224     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13225
13226   putpkt ("qTStatus");
13227
13228   TRY
13229     {
13230       p = remote_get_noisy_reply ();
13231     }
13232   CATCH (ex, RETURN_MASK_ERROR)
13233     {
13234       if (ex.error != TARGET_CLOSE_ERROR)
13235         {
13236           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13237           return -1;
13238         }
13239       throw_exception (ex);
13240     }
13241   END_CATCH
13242
13243   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13244
13245   /* If the remote target doesn't do tracing, flag it.  */
13246   if (result == PACKET_UNKNOWN)
13247     return -1;
13248
13249   /* We're working with a live target.  */
13250   ts->filename = NULL;
13251
13252   if (*p++ != 'T')
13253     error (_("Bogus trace status reply from target: %s"), rs->buf);
13254
13255   /* Function 'parse_trace_status' sets default value of each field of
13256      'ts' at first, so we don't have to do it here.  */
13257   parse_trace_status (p, ts);
13258
13259   return ts->running;
13260 }
13261
13262 void
13263 remote_target::get_tracepoint_status (struct breakpoint *bp,
13264                                       struct uploaded_tp *utp)
13265 {
13266   struct remote_state *rs = get_remote_state ();
13267   char *reply;
13268   struct bp_location *loc;
13269   struct tracepoint *tp = (struct tracepoint *) bp;
13270   size_t size = get_remote_packet_size ();
13271
13272   if (tp)
13273     {
13274       tp->hit_count = 0;
13275       tp->traceframe_usage = 0;
13276       for (loc = tp->loc; loc; loc = loc->next)
13277         {
13278           /* If the tracepoint was never downloaded, don't go asking for
13279              any status.  */
13280           if (tp->number_on_target == 0)
13281             continue;
13282           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13283                      phex_nz (loc->address, 0));
13284           putpkt (rs->buf);
13285           reply = remote_get_noisy_reply ();
13286           if (reply && *reply)
13287             {
13288               if (*reply == 'V')
13289                 parse_tracepoint_status (reply + 1, bp, utp);
13290             }
13291         }
13292     }
13293   else if (utp)
13294     {
13295       utp->hit_count = 0;
13296       utp->traceframe_usage = 0;
13297       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13298                  phex_nz (utp->addr, 0));
13299       putpkt (rs->buf);
13300       reply = remote_get_noisy_reply ();
13301       if (reply && *reply)
13302         {
13303           if (*reply == 'V')
13304             parse_tracepoint_status (reply + 1, bp, utp);
13305         }
13306     }
13307 }
13308
13309 void
13310 remote_target::trace_stop ()
13311 {
13312   struct remote_state *rs = get_remote_state ();
13313
13314   putpkt ("QTStop");
13315   remote_get_noisy_reply ();
13316   if (*rs->buf == '\0')
13317     error (_("Target does not support this command."));
13318   if (strcmp (rs->buf, "OK") != 0)
13319     error (_("Bogus reply from target: %s"), rs->buf);
13320 }
13321
13322 int
13323 remote_target::trace_find (enum trace_find_type type, int num,
13324                            CORE_ADDR addr1, CORE_ADDR addr2,
13325                            int *tpp)
13326 {
13327   struct remote_state *rs = get_remote_state ();
13328   char *endbuf = rs->buf + get_remote_packet_size ();
13329   char *p, *reply;
13330   int target_frameno = -1, target_tracept = -1;
13331
13332   /* Lookups other than by absolute frame number depend on the current
13333      trace selected, so make sure it is correct on the remote end
13334      first.  */
13335   if (type != tfind_number)
13336     set_remote_traceframe ();
13337
13338   p = rs->buf;
13339   strcpy (p, "QTFrame:");
13340   p = strchr (p, '\0');
13341   switch (type)
13342     {
13343     case tfind_number:
13344       xsnprintf (p, endbuf - p, "%x", num);
13345       break;
13346     case tfind_pc:
13347       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13348       break;
13349     case tfind_tp:
13350       xsnprintf (p, endbuf - p, "tdp:%x", num);
13351       break;
13352     case tfind_range:
13353       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13354                  phex_nz (addr2, 0));
13355       break;
13356     case tfind_outside:
13357       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13358                  phex_nz (addr2, 0));
13359       break;
13360     default:
13361       error (_("Unknown trace find type %d"), type);
13362     }
13363
13364   putpkt (rs->buf);
13365   reply = remote_get_noisy_reply ();
13366   if (*reply == '\0')
13367     error (_("Target does not support this command."));
13368
13369   while (reply && *reply)
13370     switch (*reply)
13371       {
13372       case 'F':
13373         p = ++reply;
13374         target_frameno = (int) strtol (p, &reply, 16);
13375         if (reply == p)
13376           error (_("Unable to parse trace frame number"));
13377         /* Don't update our remote traceframe number cache on failure
13378            to select a remote traceframe.  */
13379         if (target_frameno == -1)
13380           return -1;
13381         break;
13382       case 'T':
13383         p = ++reply;
13384         target_tracept = (int) strtol (p, &reply, 16);
13385         if (reply == p)
13386           error (_("Unable to parse tracepoint number"));
13387         break;
13388       case 'O':         /* "OK"? */
13389         if (reply[1] == 'K' && reply[2] == '\0')
13390           reply += 2;
13391         else
13392           error (_("Bogus reply from target: %s"), reply);
13393         break;
13394       default:
13395         error (_("Bogus reply from target: %s"), reply);
13396       }
13397   if (tpp)
13398     *tpp = target_tracept;
13399
13400   rs->remote_traceframe_number = target_frameno;
13401   return target_frameno;
13402 }
13403
13404 bool
13405 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13406 {
13407   struct remote_state *rs = get_remote_state ();
13408   char *reply;
13409   ULONGEST uval;
13410
13411   set_remote_traceframe ();
13412
13413   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13414   putpkt (rs->buf);
13415   reply = remote_get_noisy_reply ();
13416   if (reply && *reply)
13417     {
13418       if (*reply == 'V')
13419         {
13420           unpack_varlen_hex (reply + 1, &uval);
13421           *val = (LONGEST) uval;
13422           return true;
13423         }
13424     }
13425   return false;
13426 }
13427
13428 int
13429 remote_target::save_trace_data (const char *filename)
13430 {
13431   struct remote_state *rs = get_remote_state ();
13432   char *p, *reply;
13433
13434   p = rs->buf;
13435   strcpy (p, "QTSave:");
13436   p += strlen (p);
13437   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13438     error (_("Remote file name too long for trace save packet"));
13439   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13440   *p++ = '\0';
13441   putpkt (rs->buf);
13442   reply = remote_get_noisy_reply ();
13443   if (*reply == '\0')
13444     error (_("Target does not support this command."));
13445   if (strcmp (reply, "OK") != 0)
13446     error (_("Bogus reply from target: %s"), reply);
13447   return 0;
13448 }
13449
13450 /* This is basically a memory transfer, but needs to be its own packet
13451    because we don't know how the target actually organizes its trace
13452    memory, plus we want to be able to ask for as much as possible, but
13453    not be unhappy if we don't get as much as we ask for.  */
13454
13455 LONGEST
13456 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13457 {
13458   struct remote_state *rs = get_remote_state ();
13459   char *reply;
13460   char *p;
13461   int rslt;
13462
13463   p = rs->buf;
13464   strcpy (p, "qTBuffer:");
13465   p += strlen (p);
13466   p += hexnumstr (p, offset);
13467   *p++ = ',';
13468   p += hexnumstr (p, len);
13469   *p++ = '\0';
13470
13471   putpkt (rs->buf);
13472   reply = remote_get_noisy_reply ();
13473   if (reply && *reply)
13474     {
13475       /* 'l' by itself means we're at the end of the buffer and
13476          there is nothing more to get.  */
13477       if (*reply == 'l')
13478         return 0;
13479
13480       /* Convert the reply into binary.  Limit the number of bytes to
13481          convert according to our passed-in buffer size, rather than
13482          what was returned in the packet; if the target is
13483          unexpectedly generous and gives us a bigger reply than we
13484          asked for, we don't want to crash.  */
13485       rslt = hex2bin (reply, buf, len);
13486       return rslt;
13487     }
13488
13489   /* Something went wrong, flag as an error.  */
13490   return -1;
13491 }
13492
13493 void
13494 remote_target::set_disconnected_tracing (int val)
13495 {
13496   struct remote_state *rs = get_remote_state ();
13497
13498   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13499     {
13500       char *reply;
13501
13502       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13503       putpkt (rs->buf);
13504       reply = remote_get_noisy_reply ();
13505       if (*reply == '\0')
13506         error (_("Target does not support this command."));
13507       if (strcmp (reply, "OK") != 0)
13508         error (_("Bogus reply from target: %s"), reply);
13509     }
13510   else if (val)
13511     warning (_("Target does not support disconnected tracing."));
13512 }
13513
13514 int
13515 remote_target::core_of_thread (ptid_t ptid)
13516 {
13517   struct thread_info *info = find_thread_ptid (ptid);
13518
13519   if (info != NULL && info->priv != NULL)
13520     return get_remote_thread_info (info)->core;
13521
13522   return -1;
13523 }
13524
13525 void
13526 remote_target::set_circular_trace_buffer (int val)
13527 {
13528   struct remote_state *rs = get_remote_state ();
13529   char *reply;
13530
13531   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13532   putpkt (rs->buf);
13533   reply = remote_get_noisy_reply ();
13534   if (*reply == '\0')
13535     error (_("Target does not support this command."));
13536   if (strcmp (reply, "OK") != 0)
13537     error (_("Bogus reply from target: %s"), reply);
13538 }
13539
13540 traceframe_info_up
13541 remote_target::traceframe_info ()
13542 {
13543   gdb::optional<gdb::char_vector> text
13544     = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13545                             NULL);
13546   if (text)
13547     return parse_traceframe_info (text->data ());
13548
13549   return NULL;
13550 }
13551
13552 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13553    instruction on which a fast tracepoint may be placed.  Returns -1
13554    if the packet is not supported, and 0 if the minimum instruction
13555    length is unknown.  */
13556
13557 int
13558 remote_target::get_min_fast_tracepoint_insn_len ()
13559 {
13560   struct remote_state *rs = get_remote_state ();
13561   char *reply;
13562
13563   /* If we're not debugging a process yet, the IPA can't be
13564      loaded.  */
13565   if (!target_has_execution)
13566     return 0;
13567
13568   /* Make sure the remote is pointing at the right process.  */
13569   set_general_process ();
13570
13571   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13572   putpkt (rs->buf);
13573   reply = remote_get_noisy_reply ();
13574   if (*reply == '\0')
13575     return -1;
13576   else
13577     {
13578       ULONGEST min_insn_len;
13579
13580       unpack_varlen_hex (reply, &min_insn_len);
13581
13582       return (int) min_insn_len;
13583     }
13584 }
13585
13586 void
13587 remote_target::set_trace_buffer_size (LONGEST val)
13588 {
13589   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13590     {
13591       struct remote_state *rs = get_remote_state ();
13592       char *buf = rs->buf;
13593       char *endbuf = rs->buf + get_remote_packet_size ();
13594       enum packet_result result;
13595
13596       gdb_assert (val >= 0 || val == -1);
13597       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13598       /* Send -1 as literal "-1" to avoid host size dependency.  */
13599       if (val < 0)
13600         {
13601           *buf++ = '-';
13602           buf += hexnumstr (buf, (ULONGEST) -val);
13603         }
13604       else
13605         buf += hexnumstr (buf, (ULONGEST) val);
13606
13607       putpkt (rs->buf);
13608       remote_get_noisy_reply ();
13609       result = packet_ok (rs->buf,
13610                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13611
13612       if (result != PACKET_OK)
13613         warning (_("Bogus reply from target: %s"), rs->buf);
13614     }
13615 }
13616
13617 bool
13618 remote_target::set_trace_notes (const char *user, const char *notes,
13619                                 const char *stop_notes)
13620 {
13621   struct remote_state *rs = get_remote_state ();
13622   char *reply;
13623   char *buf = rs->buf;
13624   char *endbuf = rs->buf + get_remote_packet_size ();
13625   int nbytes;
13626
13627   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13628   if (user)
13629     {
13630       buf += xsnprintf (buf, endbuf - buf, "user:");
13631       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13632       buf += 2 * nbytes;
13633       *buf++ = ';';
13634     }
13635   if (notes)
13636     {
13637       buf += xsnprintf (buf, endbuf - buf, "notes:");
13638       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13639       buf += 2 * nbytes;
13640       *buf++ = ';';
13641     }
13642   if (stop_notes)
13643     {
13644       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13645       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13646       buf += 2 * nbytes;
13647       *buf++ = ';';
13648     }
13649   /* Ensure the buffer is terminated.  */
13650   *buf = '\0';
13651
13652   putpkt (rs->buf);
13653   reply = remote_get_noisy_reply ();
13654   if (*reply == '\0')
13655     return false;
13656
13657   if (strcmp (reply, "OK") != 0)
13658     error (_("Bogus reply from target: %s"), reply);
13659
13660   return true;
13661 }
13662
13663 bool
13664 remote_target::use_agent (bool use)
13665 {
13666   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13667     {
13668       struct remote_state *rs = get_remote_state ();
13669
13670       /* If the stub supports QAgent.  */
13671       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13672       putpkt (rs->buf);
13673       getpkt (&rs->buf, &rs->buf_size, 0);
13674
13675       if (strcmp (rs->buf, "OK") == 0)
13676         {
13677           ::use_agent = use;
13678           return true;
13679         }
13680     }
13681
13682   return false;
13683 }
13684
13685 bool
13686 remote_target::can_use_agent ()
13687 {
13688   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13689 }
13690
13691 struct btrace_target_info
13692 {
13693   /* The ptid of the traced thread.  */
13694   ptid_t ptid;
13695
13696   /* The obtained branch trace configuration.  */
13697   struct btrace_config conf;
13698 };
13699
13700 /* Reset our idea of our target's btrace configuration.  */
13701
13702 static void
13703 remote_btrace_reset (remote_state *rs)
13704 {
13705   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13706 }
13707
13708 /* Synchronize the configuration with the target.  */
13709
13710 void
13711 remote_target::btrace_sync_conf (const btrace_config *conf)
13712 {
13713   struct packet_config *packet;
13714   struct remote_state *rs;
13715   char *buf, *pos, *endbuf;
13716
13717   rs = get_remote_state ();
13718   buf = rs->buf;
13719   endbuf = buf + get_remote_packet_size ();
13720
13721   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13722   if (packet_config_support (packet) == PACKET_ENABLE
13723       && conf->bts.size != rs->btrace_config.bts.size)
13724     {
13725       pos = buf;
13726       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13727                         conf->bts.size);
13728
13729       putpkt (buf);
13730       getpkt (&buf, &rs->buf_size, 0);
13731
13732       if (packet_ok (buf, packet) == PACKET_ERROR)
13733         {
13734           if (buf[0] == 'E' && buf[1] == '.')
13735             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13736           else
13737             error (_("Failed to configure the BTS buffer size."));
13738         }
13739
13740       rs->btrace_config.bts.size = conf->bts.size;
13741     }
13742
13743   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13744   if (packet_config_support (packet) == PACKET_ENABLE
13745       && conf->pt.size != rs->btrace_config.pt.size)
13746     {
13747       pos = buf;
13748       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13749                         conf->pt.size);
13750
13751       putpkt (buf);
13752       getpkt (&buf, &rs->buf_size, 0);
13753
13754       if (packet_ok (buf, packet) == PACKET_ERROR)
13755         {
13756           if (buf[0] == 'E' && buf[1] == '.')
13757             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13758           else
13759             error (_("Failed to configure the trace buffer size."));
13760         }
13761
13762       rs->btrace_config.pt.size = conf->pt.size;
13763     }
13764 }
13765
13766 /* Read the current thread's btrace configuration from the target and
13767    store it into CONF.  */
13768
13769 static void
13770 btrace_read_config (struct btrace_config *conf)
13771 {
13772   gdb::optional<gdb::char_vector> xml
13773     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13774   if (xml)
13775     parse_xml_btrace_conf (conf, xml->data ());
13776 }
13777
13778 /* Maybe reopen target btrace.  */
13779
13780 void
13781 remote_target::remote_btrace_maybe_reopen ()
13782 {
13783   struct remote_state *rs = get_remote_state ();
13784   struct thread_info *tp;
13785   int btrace_target_pushed = 0;
13786 #if !defined (HAVE_LIBIPT)
13787   int warned = 0;
13788 #endif
13789
13790   scoped_restore_current_thread restore_thread;
13791
13792   ALL_NON_EXITED_THREADS (tp)
13793     {
13794       set_general_thread (tp->ptid);
13795
13796       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13797       btrace_read_config (&rs->btrace_config);
13798
13799       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13800         continue;
13801
13802 #if !defined (HAVE_LIBIPT)
13803       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13804         {
13805           if (!warned)
13806             {
13807               warned = 1;
13808               warning (_("Target is recording using Intel Processor Trace "
13809                          "but support was disabled at compile time."));
13810             }
13811
13812           continue;
13813         }
13814 #endif /* !defined (HAVE_LIBIPT) */
13815
13816       /* Push target, once, but before anything else happens.  This way our
13817          changes to the threads will be cleaned up by unpushing the target
13818          in case btrace_read_config () throws.  */
13819       if (!btrace_target_pushed)
13820         {
13821           btrace_target_pushed = 1;
13822           record_btrace_push_target ();
13823           printf_filtered (_("Target is recording using %s.\n"),
13824                            btrace_format_string (rs->btrace_config.format));
13825         }
13826
13827       tp->btrace.target = XCNEW (struct btrace_target_info);
13828       tp->btrace.target->ptid = tp->ptid;
13829       tp->btrace.target->conf = rs->btrace_config;
13830     }
13831 }
13832
13833 /* Enable branch tracing.  */
13834
13835 struct btrace_target_info *
13836 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13837 {
13838   struct btrace_target_info *tinfo = NULL;
13839   struct packet_config *packet = NULL;
13840   struct remote_state *rs = get_remote_state ();
13841   char *buf = rs->buf;
13842   char *endbuf = rs->buf + get_remote_packet_size ();
13843
13844   switch (conf->format)
13845     {
13846       case BTRACE_FORMAT_BTS:
13847         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13848         break;
13849
13850       case BTRACE_FORMAT_PT:
13851         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13852         break;
13853     }
13854
13855   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13856     error (_("Target does not support branch tracing."));
13857
13858   btrace_sync_conf (conf);
13859
13860   set_general_thread (ptid);
13861
13862   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13863   putpkt (rs->buf);
13864   getpkt (&rs->buf, &rs->buf_size, 0);
13865
13866   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13867     {
13868       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13869         error (_("Could not enable branch tracing for %s: %s"),
13870                target_pid_to_str (ptid), rs->buf + 2);
13871       else
13872         error (_("Could not enable branch tracing for %s."),
13873                target_pid_to_str (ptid));
13874     }
13875
13876   tinfo = XCNEW (struct btrace_target_info);
13877   tinfo->ptid = ptid;
13878
13879   /* If we fail to read the configuration, we lose some information, but the
13880      tracing itself is not impacted.  */
13881   TRY
13882     {
13883       btrace_read_config (&tinfo->conf);
13884     }
13885   CATCH (err, RETURN_MASK_ERROR)
13886     {
13887       if (err.message != NULL)
13888         warning ("%s", err.message);
13889     }
13890   END_CATCH
13891
13892   return tinfo;
13893 }
13894
13895 /* Disable branch tracing.  */
13896
13897 void
13898 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13899 {
13900   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13901   struct remote_state *rs = get_remote_state ();
13902   char *buf = rs->buf;
13903   char *endbuf = rs->buf + get_remote_packet_size ();
13904
13905   if (packet_config_support (packet) != PACKET_ENABLE)
13906     error (_("Target does not support branch tracing."));
13907
13908   set_general_thread (tinfo->ptid);
13909
13910   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13911   putpkt (rs->buf);
13912   getpkt (&rs->buf, &rs->buf_size, 0);
13913
13914   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13915     {
13916       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13917         error (_("Could not disable branch tracing for %s: %s"),
13918                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13919       else
13920         error (_("Could not disable branch tracing for %s."),
13921                target_pid_to_str (tinfo->ptid));
13922     }
13923
13924   xfree (tinfo);
13925 }
13926
13927 /* Teardown branch tracing.  */
13928
13929 void
13930 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13931 {
13932   /* We must not talk to the target during teardown.  */
13933   xfree (tinfo);
13934 }
13935
13936 /* Read the branch trace.  */
13937
13938 enum btrace_error
13939 remote_target::read_btrace (struct btrace_data *btrace,
13940                             struct btrace_target_info *tinfo,
13941                             enum btrace_read_type type)
13942 {
13943   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13944   const char *annex;
13945
13946   if (packet_config_support (packet) != PACKET_ENABLE)
13947     error (_("Target does not support branch tracing."));
13948
13949 #if !defined(HAVE_LIBEXPAT)
13950   error (_("Cannot process branch tracing result. XML parsing not supported."));
13951 #endif
13952
13953   switch (type)
13954     {
13955     case BTRACE_READ_ALL:
13956       annex = "all";
13957       break;
13958     case BTRACE_READ_NEW:
13959       annex = "new";
13960       break;
13961     case BTRACE_READ_DELTA:
13962       annex = "delta";
13963       break;
13964     default:
13965       internal_error (__FILE__, __LINE__,
13966                       _("Bad branch tracing read type: %u."),
13967                       (unsigned int) type);
13968     }
13969
13970   gdb::optional<gdb::char_vector> xml
13971     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13972   if (!xml)
13973     return BTRACE_ERR_UNKNOWN;
13974
13975   parse_xml_btrace (btrace, xml->data ());
13976
13977   return BTRACE_ERR_NONE;
13978 }
13979
13980 const struct btrace_config *
13981 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13982 {
13983   return &tinfo->conf;
13984 }
13985
13986 bool
13987 remote_target::augmented_libraries_svr4_read ()
13988 {
13989   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13990           == PACKET_ENABLE);
13991 }
13992
13993 /* Implementation of to_load.  */
13994
13995 void
13996 remote_target::load (const char *name, int from_tty)
13997 {
13998   generic_load (name, from_tty);
13999 }
14000
14001 /* Accepts an integer PID; returns a string representing a file that
14002    can be opened on the remote side to get the symbols for the child
14003    process.  Returns NULL if the operation is not supported.  */
14004
14005 char *
14006 remote_target::pid_to_exec_file (int pid)
14007 {
14008   static gdb::optional<gdb::char_vector> filename;
14009   struct inferior *inf;
14010   char *annex = NULL;
14011
14012   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14013     return NULL;
14014
14015   inf = find_inferior_pid (pid);
14016   if (inf == NULL)
14017     internal_error (__FILE__, __LINE__,
14018                     _("not currently attached to process %d"), pid);
14019
14020   if (!inf->fake_pid_p)
14021     {
14022       const int annex_size = 9;
14023
14024       annex = (char *) alloca (annex_size);
14025       xsnprintf (annex, annex_size, "%x", pid);
14026     }
14027
14028   filename = target_read_stralloc (current_top_target (),
14029                                    TARGET_OBJECT_EXEC_FILE, annex);
14030
14031   return filename ? filename->data () : nullptr;
14032 }
14033
14034 /* Implement the to_can_do_single_step target_ops method.  */
14035
14036 int
14037 remote_target::can_do_single_step ()
14038 {
14039   /* We can only tell whether target supports single step or not by
14040      supported s and S vCont actions if the stub supports vContSupported
14041      feature.  If the stub doesn't support vContSupported feature,
14042      we have conservatively to think target doesn't supports single
14043      step.  */
14044   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14045     {
14046       struct remote_state *rs = get_remote_state ();
14047
14048       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14049         remote_vcont_probe ();
14050
14051       return rs->supports_vCont.s && rs->supports_vCont.S;
14052     }
14053   else
14054     return 0;
14055 }
14056
14057 /* Implementation of the to_execution_direction method for the remote
14058    target.  */
14059
14060 enum exec_direction_kind
14061 remote_target::execution_direction ()
14062 {
14063   struct remote_state *rs = get_remote_state ();
14064
14065   return rs->last_resume_exec_dir;
14066 }
14067
14068 /* Return pointer to the thread_info struct which corresponds to
14069    THREAD_HANDLE (having length HANDLE_LEN).  */
14070
14071 thread_info *
14072 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14073                                              int handle_len,
14074                                              inferior *inf)
14075 {
14076   struct thread_info *tp;
14077
14078   ALL_NON_EXITED_THREADS (tp)
14079     {
14080       remote_thread_info *priv = get_remote_thread_info (tp);
14081
14082       if (tp->inf == inf && priv != NULL)
14083         {
14084           if (handle_len != priv->thread_handle.size ())
14085             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14086                    handle_len, priv->thread_handle.size ());
14087           if (memcmp (thread_handle, priv->thread_handle.data (),
14088                       handle_len) == 0)
14089             return tp;
14090         }
14091     }
14092
14093   return NULL;
14094 }
14095
14096 bool
14097 remote_target::can_async_p ()
14098 {
14099   struct remote_state *rs = get_remote_state ();
14100
14101   /* We don't go async if the user has explicitly prevented it with the
14102      "maint set target-async" command.  */
14103   if (!target_async_permitted)
14104     return false;
14105
14106   /* We're async whenever the serial device is.  */
14107   return serial_can_async_p (rs->remote_desc);
14108 }
14109
14110 bool
14111 remote_target::is_async_p ()
14112 {
14113   struct remote_state *rs = get_remote_state ();
14114
14115   if (!target_async_permitted)
14116     /* We only enable async when the user specifically asks for it.  */
14117     return false;
14118
14119   /* We're async whenever the serial device is.  */
14120   return serial_is_async_p (rs->remote_desc);
14121 }
14122
14123 /* Pass the SERIAL event on and up to the client.  One day this code
14124    will be able to delay notifying the client of an event until the
14125    point where an entire packet has been received.  */
14126
14127 static serial_event_ftype remote_async_serial_handler;
14128
14129 static void
14130 remote_async_serial_handler (struct serial *scb, void *context)
14131 {
14132   /* Don't propogate error information up to the client.  Instead let
14133      the client find out about the error by querying the target.  */
14134   inferior_event_handler (INF_REG_EVENT, NULL);
14135 }
14136
14137 static void
14138 remote_async_inferior_event_handler (gdb_client_data data)
14139 {
14140   inferior_event_handler (INF_REG_EVENT, data);
14141 }
14142
14143 void
14144 remote_target::async (int enable)
14145 {
14146   struct remote_state *rs = get_remote_state ();
14147
14148   if (enable)
14149     {
14150       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14151
14152       /* If there are pending events in the stop reply queue tell the
14153          event loop to process them.  */
14154       if (!rs->stop_reply_queue.empty ())
14155         mark_async_event_handler (rs->remote_async_inferior_event_token);
14156       /* For simplicity, below we clear the pending events token
14157          without remembering whether it is marked, so here we always
14158          mark it.  If there's actually no pending notification to
14159          process, this ends up being a no-op (other than a spurious
14160          event-loop wakeup).  */
14161       if (target_is_non_stop_p ())
14162         mark_async_event_handler (rs->notif_state->get_pending_events_token);
14163     }
14164   else
14165     {
14166       serial_async (rs->remote_desc, NULL, NULL);
14167       /* If the core is disabling async, it doesn't want to be
14168          disturbed with target events.  Clear all async event sources
14169          too.  */
14170       clear_async_event_handler (rs->remote_async_inferior_event_token);
14171       if (target_is_non_stop_p ())
14172         clear_async_event_handler (rs->notif_state->get_pending_events_token);
14173     }
14174 }
14175
14176 /* Implementation of the to_thread_events method.  */
14177
14178 void
14179 remote_target::thread_events (int enable)
14180 {
14181   struct remote_state *rs = get_remote_state ();
14182   size_t size = get_remote_packet_size ();
14183
14184   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14185     return;
14186
14187   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14188   putpkt (rs->buf);
14189   getpkt (&rs->buf, &rs->buf_size, 0);
14190
14191   switch (packet_ok (rs->buf,
14192                      &remote_protocol_packets[PACKET_QThreadEvents]))
14193     {
14194     case PACKET_OK:
14195       if (strcmp (rs->buf, "OK") != 0)
14196         error (_("Remote refused setting thread events: %s"), rs->buf);
14197       break;
14198     case PACKET_ERROR:
14199       warning (_("Remote failure reply: %s"), rs->buf);
14200       break;
14201     case PACKET_UNKNOWN:
14202       break;
14203     }
14204 }
14205
14206 static void
14207 set_remote_cmd (const char *args, int from_tty)
14208 {
14209   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14210 }
14211
14212 static void
14213 show_remote_cmd (const char *args, int from_tty)
14214 {
14215   /* We can't just use cmd_show_list here, because we want to skip
14216      the redundant "show remote Z-packet" and the legacy aliases.  */
14217   struct cmd_list_element *list = remote_show_cmdlist;
14218   struct ui_out *uiout = current_uiout;
14219
14220   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14221   for (; list != NULL; list = list->next)
14222     if (strcmp (list->name, "Z-packet") == 0)
14223       continue;
14224     else if (list->type == not_set_cmd)
14225       /* Alias commands are exactly like the original, except they
14226          don't have the normal type.  */
14227       continue;
14228     else
14229       {
14230         ui_out_emit_tuple option_emitter (uiout, "option");
14231
14232         uiout->field_string ("name", list->name);
14233         uiout->text (":  ");
14234         if (list->type == show_cmd)
14235           do_show_command (NULL, from_tty, list);
14236         else
14237           cmd_func (list, NULL, from_tty);
14238       }
14239 }
14240
14241
14242 /* Function to be called whenever a new objfile (shlib) is detected.  */
14243 static void
14244 remote_new_objfile (struct objfile *objfile)
14245 {
14246   remote_target *remote = get_current_remote_target ();
14247
14248   if (remote != NULL)                   /* Have a remote connection.  */
14249     remote->remote_check_symbols ();
14250 }
14251
14252 /* Pull all the tracepoints defined on the target and create local
14253    data structures representing them.  We don't want to create real
14254    tracepoints yet, we don't want to mess up the user's existing
14255    collection.  */
14256   
14257 int
14258 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14259 {
14260   struct remote_state *rs = get_remote_state ();
14261   char *p;
14262
14263   /* Ask for a first packet of tracepoint definition.  */
14264   putpkt ("qTfP");
14265   getpkt (&rs->buf, &rs->buf_size, 0);
14266   p = rs->buf;
14267   while (*p && *p != 'l')
14268     {
14269       parse_tracepoint_definition (p, utpp);
14270       /* Ask for another packet of tracepoint definition.  */
14271       putpkt ("qTsP");
14272       getpkt (&rs->buf, &rs->buf_size, 0);
14273       p = rs->buf;
14274     }
14275   return 0;
14276 }
14277
14278 int
14279 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14280 {
14281   struct remote_state *rs = get_remote_state ();
14282   char *p;
14283
14284   /* Ask for a first packet of variable definition.  */
14285   putpkt ("qTfV");
14286   getpkt (&rs->buf, &rs->buf_size, 0);
14287   p = rs->buf;
14288   while (*p && *p != 'l')
14289     {
14290       parse_tsv_definition (p, utsvp);
14291       /* Ask for another packet of variable definition.  */
14292       putpkt ("qTsV");
14293       getpkt (&rs->buf, &rs->buf_size, 0);
14294       p = rs->buf;
14295     }
14296   return 0;
14297 }
14298
14299 /* The "set/show range-stepping" show hook.  */
14300
14301 static void
14302 show_range_stepping (struct ui_file *file, int from_tty,
14303                      struct cmd_list_element *c,
14304                      const char *value)
14305 {
14306   fprintf_filtered (file,
14307                     _("Debugger's willingness to use range stepping "
14308                       "is %s.\n"), value);
14309 }
14310
14311 /* Return true if the vCont;r action is supported by the remote
14312    stub.  */
14313
14314 bool
14315 remote_target::vcont_r_supported ()
14316 {
14317   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14318     remote_vcont_probe ();
14319
14320   return (packet_support (PACKET_vCont) == PACKET_ENABLE
14321           && get_remote_state ()->supports_vCont.r);
14322 }
14323
14324 /* The "set/show range-stepping" set hook.  */
14325
14326 static void
14327 set_range_stepping (const char *ignore_args, int from_tty,
14328                     struct cmd_list_element *c)
14329 {
14330   /* When enabling, check whether range stepping is actually supported
14331      by the target, and warn if not.  */
14332   if (use_range_stepping)
14333     {
14334       remote_target *remote = get_current_remote_target ();
14335       if (remote == NULL
14336           || !remote->vcont_r_supported ())
14337         warning (_("Range stepping is not supported by the current target"));
14338     }
14339 }
14340
14341 void
14342 _initialize_remote (void)
14343 {
14344   struct cmd_list_element *cmd;
14345   const char *cmd_name;
14346
14347   /* architecture specific data */
14348   remote_g_packet_data_handle =
14349     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14350
14351   remote_pspace_data
14352     = register_program_space_data_with_cleanup (NULL,
14353                                                 remote_pspace_data_cleanup);
14354
14355   add_target (remote_target_info, remote_target::open);
14356   add_target (extended_remote_target_info, extended_remote_target::open);
14357
14358   /* Hook into new objfile notification.  */
14359   gdb::observers::new_objfile.attach (remote_new_objfile);
14360
14361 #if 0
14362   init_remote_threadtests ();
14363 #endif
14364
14365   /* set/show remote ...  */
14366
14367   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14368 Remote protocol specific variables\n\
14369 Configure various remote-protocol specific variables such as\n\
14370 the packets being used"),
14371                   &remote_set_cmdlist, "set remote ",
14372                   0 /* allow-unknown */, &setlist);
14373   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14374 Remote protocol specific variables\n\
14375 Configure various remote-protocol specific variables such as\n\
14376 the packets being used"),
14377                   &remote_show_cmdlist, "show remote ",
14378                   0 /* allow-unknown */, &showlist);
14379
14380   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14381 Compare section data on target to the exec file.\n\
14382 Argument is a single section name (default: all loaded sections).\n\
14383 To compare only read-only loaded sections, specify the -r option."),
14384            &cmdlist);
14385
14386   add_cmd ("packet", class_maintenance, packet_command, _("\
14387 Send an arbitrary packet to a remote target.\n\
14388    maintenance packet TEXT\n\
14389 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14390 this command sends the string TEXT to the inferior, and displays the\n\
14391 response packet.  GDB supplies the initial `$' character, and the\n\
14392 terminating `#' character and checksum."),
14393            &maintenancelist);
14394
14395   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14396 Set whether to send break if interrupted."), _("\
14397 Show whether to send break if interrupted."), _("\
14398 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14399                            set_remotebreak, show_remotebreak,
14400                            &setlist, &showlist);
14401   cmd_name = "remotebreak";
14402   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14403   deprecate_cmd (cmd, "set remote interrupt-sequence");
14404   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14405   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14406   deprecate_cmd (cmd, "show remote interrupt-sequence");
14407
14408   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14409                         interrupt_sequence_modes, &interrupt_sequence_mode,
14410                         _("\
14411 Set interrupt sequence to remote target."), _("\
14412 Show interrupt sequence to remote target."), _("\
14413 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14414                         NULL, show_interrupt_sequence,
14415                         &remote_set_cmdlist,
14416                         &remote_show_cmdlist);
14417
14418   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14419                            &interrupt_on_connect, _("\
14420 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14421 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14422 If set, interrupt sequence is sent to remote target."),
14423                            NULL, NULL,
14424                            &remote_set_cmdlist, &remote_show_cmdlist);
14425
14426   /* Install commands for configuring memory read/write packets.  */
14427
14428   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14429 Set the maximum number of bytes per memory write packet (deprecated)."),
14430            &setlist);
14431   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14432 Show the maximum number of bytes per memory write packet (deprecated)."),
14433            &showlist);
14434   add_cmd ("memory-write-packet-size", no_class,
14435            set_memory_write_packet_size, _("\
14436 Set the maximum number of bytes per memory-write packet.\n\
14437 Specify the number of bytes in a packet or 0 (zero) for the\n\
14438 default packet size.  The actual limit is further reduced\n\
14439 dependent on the target.  Specify ``fixed'' to disable the\n\
14440 further restriction and ``limit'' to enable that restriction."),
14441            &remote_set_cmdlist);
14442   add_cmd ("memory-read-packet-size", no_class,
14443            set_memory_read_packet_size, _("\
14444 Set the maximum number of bytes per memory-read packet.\n\
14445 Specify the number of bytes in a packet or 0 (zero) for the\n\
14446 default packet size.  The actual limit is further reduced\n\
14447 dependent on the target.  Specify ``fixed'' to disable the\n\
14448 further restriction and ``limit'' to enable that restriction."),
14449            &remote_set_cmdlist);
14450   add_cmd ("memory-write-packet-size", no_class,
14451            show_memory_write_packet_size,
14452            _("Show the maximum number of bytes per memory-write packet."),
14453            &remote_show_cmdlist);
14454   add_cmd ("memory-read-packet-size", no_class,
14455            show_memory_read_packet_size,
14456            _("Show the maximum number of bytes per memory-read packet."),
14457            &remote_show_cmdlist);
14458
14459   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14460                             &remote_hw_watchpoint_limit, _("\
14461 Set the maximum number of target hardware watchpoints."), _("\
14462 Show the maximum number of target hardware watchpoints."), _("\
14463 Specify \"unlimited\" for unlimited hardware watchpoints."),
14464                             NULL, show_hardware_watchpoint_limit,
14465                             &remote_set_cmdlist,
14466                             &remote_show_cmdlist);
14467   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14468                             no_class,
14469                             &remote_hw_watchpoint_length_limit, _("\
14470 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14471 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14472 Specify \"unlimited\" to allow watchpoints of unlimited size."),
14473                             NULL, show_hardware_watchpoint_length_limit,
14474                             &remote_set_cmdlist, &remote_show_cmdlist);
14475   add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
14476                             &remote_hw_breakpoint_limit, _("\
14477 Set the maximum number of target hardware breakpoints."), _("\
14478 Show the maximum number of target hardware breakpoints."), _("\
14479 Specify \"unlimited\" for unlimited hardware breakpoints."),
14480                             NULL, show_hardware_breakpoint_limit,
14481                             &remote_set_cmdlist, &remote_show_cmdlist);
14482
14483   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14484                              &remote_address_size, _("\
14485 Set the maximum size of the address (in bits) in a memory packet."), _("\
14486 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14487                              NULL,
14488                              NULL, /* FIXME: i18n: */
14489                              &setlist, &showlist);
14490
14491   init_all_packet_configs ();
14492
14493   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14494                          "X", "binary-download", 1);
14495
14496   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14497                          "vCont", "verbose-resume", 0);
14498
14499   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14500                          "QPassSignals", "pass-signals", 0);
14501
14502   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14503                          "QCatchSyscalls", "catch-syscalls", 0);
14504
14505   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14506                          "QProgramSignals", "program-signals", 0);
14507
14508   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14509                          "QSetWorkingDir", "set-working-dir", 0);
14510
14511   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14512                          "QStartupWithShell", "startup-with-shell", 0);
14513
14514   add_packet_config_cmd (&remote_protocol_packets
14515                          [PACKET_QEnvironmentHexEncoded],
14516                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14517                          0);
14518
14519   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14520                          "QEnvironmentReset", "environment-reset",
14521                          0);
14522
14523   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14524                          "QEnvironmentUnset", "environment-unset",
14525                          0);
14526
14527   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14528                          "qSymbol", "symbol-lookup", 0);
14529
14530   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14531                          "P", "set-register", 1);
14532
14533   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14534                          "p", "fetch-register", 1);
14535
14536   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14537                          "Z0", "software-breakpoint", 0);
14538
14539   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14540                          "Z1", "hardware-breakpoint", 0);
14541
14542   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14543                          "Z2", "write-watchpoint", 0);
14544
14545   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14546                          "Z3", "read-watchpoint", 0);
14547
14548   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14549                          "Z4", "access-watchpoint", 0);
14550
14551   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14552                          "qXfer:auxv:read", "read-aux-vector", 0);
14553
14554   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14555                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14556
14557   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14558                          "qXfer:features:read", "target-features", 0);
14559
14560   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14561                          "qXfer:libraries:read", "library-info", 0);
14562
14563   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14564                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14565
14566   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14567                          "qXfer:memory-map:read", "memory-map", 0);
14568
14569   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14570                          "qXfer:spu:read", "read-spu-object", 0);
14571
14572   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14573                          "qXfer:spu:write", "write-spu-object", 0);
14574
14575   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14576                         "qXfer:osdata:read", "osdata", 0);
14577
14578   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14579                          "qXfer:threads:read", "threads", 0);
14580
14581   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14582                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14583
14584   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14585                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14586
14587   add_packet_config_cmd
14588     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14589      "qXfer:traceframe-info:read", "traceframe-info", 0);
14590
14591   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14592                          "qXfer:uib:read", "unwind-info-block", 0);
14593
14594   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14595                          "qGetTLSAddr", "get-thread-local-storage-address",
14596                          0);
14597
14598   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14599                          "qGetTIBAddr", "get-thread-information-block-address",
14600                          0);
14601
14602   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14603                          "bc", "reverse-continue", 0);
14604
14605   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14606                          "bs", "reverse-step", 0);
14607
14608   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14609                          "qSupported", "supported-packets", 0);
14610
14611   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14612                          "qSearch:memory", "search-memory", 0);
14613
14614   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14615                          "qTStatus", "trace-status", 0);
14616
14617   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14618                          "vFile:setfs", "hostio-setfs", 0);
14619
14620   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14621                          "vFile:open", "hostio-open", 0);
14622
14623   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14624                          "vFile:pread", "hostio-pread", 0);
14625
14626   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14627                          "vFile:pwrite", "hostio-pwrite", 0);
14628
14629   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14630                          "vFile:close", "hostio-close", 0);
14631
14632   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14633                          "vFile:unlink", "hostio-unlink", 0);
14634
14635   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14636                          "vFile:readlink", "hostio-readlink", 0);
14637
14638   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14639                          "vFile:fstat", "hostio-fstat", 0);
14640
14641   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14642                          "vAttach", "attach", 0);
14643
14644   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14645                          "vRun", "run", 0);
14646
14647   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14648                          "QStartNoAckMode", "noack", 0);
14649
14650   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14651                          "vKill", "kill", 0);
14652
14653   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14654                          "qAttached", "query-attached", 0);
14655
14656   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14657                          "ConditionalTracepoints",
14658                          "conditional-tracepoints", 0);
14659
14660   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14661                          "ConditionalBreakpoints",
14662                          "conditional-breakpoints", 0);
14663
14664   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14665                          "BreakpointCommands",
14666                          "breakpoint-commands", 0);
14667
14668   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14669                          "FastTracepoints", "fast-tracepoints", 0);
14670
14671   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14672                          "TracepointSource", "TracepointSource", 0);
14673
14674   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14675                          "QAllow", "allow", 0);
14676
14677   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14678                          "StaticTracepoints", "static-tracepoints", 0);
14679
14680   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14681                          "InstallInTrace", "install-in-trace", 0);
14682
14683   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14684                          "qXfer:statictrace:read", "read-sdata-object", 0);
14685
14686   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14687                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14688
14689   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14690                          "QDisableRandomization", "disable-randomization", 0);
14691
14692   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14693                          "QAgent", "agent", 0);
14694
14695   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14696                          "QTBuffer:size", "trace-buffer-size", 0);
14697
14698   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14699        "Qbtrace:off", "disable-btrace", 0);
14700
14701   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14702        "Qbtrace:bts", "enable-btrace-bts", 0);
14703
14704   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14705        "Qbtrace:pt", "enable-btrace-pt", 0);
14706
14707   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14708        "qXfer:btrace", "read-btrace", 0);
14709
14710   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14711        "qXfer:btrace-conf", "read-btrace-conf", 0);
14712
14713   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14714        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14715
14716   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14717        "multiprocess-feature", "multiprocess-feature", 0);
14718
14719   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14720                          "swbreak-feature", "swbreak-feature", 0);
14721
14722   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14723                          "hwbreak-feature", "hwbreak-feature", 0);
14724
14725   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14726                          "fork-event-feature", "fork-event-feature", 0);
14727
14728   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14729                          "vfork-event-feature", "vfork-event-feature", 0);
14730
14731   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14732        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14733
14734   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14735                          "vContSupported", "verbose-resume-supported", 0);
14736
14737   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14738                          "exec-event-feature", "exec-event-feature", 0);
14739
14740   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14741                          "vCtrlC", "ctrl-c", 0);
14742
14743   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14744                          "QThreadEvents", "thread-events", 0);
14745
14746   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14747                          "N stop reply", "no-resumed-stop-reply", 0);
14748
14749   /* Assert that we've registered "set remote foo-packet" commands
14750      for all packet configs.  */
14751   {
14752     int i;
14753
14754     for (i = 0; i < PACKET_MAX; i++)
14755       {
14756         /* Ideally all configs would have a command associated.  Some
14757            still don't though.  */
14758         int excepted;
14759
14760         switch (i)
14761           {
14762           case PACKET_QNonStop:
14763           case PACKET_EnableDisableTracepoints_feature:
14764           case PACKET_tracenz_feature:
14765           case PACKET_DisconnectedTracing_feature:
14766           case PACKET_augmented_libraries_svr4_read_feature:
14767           case PACKET_qCRC:
14768             /* Additions to this list need to be well justified:
14769                pre-existing packets are OK; new packets are not.  */
14770             excepted = 1;
14771             break;
14772           default:
14773             excepted = 0;
14774             break;
14775           }
14776
14777         /* This catches both forgetting to add a config command, and
14778            forgetting to remove a packet from the exception list.  */
14779         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14780       }
14781   }
14782
14783   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14784      Z sub-packet has its own set and show commands, but users may
14785      have sets to this variable in their .gdbinit files (or in their
14786      documentation).  */
14787   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14788                                 &remote_Z_packet_detect, _("\
14789 Set use of remote protocol `Z' packets"), _("\
14790 Show use of remote protocol `Z' packets "), _("\
14791 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14792 packets."),
14793                                 set_remote_protocol_Z_packet_cmd,
14794                                 show_remote_protocol_Z_packet_cmd,
14795                                 /* FIXME: i18n: Use of remote protocol
14796                                    `Z' packets is %s.  */
14797                                 &remote_set_cmdlist, &remote_show_cmdlist);
14798
14799   add_prefix_cmd ("remote", class_files, remote_command, _("\
14800 Manipulate files on the remote system\n\
14801 Transfer files to and from the remote target system."),
14802                   &remote_cmdlist, "remote ",
14803                   0 /* allow-unknown */, &cmdlist);
14804
14805   add_cmd ("put", class_files, remote_put_command,
14806            _("Copy a local file to the remote system."),
14807            &remote_cmdlist);
14808
14809   add_cmd ("get", class_files, remote_get_command,
14810            _("Copy a remote file to the local system."),
14811            &remote_cmdlist);
14812
14813   add_cmd ("delete", class_files, remote_delete_command,
14814            _("Delete a remote file."),
14815            &remote_cmdlist);
14816
14817   add_setshow_string_noescape_cmd ("exec-file", class_files,
14818                                    &remote_exec_file_var, _("\
14819 Set the remote pathname for \"run\""), _("\
14820 Show the remote pathname for \"run\""), NULL,
14821                                    set_remote_exec_file,
14822                                    show_remote_exec_file,
14823                                    &remote_set_cmdlist,
14824                                    &remote_show_cmdlist);
14825
14826   add_setshow_boolean_cmd ("range-stepping", class_run,
14827                            &use_range_stepping, _("\
14828 Enable or disable range stepping."), _("\
14829 Show whether target-assisted range stepping is enabled."), _("\
14830 If on, and the target supports it, when stepping a source line, GDB\n\
14831 tells the target to step the corresponding range of addresses itself instead\n\
14832 of issuing multiple single-steps.  This speeds up source level\n\
14833 stepping.  If off, GDB always issues single-steps, even if range\n\
14834 stepping is supported by the target.  The default is on."),
14835                            set_range_stepping,
14836                            show_range_stepping,
14837                            &setlist,
14838                            &showlist);
14839
14840   /* Eventually initialize fileio.  See fileio.c */
14841   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14842
14843   /* Take advantage of the fact that the TID field is not used, to tag
14844      special ptids with it set to != 0.  */
14845   magic_null_ptid = ptid_t (42000, -1, 1);
14846   not_sent_ptid = ptid_t (42000, -2, 1);
14847   any_thread_ptid = ptid_t (42000, 0, 1);
14848 }