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