Convert symfile-debug.c to type-safe registry API
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2019 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 "process-stratum-target.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 "common/filestuff.h"
46 #include "common/rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "common/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 "common/agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "common/scoped_restore.h"
76 #include "common/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 typedef std::unique_ptr<stop_reply> stop_reply_up;
100
101 /* Generic configuration support for packets the stub optionally
102    supports.  Allows the user to specify the use of the packet as well
103    as allowing GDB to auto-detect support in the remote stub.  */
104
105 enum packet_support
106   {
107     PACKET_SUPPORT_UNKNOWN = 0,
108     PACKET_ENABLE,
109     PACKET_DISABLE
110   };
111
112 /* Analyze a packet's return value and update the packet config
113    accordingly.  */
114
115 enum packet_result
116 {
117   PACKET_ERROR,
118   PACKET_OK,
119   PACKET_UNKNOWN
120 };
121
122 struct threads_listing_context;
123
124 /* Stub vCont actions support.
125
126    Each field is a boolean flag indicating whether the stub reports
127    support for the corresponding action.  */
128
129 struct vCont_action_support
130 {
131   /* vCont;t */
132   bool t = false;
133
134   /* vCont;r */
135   bool r = false;
136
137   /* vCont;s */
138   bool s = false;
139
140   /* vCont;S */
141   bool S = false;
142 };
143
144 /* About this many threadisds fit in a packet.  */
145
146 #define MAXTHREADLISTRESULTS 32
147
148 /* Data for the vFile:pread readahead cache.  */
149
150 struct readahead_cache
151 {
152   /* Invalidate the readahead cache.  */
153   void invalidate ();
154
155   /* Invalidate the readahead cache if it is holding data for FD.  */
156   void invalidate_fd (int fd);
157
158   /* Serve pread from the readahead cache.  Returns number of bytes
159      read, or 0 if the request can't be served from the cache.  */
160   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
161
162   /* The file descriptor for the file that is being cached.  -1 if the
163      cache is invalid.  */
164   int fd = -1;
165
166   /* The offset into the file that the cache buffer corresponds
167      to.  */
168   ULONGEST offset = 0;
169
170   /* The buffer holding the cache contents.  */
171   gdb_byte *buf = nullptr;
172   /* The buffer's size.  We try to read as much as fits into a packet
173      at a time.  */
174   size_t bufsize = 0;
175
176   /* Cache hit and miss counters.  */
177   ULONGEST hit_count = 0;
178   ULONGEST miss_count = 0;
179 };
180
181 /* Description of the remote protocol for a given architecture.  */
182
183 struct packet_reg
184 {
185   long offset; /* Offset into G packet.  */
186   long regnum; /* GDB's internal register number.  */
187   LONGEST pnum; /* Remote protocol register number.  */
188   int in_g_packet; /* Always part of G packet.  */
189   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
190      at present.  */
191   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
192      at present.  */
193 };
194
195 struct remote_arch_state
196 {
197   explicit remote_arch_state (struct gdbarch *gdbarch);
198
199   /* Description of the remote protocol registers.  */
200   long sizeof_g_packet;
201
202   /* Description of the remote protocol registers indexed by REGNUM
203      (making an array gdbarch_num_regs in size).  */
204   std::unique_ptr<packet_reg[]> regs;
205
206   /* This is the size (in chars) of the first response to the ``g''
207      packet.  It is used as a heuristic when determining the maximum
208      size of memory-read and memory-write packets.  A target will
209      typically only reserve a buffer large enough to hold the ``g''
210      packet.  The size does not include packet overhead (headers and
211      trailers).  */
212   long actual_register_packet_size;
213
214   /* This is the maximum size (in chars) of a non read/write packet.
215      It is also used as a cap on the size of read/write packets.  */
216   long remote_packet_size;
217 };
218
219 /* Description of the remote protocol state for the currently
220    connected target.  This is per-target state, and independent of the
221    selected architecture.  */
222
223 class remote_state
224 {
225 public:
226
227   remote_state ();
228   ~remote_state ();
229
230   /* Get the remote arch state for GDBARCH.  */
231   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
232
233 public: /* data */
234
235   /* A buffer to use for incoming packets, and its current size.  The
236      buffer is grown dynamically for larger incoming packets.
237      Outgoing packets may also be constructed in this buffer.
238      The size of the buffer is always at least REMOTE_PACKET_SIZE;
239      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
240      packets.  */
241   gdb::char_vector buf;
242
243   /* True if we're going through initial connection setup (finding out
244      about the remote side's threads, relocating symbols, etc.).  */
245   bool starting_up = false;
246
247   /* If we negotiated packet size explicitly (and thus can bypass
248      heuristics for the largest packet size that will not overflow
249      a buffer in the stub), this will be set to that packet size.
250      Otherwise zero, meaning to use the guessed size.  */
251   long explicit_packet_size = 0;
252
253   /* remote_wait is normally called when the target is running and
254      waits for a stop reply packet.  But sometimes we need to call it
255      when the target is already stopped.  We can send a "?" packet
256      and have remote_wait read the response.  Or, if we already have
257      the response, we can stash it in BUF and tell remote_wait to
258      skip calling getpkt.  This flag is set when BUF contains a
259      stop reply packet and the target is not waiting.  */
260   int cached_wait_status = 0;
261
262   /* True, if in no ack mode.  That is, neither GDB nor the stub will
263      expect acks from each other.  The connection is assumed to be
264      reliable.  */
265   bool noack_mode = false;
266
267   /* True if we're connected in extended remote mode.  */
268   bool extended = false;
269
270   /* True if we resumed the target and we're waiting for the target to
271      stop.  In the mean time, we can't start another command/query.
272      The remote server wouldn't be ready to process it, so we'd
273      timeout waiting for a reply that would never come and eventually
274      we'd close the connection.  This can happen in asynchronous mode
275      because we allow GDB commands while the target is running.  */
276   bool waiting_for_stop_reply = false;
277
278   /* The status of the stub support for the various vCont actions.  */
279   vCont_action_support supports_vCont;
280
281   /* True if the user has pressed Ctrl-C, but the target hasn't
282      responded to that.  */
283   bool ctrlc_pending_p = false;
284
285   /* True if we saw a Ctrl-C while reading or writing from/to the
286      remote descriptor.  At that point it is not safe to send a remote
287      interrupt packet, so we instead remember we saw the Ctrl-C and
288      process it once we're done with sending/receiving the current
289      packet, which should be shortly.  If however that takes too long,
290      and the user presses Ctrl-C again, we offer to disconnect.  */
291   bool got_ctrlc_during_io = false;
292
293   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
294      remote_open knows that we don't have a file open when the program
295      starts.  */
296   struct serial *remote_desc = nullptr;
297
298   /* These are the threads which we last sent to the remote system.  The
299      TID member will be -1 for all or -2 for not sent yet.  */
300   ptid_t general_thread = null_ptid;
301   ptid_t continue_thread = null_ptid;
302
303   /* This is the traceframe which we last selected on the remote system.
304      It will be -1 if no traceframe is selected.  */
305   int remote_traceframe_number = -1;
306
307   char *last_pass_packet = nullptr;
308
309   /* The last QProgramSignals packet sent to the target.  We bypass
310      sending a new program signals list down to the target if the new
311      packet is exactly the same as the last we sent.  IOW, we only let
312      the target know about program signals list changes.  */
313   char *last_program_signals_packet = nullptr;
314
315   gdb_signal last_sent_signal = GDB_SIGNAL_0;
316
317   bool last_sent_step = false;
318
319   /* The execution direction of the last resume we got.  */
320   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
321
322   char *finished_object = nullptr;
323   char *finished_annex = nullptr;
324   ULONGEST finished_offset = 0;
325
326   /* Should we try the 'ThreadInfo' query packet?
327
328      This variable (NOT available to the user: auto-detect only!)
329      determines whether GDB will use the new, simpler "ThreadInfo"
330      query or the older, more complex syntax for thread queries.
331      This is an auto-detect variable (set to true at each connect,
332      and set to false when the target fails to recognize it).  */
333   bool use_threadinfo_query = false;
334   bool use_threadextra_query = false;
335
336   threadref echo_nextthread {};
337   threadref nextthread {};
338   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
339
340   /* The state of remote notification.  */
341   struct remote_notif_state *notif_state = nullptr;
342
343   /* The branch trace configuration.  */
344   struct btrace_config btrace_config {};
345
346   /* The argument to the last "vFile:setfs:" packet we sent, used
347      to avoid sending repeated unnecessary "vFile:setfs:" packets.
348      Initialized to -1 to indicate that no "vFile:setfs:" packet
349      has yet been sent.  */
350   int fs_pid = -1;
351
352   /* A readahead cache for vFile:pread.  Often, reading a binary
353      involves a sequence of small reads.  E.g., when parsing an ELF
354      file.  A readahead cache helps mostly the case of remote
355      debugging on a connection with higher latency, due to the
356      request/reply nature of the RSP.  We only cache data for a single
357      file descriptor at a time.  */
358   struct readahead_cache readahead_cache;
359
360   /* The list of already fetched and acknowledged stop events.  This
361      queue is used for notification Stop, and other notifications
362      don't need queue for their events, because the notification
363      events of Stop can't be consumed immediately, so that events
364      should be queued first, and be consumed by remote_wait_{ns,as}
365      one per time.  Other notifications can consume their events
366      immediately, so queue is not needed for them.  */
367   std::vector<stop_reply_up> stop_reply_queue;
368
369   /* Asynchronous signal handle registered as event loop source for
370      when we have pending events ready to be passed to the core.  */
371   struct async_event_handler *remote_async_inferior_event_token = nullptr;
372
373   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
374      ``forever'' still use the normal timeout mechanism.  This is
375      currently used by the ASYNC code to guarentee that target reads
376      during the initial connect always time-out.  Once getpkt has been
377      modified to return a timeout indication and, in turn
378      remote_wait()/wait_for_inferior() have gained a timeout parameter
379      this can go away.  */
380   int wait_forever_enabled_p = 1;
381
382 private:
383   /* Mapping of remote protocol data for each gdbarch.  Usually there
384      is only one entry here, though we may see more with stubs that
385      support multi-process.  */
386   std::unordered_map<struct gdbarch *, remote_arch_state>
387     m_arch_states;
388 };
389
390 static const target_info remote_target_info = {
391   "remote",
392   N_("Remote serial target in gdb-specific protocol"),
393   remote_doc
394 };
395
396 class remote_target : public process_stratum_target
397 {
398 public:
399   remote_target () = default;
400   ~remote_target () override;
401
402   const target_info &info () const override
403   { return remote_target_info; }
404
405   thread_control_capabilities get_thread_control_capabilities () override
406   { return tc_schedlock; }
407
408   /* Open a remote connection.  */
409   static void open (const char *, int);
410
411   void close () override;
412
413   void detach (inferior *, int) override;
414   void disconnect (const char *, int) override;
415
416   void commit_resume () override;
417   void resume (ptid_t, int, enum gdb_signal) override;
418   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
419
420   void fetch_registers (struct regcache *, int) override;
421   void store_registers (struct regcache *, int) override;
422   void prepare_to_store (struct regcache *) override;
423
424   void files_info () override;
425
426   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
427
428   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
429                          enum remove_bp_reason) override;
430
431
432   bool stopped_by_sw_breakpoint () override;
433   bool supports_stopped_by_sw_breakpoint () override;
434
435   bool stopped_by_hw_breakpoint () override;
436
437   bool supports_stopped_by_hw_breakpoint () override;
438
439   bool stopped_by_watchpoint () override;
440
441   bool stopped_data_address (CORE_ADDR *) override;
442
443   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
444
445   int can_use_hw_breakpoint (enum bptype, int, int) override;
446
447   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
448
449   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
450
451   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
452
453   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
454                          struct expression *) override;
455
456   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
457                          struct expression *) override;
458
459   void kill () override;
460
461   void load (const char *, int) override;
462
463   void mourn_inferior () override;
464
465   void pass_signals (gdb::array_view<const unsigned char>) override;
466
467   int set_syscall_catchpoint (int, bool, int,
468                               gdb::array_view<const int>) override;
469
470   void program_signals (gdb::array_view<const unsigned char>) override;
471
472   bool thread_alive (ptid_t ptid) override;
473
474   const char *thread_name (struct thread_info *) override;
475
476   void update_thread_list () override;
477
478   std::string pid_to_str (ptid_t) override;
479
480   const char *extra_thread_info (struct thread_info *) override;
481
482   ptid_t get_ada_task_ptid (long lwp, long thread) override;
483
484   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
485                                              int handle_len,
486                                              inferior *inf) override;
487
488   gdb::byte_vector thread_info_to_thread_handle (struct thread_info *tp)
489                                                  override;
490
491   void stop (ptid_t) override;
492
493   void interrupt () override;
494
495   void pass_ctrlc () override;
496
497   enum target_xfer_status xfer_partial (enum target_object object,
498                                         const char *annex,
499                                         gdb_byte *readbuf,
500                                         const gdb_byte *writebuf,
501                                         ULONGEST offset, ULONGEST len,
502                                         ULONGEST *xfered_len) override;
503
504   ULONGEST get_memory_xfer_limit () override;
505
506   void rcmd (const char *command, struct ui_file *output) override;
507
508   char *pid_to_exec_file (int pid) override;
509
510   void log_command (const char *cmd) override
511   {
512     serial_log_command (this, cmd);
513   }
514
515   CORE_ADDR get_thread_local_address (ptid_t ptid,
516                                       CORE_ADDR load_module_addr,
517                                       CORE_ADDR offset) override;
518
519   bool can_execute_reverse () override;
520
521   std::vector<mem_region> memory_map () override;
522
523   void flash_erase (ULONGEST address, LONGEST length) override;
524
525   void flash_done () override;
526
527   const struct target_desc *read_description () override;
528
529   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
530                      const gdb_byte *pattern, ULONGEST pattern_len,
531                      CORE_ADDR *found_addrp) override;
532
533   bool can_async_p () override;
534
535   bool is_async_p () override;
536
537   void async (int) override;
538
539   void thread_events (int) override;
540
541   int can_do_single_step () override;
542
543   void terminal_inferior () override;
544
545   void terminal_ours () override;
546
547   bool supports_non_stop () override;
548
549   bool supports_multi_process () override;
550
551   bool supports_disable_randomization () override;
552
553   bool filesystem_is_local () override;
554
555
556   int fileio_open (struct inferior *inf, const char *filename,
557                    int flags, int mode, int warn_if_slow,
558                    int *target_errno) override;
559
560   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
561                      ULONGEST offset, int *target_errno) override;
562
563   int fileio_pread (int fd, gdb_byte *read_buf, int len,
564                     ULONGEST offset, int *target_errno) override;
565
566   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
567
568   int fileio_close (int fd, int *target_errno) override;
569
570   int fileio_unlink (struct inferior *inf,
571                      const char *filename,
572                      int *target_errno) override;
573
574   gdb::optional<std::string>
575     fileio_readlink (struct inferior *inf,
576                      const char *filename,
577                      int *target_errno) override;
578
579   bool supports_enable_disable_tracepoint () override;
580
581   bool supports_string_tracing () override;
582
583   bool supports_evaluation_of_breakpoint_conditions () override;
584
585   bool can_run_breakpoint_commands () override;
586
587   void trace_init () override;
588
589   void download_tracepoint (struct bp_location *location) override;
590
591   bool can_download_tracepoint () override;
592
593   void download_trace_state_variable (const trace_state_variable &tsv) override;
594
595   void enable_tracepoint (struct bp_location *location) override;
596
597   void disable_tracepoint (struct bp_location *location) override;
598
599   void trace_set_readonly_regions () override;
600
601   void trace_start () override;
602
603   int get_trace_status (struct trace_status *ts) override;
604
605   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
606     override;
607
608   void trace_stop () override;
609
610   int trace_find (enum trace_find_type type, int num,
611                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
612
613   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
614
615   int save_trace_data (const char *filename) override;
616
617   int upload_tracepoints (struct uploaded_tp **utpp) override;
618
619   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
620
621   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
622
623   int get_min_fast_tracepoint_insn_len () override;
624
625   void set_disconnected_tracing (int val) override;
626
627   void set_circular_trace_buffer (int val) override;
628
629   void set_trace_buffer_size (LONGEST val) override;
630
631   bool set_trace_notes (const char *user, const char *notes,
632                         const char *stopnotes) override;
633
634   int core_of_thread (ptid_t ptid) override;
635
636   int verify_memory (const gdb_byte *data,
637                      CORE_ADDR memaddr, ULONGEST size) override;
638
639
640   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
641
642   void set_permissions () override;
643
644   bool static_tracepoint_marker_at (CORE_ADDR,
645                                     struct static_tracepoint_marker *marker)
646     override;
647
648   std::vector<static_tracepoint_marker>
649     static_tracepoint_markers_by_strid (const char *id) override;
650
651   traceframe_info_up traceframe_info () override;
652
653   bool use_agent (bool use) override;
654   bool can_use_agent () override;
655
656   struct btrace_target_info *enable_btrace (ptid_t ptid,
657                                             const struct btrace_config *conf) override;
658
659   void disable_btrace (struct btrace_target_info *tinfo) override;
660
661   void teardown_btrace (struct btrace_target_info *tinfo) override;
662
663   enum btrace_error read_btrace (struct btrace_data *data,
664                                  struct btrace_target_info *btinfo,
665                                  enum btrace_read_type type) override;
666
667   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
668   bool augmented_libraries_svr4_read () override;
669   int follow_fork (int, int) override;
670   void follow_exec (struct inferior *, char *) override;
671   int insert_fork_catchpoint (int) override;
672   int remove_fork_catchpoint (int) override;
673   int insert_vfork_catchpoint (int) override;
674   int remove_vfork_catchpoint (int) override;
675   int insert_exec_catchpoint (int) override;
676   int remove_exec_catchpoint (int) override;
677   enum exec_direction_kind execution_direction () override;
678
679 public: /* Remote specific methods.  */
680
681   void remote_download_command_source (int num, ULONGEST addr,
682                                        struct command_line *cmds);
683
684   void remote_file_put (const char *local_file, const char *remote_file,
685                         int from_tty);
686   void remote_file_get (const char *remote_file, const char *local_file,
687                         int from_tty);
688   void remote_file_delete (const char *remote_file, int from_tty);
689
690   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
691                            ULONGEST offset, int *remote_errno);
692   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
693                             ULONGEST offset, int *remote_errno);
694   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
695                                  ULONGEST offset, int *remote_errno);
696
697   int remote_hostio_send_command (int command_bytes, int which_packet,
698                                   int *remote_errno, char **attachment,
699                                   int *attachment_len);
700   int remote_hostio_set_filesystem (struct inferior *inf,
701                                     int *remote_errno);
702   /* We should get rid of this and use fileio_open directly.  */
703   int remote_hostio_open (struct inferior *inf, const char *filename,
704                           int flags, int mode, int warn_if_slow,
705                           int *remote_errno);
706   int remote_hostio_close (int fd, int *remote_errno);
707
708   int remote_hostio_unlink (inferior *inf, const char *filename,
709                             int *remote_errno);
710
711   struct remote_state *get_remote_state ();
712
713   long get_remote_packet_size (void);
714   long get_memory_packet_size (struct memory_packet_config *config);
715
716   long get_memory_write_packet_size ();
717   long get_memory_read_packet_size ();
718
719   char *append_pending_thread_resumptions (char *p, char *endp,
720                                            ptid_t ptid);
721   static void open_1 (const char *name, int from_tty, int extended_p);
722   void start_remote (int from_tty, int extended_p);
723   void remote_detach_1 (struct inferior *inf, int from_tty);
724
725   char *append_resumption (char *p, char *endp,
726                            ptid_t ptid, int step, gdb_signal siggnal);
727   int remote_resume_with_vcont (ptid_t ptid, int step,
728                                 gdb_signal siggnal);
729
730   void add_current_inferior_and_thread (char *wait_status);
731
732   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
733                   int options);
734   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
735                   int options);
736
737   ptid_t process_stop_reply (struct stop_reply *stop_reply,
738                              target_waitstatus *status);
739
740   void remote_notice_new_inferior (ptid_t currthread, int executing);
741
742   void process_initial_stop_replies (int from_tty);
743
744   thread_info *remote_add_thread (ptid_t ptid, bool running, bool executing);
745
746   void btrace_sync_conf (const btrace_config *conf);
747
748   void remote_btrace_maybe_reopen ();
749
750   void remove_new_fork_children (threads_listing_context *context);
751   void kill_new_fork_children (int pid);
752   void discard_pending_stop_replies (struct inferior *inf);
753   int stop_reply_queue_length ();
754
755   void check_pending_events_prevent_wildcard_vcont
756     (int *may_global_wildcard_vcont);
757
758   void discard_pending_stop_replies_in_queue ();
759   struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
760   struct stop_reply *queued_stop_reply (ptid_t ptid);
761   int peek_stop_reply (ptid_t ptid);
762   void remote_parse_stop_reply (const char *buf, stop_reply *event);
763
764   void remote_stop_ns (ptid_t ptid);
765   void remote_interrupt_as ();
766   void remote_interrupt_ns ();
767
768   char *remote_get_noisy_reply ();
769   int remote_query_attached (int pid);
770   inferior *remote_add_inferior (bool fake_pid_p, int pid, int attached,
771                                  int try_open_exec);
772
773   ptid_t remote_current_thread (ptid_t oldpid);
774   ptid_t get_current_thread (char *wait_status);
775
776   void set_thread (ptid_t ptid, int gen);
777   void set_general_thread (ptid_t ptid);
778   void set_continue_thread (ptid_t ptid);
779   void set_general_process ();
780
781   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
782
783   int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
784                                           gdb_ext_thread_info *info);
785   int remote_get_threadinfo (threadref *threadid, int fieldset,
786                              gdb_ext_thread_info *info);
787
788   int parse_threadlist_response (char *pkt, int result_limit,
789                                  threadref *original_echo,
790                                  threadref *resultlist,
791                                  int *doneflag);
792   int remote_get_threadlist (int startflag, threadref *nextthread,
793                              int result_limit, int *done, int *result_count,
794                              threadref *threadlist);
795
796   int remote_threadlist_iterator (rmt_thread_action stepfunction,
797                                   void *context, int looplimit);
798
799   int remote_get_threads_with_ql (threads_listing_context *context);
800   int remote_get_threads_with_qxfer (threads_listing_context *context);
801   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
802
803   void extended_remote_restart ();
804
805   void get_offsets ();
806
807   void remote_check_symbols ();
808
809   void remote_supported_packet (const struct protocol_feature *feature,
810                                 enum packet_support support,
811                                 const char *argument);
812
813   void remote_query_supported ();
814
815   void remote_packet_size (const protocol_feature *feature,
816                            packet_support support, const char *value);
817
818   void remote_serial_quit_handler ();
819
820   void remote_detach_pid (int pid);
821
822   void remote_vcont_probe ();
823
824   void remote_resume_with_hc (ptid_t ptid, int step,
825                               gdb_signal siggnal);
826
827   void send_interrupt_sequence ();
828   void interrupt_query ();
829
830   void remote_notif_get_pending_events (notif_client *nc);
831
832   int fetch_register_using_p (struct regcache *regcache,
833                               packet_reg *reg);
834   int send_g_packet ();
835   void process_g_packet (struct regcache *regcache);
836   void fetch_registers_using_g (struct regcache *regcache);
837   int store_register_using_P (const struct regcache *regcache,
838                               packet_reg *reg);
839   void store_registers_using_G (const struct regcache *regcache);
840
841   void set_remote_traceframe ();
842
843   void check_binary_download (CORE_ADDR addr);
844
845   target_xfer_status remote_write_bytes_aux (const char *header,
846                                              CORE_ADDR memaddr,
847                                              const gdb_byte *myaddr,
848                                              ULONGEST len_units,
849                                              int unit_size,
850                                              ULONGEST *xfered_len_units,
851                                              char packet_format,
852                                              int use_length);
853
854   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
855                                          const gdb_byte *myaddr, ULONGEST len,
856                                          int unit_size, ULONGEST *xfered_len);
857
858   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
859                                           ULONGEST len_units,
860                                           int unit_size, ULONGEST *xfered_len_units);
861
862   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
863                                                         ULONGEST memaddr,
864                                                         ULONGEST len,
865                                                         int unit_size,
866                                                         ULONGEST *xfered_len);
867
868   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
869                                         gdb_byte *myaddr, ULONGEST len,
870                                         int unit_size,
871                                         ULONGEST *xfered_len);
872
873   packet_result remote_send_printf (const char *format, ...)
874     ATTRIBUTE_PRINTF (2, 3);
875
876   target_xfer_status remote_flash_write (ULONGEST address,
877                                          ULONGEST length, ULONGEST *xfered_len,
878                                          const gdb_byte *data);
879
880   int readchar (int timeout);
881
882   void remote_serial_write (const char *str, int len);
883
884   int putpkt (const char *buf);
885   int putpkt_binary (const char *buf, int cnt);
886
887   int putpkt (const gdb::char_vector &buf)
888   {
889     return putpkt (buf.data ());
890   }
891
892   void skip_frame ();
893   long read_frame (gdb::char_vector *buf_p);
894   void getpkt (gdb::char_vector *buf, int forever);
895   int getpkt_or_notif_sane_1 (gdb::char_vector *buf, int forever,
896                               int expecting_notif, int *is_notif);
897   int getpkt_sane (gdb::char_vector *buf, int forever);
898   int getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
899                             int *is_notif);
900   int remote_vkill (int pid);
901   void remote_kill_k ();
902
903   void extended_remote_disable_randomization (int val);
904   int extended_remote_run (const std::string &args);
905
906   void send_environment_packet (const char *action,
907                                 const char *packet,
908                                 const char *value);
909
910   void extended_remote_environment_support ();
911   void extended_remote_set_inferior_cwd ();
912
913   target_xfer_status remote_write_qxfer (const char *object_name,
914                                          const char *annex,
915                                          const gdb_byte *writebuf,
916                                          ULONGEST offset, LONGEST len,
917                                          ULONGEST *xfered_len,
918                                          struct packet_config *packet);
919
920   target_xfer_status remote_read_qxfer (const char *object_name,
921                                         const char *annex,
922                                         gdb_byte *readbuf, ULONGEST offset,
923                                         LONGEST len,
924                                         ULONGEST *xfered_len,
925                                         struct packet_config *packet);
926
927   void push_stop_reply (struct stop_reply *new_event);
928
929   bool vcont_r_supported ();
930
931   void packet_command (const char *args, int from_tty);
932
933 private: /* data fields */
934
935   /* The remote state.  Don't reference this directly.  Use the
936      get_remote_state method instead.  */
937   remote_state m_remote_state;
938 };
939
940 static const target_info extended_remote_target_info = {
941   "extended-remote",
942   N_("Extended remote serial target in gdb-specific protocol"),
943   remote_doc
944 };
945
946 /* Set up the extended remote target by extending the standard remote
947    target and adding to it.  */
948
949 class extended_remote_target final : public remote_target
950 {
951 public:
952   const target_info &info () const override
953   { return extended_remote_target_info; }
954
955   /* Open an extended-remote connection.  */
956   static void open (const char *, int);
957
958   bool can_create_inferior () override { return true; }
959   void create_inferior (const char *, const std::string &,
960                         char **, int) override;
961
962   void detach (inferior *, int) override;
963
964   bool can_attach () override { return true; }
965   void attach (const char *, int) override;
966
967   void post_attach (int) override;
968   bool supports_disable_randomization () override;
969 };
970
971 /* Per-program-space data key.  */
972 static const struct program_space_data *remote_pspace_data;
973
974 /* The variable registered as the control variable used by the
975    remote exec-file commands.  While the remote exec-file setting is
976    per-program-space, the set/show machinery uses this as the 
977    location of the remote exec-file value.  */
978 static char *remote_exec_file_var;
979
980 /* The size to align memory write packets, when practical.  The protocol
981    does not guarantee any alignment, and gdb will generate short
982    writes and unaligned writes, but even as a best-effort attempt this
983    can improve bulk transfers.  For instance, if a write is misaligned
984    relative to the target's data bus, the stub may need to make an extra
985    round trip fetching data from the target.  This doesn't make a
986    huge difference, but it's easy to do, so we try to be helpful.
987
988    The alignment chosen is arbitrary; usually data bus width is
989    important here, not the possibly larger cache line size.  */
990 enum { REMOTE_ALIGN_WRITES = 16 };
991
992 /* Prototypes for local functions.  */
993
994 static int hexnumlen (ULONGEST num);
995
996 static int stubhex (int ch);
997
998 static int hexnumstr (char *, ULONGEST);
999
1000 static int hexnumnstr (char *, ULONGEST, int);
1001
1002 static CORE_ADDR remote_address_masked (CORE_ADDR);
1003
1004 static void print_packet (const char *);
1005
1006 static int stub_unpack_int (char *buff, int fieldlength);
1007
1008 struct packet_config;
1009
1010 static void show_packet_config_cmd (struct packet_config *config);
1011
1012 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1013                                              int from_tty,
1014                                              struct cmd_list_element *c,
1015                                              const char *value);
1016
1017 static ptid_t read_ptid (const char *buf, const char **obuf);
1018
1019 static void remote_async_inferior_event_handler (gdb_client_data);
1020
1021 static bool remote_read_description_p (struct target_ops *target);
1022
1023 static void remote_console_output (const char *msg);
1024
1025 static void remote_btrace_reset (remote_state *rs);
1026
1027 static void remote_unpush_and_throw (void);
1028
1029 /* For "remote".  */
1030
1031 static struct cmd_list_element *remote_cmdlist;
1032
1033 /* For "set remote" and "show remote".  */
1034
1035 static struct cmd_list_element *remote_set_cmdlist;
1036 static struct cmd_list_element *remote_show_cmdlist;
1037
1038 /* Controls whether GDB is willing to use range stepping.  */
1039
1040 static int use_range_stepping = 1;
1041
1042 /* The max number of chars in debug output.  The rest of chars are
1043    omitted.  */
1044
1045 #define REMOTE_DEBUG_MAX_CHAR 512
1046
1047 /* Private data that we'll store in (struct thread_info)->priv.  */
1048 struct remote_thread_info : public private_thread_info
1049 {
1050   std::string extra;
1051   std::string name;
1052   int core = -1;
1053
1054   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1055      sequence of bytes.  */
1056   gdb::byte_vector thread_handle;
1057
1058   /* Whether the target stopped for a breakpoint/watchpoint.  */
1059   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1060
1061   /* This is set to the data address of the access causing the target
1062      to stop for a watchpoint.  */
1063   CORE_ADDR watch_data_address = 0;
1064
1065   /* Fields used by the vCont action coalescing implemented in
1066      remote_resume / remote_commit_resume.  remote_resume stores each
1067      thread's last resume request in these fields, so that a later
1068      remote_commit_resume knows which is the proper action for this
1069      thread to include in the vCont packet.  */
1070
1071   /* True if the last target_resume call for this thread was a step
1072      request, false if a continue request.  */
1073   int last_resume_step = 0;
1074
1075   /* The signal specified in the last target_resume call for this
1076      thread.  */
1077   gdb_signal last_resume_sig = GDB_SIGNAL_0;
1078
1079   /* Whether this thread was already vCont-resumed on the remote
1080      side.  */
1081   int vcont_resumed = 0;
1082 };
1083
1084 remote_state::remote_state ()
1085   : buf (400)
1086 {
1087 }
1088
1089 remote_state::~remote_state ()
1090 {
1091   xfree (this->last_pass_packet);
1092   xfree (this->last_program_signals_packet);
1093   xfree (this->finished_object);
1094   xfree (this->finished_annex);
1095 }
1096
1097 /* Utility: generate error from an incoming stub packet.  */
1098 static void
1099 trace_error (char *buf)
1100 {
1101   if (*buf++ != 'E')
1102     return;                     /* not an error msg */
1103   switch (*buf)
1104     {
1105     case '1':                   /* malformed packet error */
1106       if (*++buf == '0')        /*   general case: */
1107         error (_("remote.c: error in outgoing packet."));
1108       else
1109         error (_("remote.c: error in outgoing packet at field #%ld."),
1110                strtol (buf, NULL, 16));
1111     default:
1112       error (_("Target returns error code '%s'."), buf);
1113     }
1114 }
1115
1116 /* Utility: wait for reply from stub, while accepting "O" packets.  */
1117
1118 char *
1119 remote_target::remote_get_noisy_reply ()
1120 {
1121   struct remote_state *rs = get_remote_state ();
1122
1123   do                            /* Loop on reply from remote stub.  */
1124     {
1125       char *buf;
1126
1127       QUIT;                     /* Allow user to bail out with ^C.  */
1128       getpkt (&rs->buf, 0);
1129       buf = rs->buf.data ();
1130       if (buf[0] == 'E')
1131         trace_error (buf);
1132       else if (startswith (buf, "qRelocInsn:"))
1133         {
1134           ULONGEST ul;
1135           CORE_ADDR from, to, org_to;
1136           const char *p, *pp;
1137           int adjusted_size = 0;
1138           int relocated = 0;
1139
1140           p = buf + strlen ("qRelocInsn:");
1141           pp = unpack_varlen_hex (p, &ul);
1142           if (*pp != ';')
1143             error (_("invalid qRelocInsn packet: %s"), buf);
1144           from = ul;
1145
1146           p = pp + 1;
1147           unpack_varlen_hex (p, &ul);
1148           to = ul;
1149
1150           org_to = to;
1151
1152           try
1153             {
1154               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1155               relocated = 1;
1156             }
1157           catch (const gdb_exception &ex)
1158             {
1159               if (ex.error == MEMORY_ERROR)
1160                 {
1161                   /* Propagate memory errors silently back to the
1162                      target.  The stub may have limited the range of
1163                      addresses we can write to, for example.  */
1164                 }
1165               else
1166                 {
1167                   /* Something unexpectedly bad happened.  Be verbose
1168                      so we can tell what, and propagate the error back
1169                      to the stub, so it doesn't get stuck waiting for
1170                      a response.  */
1171                   exception_fprintf (gdb_stderr, ex,
1172                                      _("warning: relocating instruction: "));
1173                 }
1174               putpkt ("E01");
1175             }
1176
1177           if (relocated)
1178             {
1179               adjusted_size = to - org_to;
1180
1181               xsnprintf (buf, rs->buf.size (), "qRelocInsn:%x", adjusted_size);
1182               putpkt (buf);
1183             }
1184         }
1185       else if (buf[0] == 'O' && buf[1] != 'K')
1186         remote_console_output (buf + 1);        /* 'O' message from stub */
1187       else
1188         return buf;             /* Here's the actual reply.  */
1189     }
1190   while (1);
1191 }
1192
1193 struct remote_arch_state *
1194 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1195 {
1196   remote_arch_state *rsa;
1197
1198   auto it = this->m_arch_states.find (gdbarch);
1199   if (it == this->m_arch_states.end ())
1200     {
1201       auto p = this->m_arch_states.emplace (std::piecewise_construct,
1202                                             std::forward_as_tuple (gdbarch),
1203                                             std::forward_as_tuple (gdbarch));
1204       rsa = &p.first->second;
1205
1206       /* Make sure that the packet buffer is plenty big enough for
1207          this architecture.  */
1208       if (this->buf.size () < rsa->remote_packet_size)
1209         this->buf.resize (2 * rsa->remote_packet_size);
1210     }
1211   else
1212     rsa = &it->second;
1213
1214   return rsa;
1215 }
1216
1217 /* Fetch the global remote target state.  */
1218
1219 remote_state *
1220 remote_target::get_remote_state ()
1221 {
1222   /* Make sure that the remote architecture state has been
1223      initialized, because doing so might reallocate rs->buf.  Any
1224      function which calls getpkt also needs to be mindful of changes
1225      to rs->buf, but this call limits the number of places which run
1226      into trouble.  */
1227   m_remote_state.get_remote_arch_state (target_gdbarch ());
1228
1229   return &m_remote_state;
1230 }
1231
1232 /* Cleanup routine for the remote module's pspace data.  */
1233
1234 static void
1235 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1236 {
1237   char *remote_exec_file = (char *) arg;
1238
1239   xfree (remote_exec_file);
1240 }
1241
1242 /* Fetch the remote exec-file from the current program space.  */
1243
1244 static const char *
1245 get_remote_exec_file (void)
1246 {
1247   char *remote_exec_file;
1248
1249   remote_exec_file
1250     = (char *) program_space_data (current_program_space,
1251                                    remote_pspace_data);
1252   if (remote_exec_file == NULL)
1253     return "";
1254
1255   return remote_exec_file;
1256 }
1257
1258 /* Set the remote exec file for PSPACE.  */
1259
1260 static void
1261 set_pspace_remote_exec_file (struct program_space *pspace,
1262                         char *remote_exec_file)
1263 {
1264   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1265
1266   xfree (old_file);
1267   set_program_space_data (pspace, remote_pspace_data,
1268                           xstrdup (remote_exec_file));
1269 }
1270
1271 /* The "set/show remote exec-file" set command hook.  */
1272
1273 static void
1274 set_remote_exec_file (const char *ignored, int from_tty,
1275                       struct cmd_list_element *c)
1276 {
1277   gdb_assert (remote_exec_file_var != NULL);
1278   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1279 }
1280
1281 /* The "set/show remote exec-file" show command hook.  */
1282
1283 static void
1284 show_remote_exec_file (struct ui_file *file, int from_tty,
1285                        struct cmd_list_element *cmd, const char *value)
1286 {
1287   fprintf_filtered (file, "%s\n", remote_exec_file_var);
1288 }
1289
1290 static int
1291 compare_pnums (const void *lhs_, const void *rhs_)
1292 {
1293   const struct packet_reg * const *lhs
1294     = (const struct packet_reg * const *) lhs_;
1295   const struct packet_reg * const *rhs
1296     = (const struct packet_reg * const *) rhs_;
1297
1298   if ((*lhs)->pnum < (*rhs)->pnum)
1299     return -1;
1300   else if ((*lhs)->pnum == (*rhs)->pnum)
1301     return 0;
1302   else
1303     return 1;
1304 }
1305
1306 static int
1307 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1308 {
1309   int regnum, num_remote_regs, offset;
1310   struct packet_reg **remote_regs;
1311
1312   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1313     {
1314       struct packet_reg *r = &regs[regnum];
1315
1316       if (register_size (gdbarch, regnum) == 0)
1317         /* Do not try to fetch zero-sized (placeholder) registers.  */
1318         r->pnum = -1;
1319       else
1320         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1321
1322       r->regnum = regnum;
1323     }
1324
1325   /* Define the g/G packet format as the contents of each register
1326      with a remote protocol number, in order of ascending protocol
1327      number.  */
1328
1329   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1330   for (num_remote_regs = 0, regnum = 0;
1331        regnum < gdbarch_num_regs (gdbarch);
1332        regnum++)
1333     if (regs[regnum].pnum != -1)
1334       remote_regs[num_remote_regs++] = &regs[regnum];
1335
1336   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1337          compare_pnums);
1338
1339   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1340     {
1341       remote_regs[regnum]->in_g_packet = 1;
1342       remote_regs[regnum]->offset = offset;
1343       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1344     }
1345
1346   return offset;
1347 }
1348
1349 /* Given the architecture described by GDBARCH, return the remote
1350    protocol register's number and the register's offset in the g/G
1351    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1352    If the target does not have a mapping for REGNUM, return false,
1353    otherwise, return true.  */
1354
1355 int
1356 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1357                                    int *pnum, int *poffset)
1358 {
1359   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1360
1361   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1362
1363   map_regcache_remote_table (gdbarch, regs.data ());
1364
1365   *pnum = regs[regnum].pnum;
1366   *poffset = regs[regnum].offset;
1367
1368   return *pnum != -1;
1369 }
1370
1371 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1372 {
1373   /* Use the architecture to build a regnum<->pnum table, which will be
1374      1:1 unless a feature set specifies otherwise.  */
1375   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1376
1377   /* Record the maximum possible size of the g packet - it may turn out
1378      to be smaller.  */
1379   this->sizeof_g_packet
1380     = map_regcache_remote_table (gdbarch, this->regs.get ());
1381
1382   /* Default maximum number of characters in a packet body.  Many
1383      remote stubs have a hardwired buffer size of 400 bytes
1384      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
1385      as the maximum packet-size to ensure that the packet and an extra
1386      NUL character can always fit in the buffer.  This stops GDB
1387      trashing stubs that try to squeeze an extra NUL into what is
1388      already a full buffer (As of 1999-12-04 that was most stubs).  */
1389   this->remote_packet_size = 400 - 1;
1390
1391   /* This one is filled in when a ``g'' packet is received.  */
1392   this->actual_register_packet_size = 0;
1393
1394   /* Should rsa->sizeof_g_packet needs more space than the
1395      default, adjust the size accordingly.  Remember that each byte is
1396      encoded as two characters.  32 is the overhead for the packet
1397      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
1398      (``$NN:G...#NN'') is a better guess, the below has been padded a
1399      little.  */
1400   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1401     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1402 }
1403
1404 /* Get a pointer to the current remote target.  If not connected to a
1405    remote target, return NULL.  */
1406
1407 static remote_target *
1408 get_current_remote_target ()
1409 {
1410   target_ops *proc_target = find_target_at (process_stratum);
1411   return dynamic_cast<remote_target *> (proc_target);
1412 }
1413
1414 /* Return the current allowed size of a remote packet.  This is
1415    inferred from the current architecture, and should be used to
1416    limit the length of outgoing packets.  */
1417 long
1418 remote_target::get_remote_packet_size ()
1419 {
1420   struct remote_state *rs = get_remote_state ();
1421   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1422
1423   if (rs->explicit_packet_size)
1424     return rs->explicit_packet_size;
1425
1426   return rsa->remote_packet_size;
1427 }
1428
1429 static struct packet_reg *
1430 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1431                         long regnum)
1432 {
1433   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1434     return NULL;
1435   else
1436     {
1437       struct packet_reg *r = &rsa->regs[regnum];
1438
1439       gdb_assert (r->regnum == regnum);
1440       return r;
1441     }
1442 }
1443
1444 static struct packet_reg *
1445 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1446                       LONGEST pnum)
1447 {
1448   int i;
1449
1450   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1451     {
1452       struct packet_reg *r = &rsa->regs[i];
1453
1454       if (r->pnum == pnum)
1455         return r;
1456     }
1457   return NULL;
1458 }
1459
1460 /* Allow the user to specify what sequence to send to the remote
1461    when he requests a program interruption: Although ^C is usually
1462    what remote systems expect (this is the default, here), it is
1463    sometimes preferable to send a break.  On other systems such
1464    as the Linux kernel, a break followed by g, which is Magic SysRq g
1465    is required in order to interrupt the execution.  */
1466 const char interrupt_sequence_control_c[] = "Ctrl-C";
1467 const char interrupt_sequence_break[] = "BREAK";
1468 const char interrupt_sequence_break_g[] = "BREAK-g";
1469 static const char *const interrupt_sequence_modes[] =
1470   {
1471     interrupt_sequence_control_c,
1472     interrupt_sequence_break,
1473     interrupt_sequence_break_g,
1474     NULL
1475   };
1476 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1477
1478 static void
1479 show_interrupt_sequence (struct ui_file *file, int from_tty,
1480                          struct cmd_list_element *c,
1481                          const char *value)
1482 {
1483   if (interrupt_sequence_mode == interrupt_sequence_control_c)
1484     fprintf_filtered (file,
1485                       _("Send the ASCII ETX character (Ctrl-c) "
1486                         "to the remote target to interrupt the "
1487                         "execution of the program.\n"));
1488   else if (interrupt_sequence_mode == interrupt_sequence_break)
1489     fprintf_filtered (file,
1490                       _("send a break signal to the remote target "
1491                         "to interrupt the execution of the program.\n"));
1492   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1493     fprintf_filtered (file,
1494                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1495                         "the remote target to interrupt the execution "
1496                         "of Linux kernel.\n"));
1497   else
1498     internal_error (__FILE__, __LINE__,
1499                     _("Invalid value for interrupt_sequence_mode: %s."),
1500                     interrupt_sequence_mode);
1501 }
1502
1503 /* This boolean variable specifies whether interrupt_sequence is sent
1504    to the remote target when gdb connects to it.
1505    This is mostly needed when you debug the Linux kernel: The Linux kernel
1506    expects BREAK g which is Magic SysRq g for connecting gdb.  */
1507 static int interrupt_on_connect = 0;
1508
1509 /* This variable is used to implement the "set/show remotebreak" commands.
1510    Since these commands are now deprecated in favor of "set/show remote
1511    interrupt-sequence", it no longer has any effect on the code.  */
1512 static int remote_break;
1513
1514 static void
1515 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1516 {
1517   if (remote_break)
1518     interrupt_sequence_mode = interrupt_sequence_break;
1519   else
1520     interrupt_sequence_mode = interrupt_sequence_control_c;
1521 }
1522
1523 static void
1524 show_remotebreak (struct ui_file *file, int from_tty,
1525                   struct cmd_list_element *c,
1526                   const char *value)
1527 {
1528 }
1529
1530 /* This variable sets the number of bits in an address that are to be
1531    sent in a memory ("M" or "m") packet.  Normally, after stripping
1532    leading zeros, the entire address would be sent.  This variable
1533    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
1534    initial implementation of remote.c restricted the address sent in
1535    memory packets to ``host::sizeof long'' bytes - (typically 32
1536    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1537    address was never sent.  Since fixing this bug may cause a break in
1538    some remote targets this variable is principly provided to
1539    facilitate backward compatibility.  */
1540
1541 static unsigned int remote_address_size;
1542
1543 \f
1544 /* User configurable variables for the number of characters in a
1545    memory read/write packet.  MIN (rsa->remote_packet_size,
1546    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1547    values (fifo overruns, et.al.) and some users need larger values
1548    (speed up transfers).  The variables ``preferred_*'' (the user
1549    request), ``current_*'' (what was actually set) and ``forced_*''
1550    (Positive - a soft limit, negative - a hard limit).  */
1551
1552 struct memory_packet_config
1553 {
1554   const char *name;
1555   long size;
1556   int fixed_p;
1557 };
1558
1559 /* The default max memory-write-packet-size, when the setting is
1560    "fixed".  The 16k is historical.  (It came from older GDB's using
1561    alloca for buffers and the knowledge (folklore?) that some hosts
1562    don't cope very well with large alloca calls.)  */
1563 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1564
1565 /* The minimum remote packet size for memory transfers.  Ensures we
1566    can write at least one byte.  */
1567 #define MIN_MEMORY_PACKET_SIZE 20
1568
1569 /* Get the memory packet size, assuming it is fixed.  */
1570
1571 static long
1572 get_fixed_memory_packet_size (struct memory_packet_config *config)
1573 {
1574   gdb_assert (config->fixed_p);
1575
1576   if (config->size <= 0)
1577     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1578   else
1579     return config->size;
1580 }
1581
1582 /* Compute the current size of a read/write packet.  Since this makes
1583    use of ``actual_register_packet_size'' the computation is dynamic.  */
1584
1585 long
1586 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1587 {
1588   struct remote_state *rs = get_remote_state ();
1589   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1590
1591   long what_they_get;
1592   if (config->fixed_p)
1593     what_they_get = get_fixed_memory_packet_size (config);
1594   else
1595     {
1596       what_they_get = get_remote_packet_size ();
1597       /* Limit the packet to the size specified by the user.  */
1598       if (config->size > 0
1599           && what_they_get > config->size)
1600         what_they_get = config->size;
1601
1602       /* Limit it to the size of the targets ``g'' response unless we have
1603          permission from the stub to use a larger packet size.  */
1604       if (rs->explicit_packet_size == 0
1605           && rsa->actual_register_packet_size > 0
1606           && what_they_get > rsa->actual_register_packet_size)
1607         what_they_get = rsa->actual_register_packet_size;
1608     }
1609   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1610     what_they_get = MIN_MEMORY_PACKET_SIZE;
1611
1612   /* Make sure there is room in the global buffer for this packet
1613      (including its trailing NUL byte).  */
1614   if (rs->buf.size () < what_they_get + 1)
1615     rs->buf.resize (2 * what_they_get);
1616
1617   return what_they_get;
1618 }
1619
1620 /* Update the size of a read/write packet.  If they user wants
1621    something really big then do a sanity check.  */
1622
1623 static void
1624 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1625 {
1626   int fixed_p = config->fixed_p;
1627   long size = config->size;
1628
1629   if (args == NULL)
1630     error (_("Argument required (integer, `fixed' or `limited')."));
1631   else if (strcmp (args, "hard") == 0
1632       || strcmp (args, "fixed") == 0)
1633     fixed_p = 1;
1634   else if (strcmp (args, "soft") == 0
1635            || strcmp (args, "limit") == 0)
1636     fixed_p = 0;
1637   else
1638     {
1639       char *end;
1640
1641       size = strtoul (args, &end, 0);
1642       if (args == end)
1643         error (_("Invalid %s (bad syntax)."), config->name);
1644
1645       /* Instead of explicitly capping the size of a packet to or
1646          disallowing it, the user is allowed to set the size to
1647          something arbitrarily large.  */
1648     }
1649
1650   /* Extra checks?  */
1651   if (fixed_p && !config->fixed_p)
1652     {
1653       /* So that the query shows the correct value.  */
1654       long query_size = (size <= 0
1655                          ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1656                          : size);
1657
1658       if (! query (_("The target may not be able to correctly handle a %s\n"
1659                    "of %ld bytes. Change the packet size? "),
1660                    config->name, query_size))
1661         error (_("Packet size not changed."));
1662     }
1663   /* Update the config.  */
1664   config->fixed_p = fixed_p;
1665   config->size = size;
1666 }
1667
1668 static void
1669 show_memory_packet_size (struct memory_packet_config *config)
1670 {
1671   if (config->size == 0)
1672     printf_filtered (_("The %s is 0 (default). "), config->name);
1673   else
1674     printf_filtered (_("The %s is %ld. "), config->name, config->size);
1675   if (config->fixed_p)
1676     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1677                      get_fixed_memory_packet_size (config));
1678   else
1679     {
1680       remote_target *remote = get_current_remote_target ();
1681
1682       if (remote != NULL)
1683         printf_filtered (_("Packets are limited to %ld bytes.\n"),
1684                          remote->get_memory_packet_size (config));
1685       else
1686         puts_filtered ("The actual limit will be further reduced "
1687                        "dependent on the target.\n");
1688     }
1689 }
1690
1691 static struct memory_packet_config memory_write_packet_config =
1692 {
1693   "memory-write-packet-size",
1694 };
1695
1696 static void
1697 set_memory_write_packet_size (const char *args, int from_tty)
1698 {
1699   set_memory_packet_size (args, &memory_write_packet_config);
1700 }
1701
1702 static void
1703 show_memory_write_packet_size (const char *args, int from_tty)
1704 {
1705   show_memory_packet_size (&memory_write_packet_config);
1706 }
1707
1708 /* Show the number of hardware watchpoints that can be used.  */
1709
1710 static void
1711 show_hardware_watchpoint_limit (struct ui_file *file, int from_tty,
1712                                 struct cmd_list_element *c,
1713                                 const char *value)
1714 {
1715   fprintf_filtered (file, _("The maximum number of target hardware "
1716                             "watchpoints is %s.\n"), value);
1717 }
1718
1719 /* Show the length limit (in bytes) for hardware watchpoints.  */
1720
1721 static void
1722 show_hardware_watchpoint_length_limit (struct ui_file *file, int from_tty,
1723                                        struct cmd_list_element *c,
1724                                        const char *value)
1725 {
1726   fprintf_filtered (file, _("The maximum length (in bytes) of a target "
1727                             "hardware watchpoint is %s.\n"), value);
1728 }
1729
1730 /* Show the number of hardware breakpoints that can be used.  */
1731
1732 static void
1733 show_hardware_breakpoint_limit (struct ui_file *file, int from_tty,
1734                                 struct cmd_list_element *c,
1735                                 const char *value)
1736 {
1737   fprintf_filtered (file, _("The maximum number of target hardware "
1738                             "breakpoints is %s.\n"), value);
1739 }
1740
1741 long
1742 remote_target::get_memory_write_packet_size ()
1743 {
1744   return get_memory_packet_size (&memory_write_packet_config);
1745 }
1746
1747 static struct memory_packet_config memory_read_packet_config =
1748 {
1749   "memory-read-packet-size",
1750 };
1751
1752 static void
1753 set_memory_read_packet_size (const char *args, int from_tty)
1754 {
1755   set_memory_packet_size (args, &memory_read_packet_config);
1756 }
1757
1758 static void
1759 show_memory_read_packet_size (const char *args, int from_tty)
1760 {
1761   show_memory_packet_size (&memory_read_packet_config);
1762 }
1763
1764 long
1765 remote_target::get_memory_read_packet_size ()
1766 {
1767   long size = get_memory_packet_size (&memory_read_packet_config);
1768
1769   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1770      extra buffer size argument before the memory read size can be
1771      increased beyond this.  */
1772   if (size > get_remote_packet_size ())
1773     size = get_remote_packet_size ();
1774   return size;
1775 }
1776
1777 \f
1778
1779 struct packet_config
1780   {
1781     const char *name;
1782     const char *title;
1783
1784     /* If auto, GDB auto-detects support for this packet or feature,
1785        either through qSupported, or by trying the packet and looking
1786        at the response.  If true, GDB assumes the target supports this
1787        packet.  If false, the packet is disabled.  Configs that don't
1788        have an associated command always have this set to auto.  */
1789     enum auto_boolean detect;
1790
1791     /* Does the target support this packet?  */
1792     enum packet_support support;
1793   };
1794
1795 static enum packet_support packet_config_support (struct packet_config *config);
1796 static enum packet_support packet_support (int packet);
1797
1798 static void
1799 show_packet_config_cmd (struct packet_config *config)
1800 {
1801   const char *support = "internal-error";
1802
1803   switch (packet_config_support (config))
1804     {
1805     case PACKET_ENABLE:
1806       support = "enabled";
1807       break;
1808     case PACKET_DISABLE:
1809       support = "disabled";
1810       break;
1811     case PACKET_SUPPORT_UNKNOWN:
1812       support = "unknown";
1813       break;
1814     }
1815   switch (config->detect)
1816     {
1817     case AUTO_BOOLEAN_AUTO:
1818       printf_filtered (_("Support for the `%s' packet "
1819                          "is auto-detected, currently %s.\n"),
1820                        config->name, support);
1821       break;
1822     case AUTO_BOOLEAN_TRUE:
1823     case AUTO_BOOLEAN_FALSE:
1824       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1825                        config->name, support);
1826       break;
1827     }
1828 }
1829
1830 static void
1831 add_packet_config_cmd (struct packet_config *config, const char *name,
1832                        const char *title, int legacy)
1833 {
1834   char *set_doc;
1835   char *show_doc;
1836   char *cmd_name;
1837
1838   config->name = name;
1839   config->title = title;
1840   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1841                         name, title);
1842   show_doc = xstrprintf ("Show current use of remote "
1843                          "protocol `%s' (%s) packet",
1844                          name, title);
1845   /* set/show TITLE-packet {auto,on,off} */
1846   cmd_name = xstrprintf ("%s-packet", title);
1847   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1848                                 &config->detect, set_doc,
1849                                 show_doc, NULL, /* help_doc */
1850                                 NULL,
1851                                 show_remote_protocol_packet_cmd,
1852                                 &remote_set_cmdlist, &remote_show_cmdlist);
1853   /* The command code copies the documentation strings.  */
1854   xfree (set_doc);
1855   xfree (show_doc);
1856   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1857   if (legacy)
1858     {
1859       char *legacy_name;
1860
1861       legacy_name = xstrprintf ("%s-packet", name);
1862       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1863                      &remote_set_cmdlist);
1864       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1865                      &remote_show_cmdlist);
1866     }
1867 }
1868
1869 static enum packet_result
1870 packet_check_result (const char *buf)
1871 {
1872   if (buf[0] != '\0')
1873     {
1874       /* The stub recognized the packet request.  Check that the
1875          operation succeeded.  */
1876       if (buf[0] == 'E'
1877           && isxdigit (buf[1]) && isxdigit (buf[2])
1878           && buf[3] == '\0')
1879         /* "Enn"  - definitly an error.  */
1880         return PACKET_ERROR;
1881
1882       /* Always treat "E." as an error.  This will be used for
1883          more verbose error messages, such as E.memtypes.  */
1884       if (buf[0] == 'E' && buf[1] == '.')
1885         return PACKET_ERROR;
1886
1887       /* The packet may or may not be OK.  Just assume it is.  */
1888       return PACKET_OK;
1889     }
1890   else
1891     /* The stub does not support the packet.  */
1892     return PACKET_UNKNOWN;
1893 }
1894
1895 static enum packet_result
1896 packet_check_result (const gdb::char_vector &buf)
1897 {
1898   return packet_check_result (buf.data ());
1899 }
1900
1901 static enum packet_result
1902 packet_ok (const char *buf, struct packet_config *config)
1903 {
1904   enum packet_result result;
1905
1906   if (config->detect != AUTO_BOOLEAN_TRUE
1907       && config->support == PACKET_DISABLE)
1908     internal_error (__FILE__, __LINE__,
1909                     _("packet_ok: attempt to use a disabled packet"));
1910
1911   result = packet_check_result (buf);
1912   switch (result)
1913     {
1914     case PACKET_OK:
1915     case PACKET_ERROR:
1916       /* The stub recognized the packet request.  */
1917       if (config->support == PACKET_SUPPORT_UNKNOWN)
1918         {
1919           if (remote_debug)
1920             fprintf_unfiltered (gdb_stdlog,
1921                                 "Packet %s (%s) is supported\n",
1922                                 config->name, config->title);
1923           config->support = PACKET_ENABLE;
1924         }
1925       break;
1926     case PACKET_UNKNOWN:
1927       /* The stub does not support the packet.  */
1928       if (config->detect == AUTO_BOOLEAN_AUTO
1929           && config->support == PACKET_ENABLE)
1930         {
1931           /* If the stub previously indicated that the packet was
1932              supported then there is a protocol error.  */
1933           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1934                  config->name, config->title);
1935         }
1936       else if (config->detect == AUTO_BOOLEAN_TRUE)
1937         {
1938           /* The user set it wrong.  */
1939           error (_("Enabled packet %s (%s) not recognized by stub"),
1940                  config->name, config->title);
1941         }
1942
1943       if (remote_debug)
1944         fprintf_unfiltered (gdb_stdlog,
1945                             "Packet %s (%s) is NOT supported\n",
1946                             config->name, config->title);
1947       config->support = PACKET_DISABLE;
1948       break;
1949     }
1950
1951   return result;
1952 }
1953
1954 static enum packet_result
1955 packet_ok (const gdb::char_vector &buf, struct packet_config *config)
1956 {
1957   return packet_ok (buf.data (), config);
1958 }
1959
1960 enum {
1961   PACKET_vCont = 0,
1962   PACKET_X,
1963   PACKET_qSymbol,
1964   PACKET_P,
1965   PACKET_p,
1966   PACKET_Z0,
1967   PACKET_Z1,
1968   PACKET_Z2,
1969   PACKET_Z3,
1970   PACKET_Z4,
1971   PACKET_vFile_setfs,
1972   PACKET_vFile_open,
1973   PACKET_vFile_pread,
1974   PACKET_vFile_pwrite,
1975   PACKET_vFile_close,
1976   PACKET_vFile_unlink,
1977   PACKET_vFile_readlink,
1978   PACKET_vFile_fstat,
1979   PACKET_qXfer_auxv,
1980   PACKET_qXfer_features,
1981   PACKET_qXfer_exec_file,
1982   PACKET_qXfer_libraries,
1983   PACKET_qXfer_libraries_svr4,
1984   PACKET_qXfer_memory_map,
1985   PACKET_qXfer_spu_read,
1986   PACKET_qXfer_spu_write,
1987   PACKET_qXfer_osdata,
1988   PACKET_qXfer_threads,
1989   PACKET_qXfer_statictrace_read,
1990   PACKET_qXfer_traceframe_info,
1991   PACKET_qXfer_uib,
1992   PACKET_qGetTIBAddr,
1993   PACKET_qGetTLSAddr,
1994   PACKET_qSupported,
1995   PACKET_qTStatus,
1996   PACKET_QPassSignals,
1997   PACKET_QCatchSyscalls,
1998   PACKET_QProgramSignals,
1999   PACKET_QSetWorkingDir,
2000   PACKET_QStartupWithShell,
2001   PACKET_QEnvironmentHexEncoded,
2002   PACKET_QEnvironmentReset,
2003   PACKET_QEnvironmentUnset,
2004   PACKET_qCRC,
2005   PACKET_qSearch_memory,
2006   PACKET_vAttach,
2007   PACKET_vRun,
2008   PACKET_QStartNoAckMode,
2009   PACKET_vKill,
2010   PACKET_qXfer_siginfo_read,
2011   PACKET_qXfer_siginfo_write,
2012   PACKET_qAttached,
2013
2014   /* Support for conditional tracepoints.  */
2015   PACKET_ConditionalTracepoints,
2016
2017   /* Support for target-side breakpoint conditions.  */
2018   PACKET_ConditionalBreakpoints,
2019
2020   /* Support for target-side breakpoint commands.  */
2021   PACKET_BreakpointCommands,
2022
2023   /* Support for fast tracepoints.  */
2024   PACKET_FastTracepoints,
2025
2026   /* Support for static tracepoints.  */
2027   PACKET_StaticTracepoints,
2028
2029   /* Support for installing tracepoints while a trace experiment is
2030      running.  */
2031   PACKET_InstallInTrace,
2032
2033   PACKET_bc,
2034   PACKET_bs,
2035   PACKET_TracepointSource,
2036   PACKET_QAllow,
2037   PACKET_qXfer_fdpic,
2038   PACKET_QDisableRandomization,
2039   PACKET_QAgent,
2040   PACKET_QTBuffer_size,
2041   PACKET_Qbtrace_off,
2042   PACKET_Qbtrace_bts,
2043   PACKET_Qbtrace_pt,
2044   PACKET_qXfer_btrace,
2045
2046   /* Support for the QNonStop packet.  */
2047   PACKET_QNonStop,
2048
2049   /* Support for the QThreadEvents packet.  */
2050   PACKET_QThreadEvents,
2051
2052   /* Support for multi-process extensions.  */
2053   PACKET_multiprocess_feature,
2054
2055   /* Support for enabling and disabling tracepoints while a trace
2056      experiment is running.  */
2057   PACKET_EnableDisableTracepoints_feature,
2058
2059   /* Support for collecting strings using the tracenz bytecode.  */
2060   PACKET_tracenz_feature,
2061
2062   /* Support for continuing to run a trace experiment while GDB is
2063      disconnected.  */
2064   PACKET_DisconnectedTracing_feature,
2065
2066   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
2067   PACKET_augmented_libraries_svr4_read_feature,
2068
2069   /* Support for the qXfer:btrace-conf:read packet.  */
2070   PACKET_qXfer_btrace_conf,
2071
2072   /* Support for the Qbtrace-conf:bts:size packet.  */
2073   PACKET_Qbtrace_conf_bts_size,
2074
2075   /* Support for swbreak+ feature.  */
2076   PACKET_swbreak_feature,
2077
2078   /* Support for hwbreak+ feature.  */
2079   PACKET_hwbreak_feature,
2080
2081   /* Support for fork events.  */
2082   PACKET_fork_event_feature,
2083
2084   /* Support for vfork events.  */
2085   PACKET_vfork_event_feature,
2086
2087   /* Support for the Qbtrace-conf:pt:size packet.  */
2088   PACKET_Qbtrace_conf_pt_size,
2089
2090   /* Support for exec events.  */
2091   PACKET_exec_event_feature,
2092
2093   /* Support for query supported vCont actions.  */
2094   PACKET_vContSupported,
2095
2096   /* Support remote CTRL-C.  */
2097   PACKET_vCtrlC,
2098
2099   /* Support TARGET_WAITKIND_NO_RESUMED.  */
2100   PACKET_no_resumed,
2101
2102   PACKET_MAX
2103 };
2104
2105 static struct packet_config remote_protocol_packets[PACKET_MAX];
2106
2107 /* Returns the packet's corresponding "set remote foo-packet" command
2108    state.  See struct packet_config for more details.  */
2109
2110 static enum auto_boolean
2111 packet_set_cmd_state (int packet)
2112 {
2113   return remote_protocol_packets[packet].detect;
2114 }
2115
2116 /* Returns whether a given packet or feature is supported.  This takes
2117    into account the state of the corresponding "set remote foo-packet"
2118    command, which may be used to bypass auto-detection.  */
2119
2120 static enum packet_support
2121 packet_config_support (struct packet_config *config)
2122 {
2123   switch (config->detect)
2124     {
2125     case AUTO_BOOLEAN_TRUE:
2126       return PACKET_ENABLE;
2127     case AUTO_BOOLEAN_FALSE:
2128       return PACKET_DISABLE;
2129     case AUTO_BOOLEAN_AUTO:
2130       return config->support;
2131     default:
2132       gdb_assert_not_reached (_("bad switch"));
2133     }
2134 }
2135
2136 /* Same as packet_config_support, but takes the packet's enum value as
2137    argument.  */
2138
2139 static enum packet_support
2140 packet_support (int packet)
2141 {
2142   struct packet_config *config = &remote_protocol_packets[packet];
2143
2144   return packet_config_support (config);
2145 }
2146
2147 static void
2148 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2149                                  struct cmd_list_element *c,
2150                                  const char *value)
2151 {
2152   struct packet_config *packet;
2153
2154   for (packet = remote_protocol_packets;
2155        packet < &remote_protocol_packets[PACKET_MAX];
2156        packet++)
2157     {
2158       if (&packet->detect == c->var)
2159         {
2160           show_packet_config_cmd (packet);
2161           return;
2162         }
2163     }
2164   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2165                   c->name);
2166 }
2167
2168 /* Should we try one of the 'Z' requests?  */
2169
2170 enum Z_packet_type
2171 {
2172   Z_PACKET_SOFTWARE_BP,
2173   Z_PACKET_HARDWARE_BP,
2174   Z_PACKET_WRITE_WP,
2175   Z_PACKET_READ_WP,
2176   Z_PACKET_ACCESS_WP,
2177   NR_Z_PACKET_TYPES
2178 };
2179
2180 /* For compatibility with older distributions.  Provide a ``set remote
2181    Z-packet ...'' command that updates all the Z packet types.  */
2182
2183 static enum auto_boolean remote_Z_packet_detect;
2184
2185 static void
2186 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2187                                   struct cmd_list_element *c)
2188 {
2189   int i;
2190
2191   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2192     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2193 }
2194
2195 static void
2196 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2197                                    struct cmd_list_element *c,
2198                                    const char *value)
2199 {
2200   int i;
2201
2202   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2203     {
2204       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2205     }
2206 }
2207
2208 /* Returns true if the multi-process extensions are in effect.  */
2209
2210 static int
2211 remote_multi_process_p (struct remote_state *rs)
2212 {
2213   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2214 }
2215
2216 /* Returns true if fork events are supported.  */
2217
2218 static int
2219 remote_fork_event_p (struct remote_state *rs)
2220 {
2221   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2222 }
2223
2224 /* Returns true if vfork events are supported.  */
2225
2226 static int
2227 remote_vfork_event_p (struct remote_state *rs)
2228 {
2229   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2230 }
2231
2232 /* Returns true if exec events are supported.  */
2233
2234 static int
2235 remote_exec_event_p (struct remote_state *rs)
2236 {
2237   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2238 }
2239
2240 /* Insert fork catchpoint target routine.  If fork events are enabled
2241    then return success, nothing more to do.  */
2242
2243 int
2244 remote_target::insert_fork_catchpoint (int pid)
2245 {
2246   struct remote_state *rs = get_remote_state ();
2247
2248   return !remote_fork_event_p (rs);
2249 }
2250
2251 /* Remove fork catchpoint target routine.  Nothing to do, just
2252    return success.  */
2253
2254 int
2255 remote_target::remove_fork_catchpoint (int pid)
2256 {
2257   return 0;
2258 }
2259
2260 /* Insert vfork catchpoint target routine.  If vfork events are enabled
2261    then return success, nothing more to do.  */
2262
2263 int
2264 remote_target::insert_vfork_catchpoint (int pid)
2265 {
2266   struct remote_state *rs = get_remote_state ();
2267
2268   return !remote_vfork_event_p (rs);
2269 }
2270
2271 /* Remove vfork catchpoint target routine.  Nothing to do, just
2272    return success.  */
2273
2274 int
2275 remote_target::remove_vfork_catchpoint (int pid)
2276 {
2277   return 0;
2278 }
2279
2280 /* Insert exec catchpoint target routine.  If exec events are
2281    enabled, just return success.  */
2282
2283 int
2284 remote_target::insert_exec_catchpoint (int pid)
2285 {
2286   struct remote_state *rs = get_remote_state ();
2287
2288   return !remote_exec_event_p (rs);
2289 }
2290
2291 /* Remove exec catchpoint target routine.  Nothing to do, just
2292    return success.  */
2293
2294 int
2295 remote_target::remove_exec_catchpoint (int pid)
2296 {
2297   return 0;
2298 }
2299
2300 \f
2301
2302 /* Take advantage of the fact that the TID field is not used, to tag
2303    special ptids with it set to != 0.  */
2304 static const ptid_t magic_null_ptid (42000, -1, 1);
2305 static const ptid_t not_sent_ptid (42000, -2, 1);
2306 static const ptid_t any_thread_ptid (42000, 0, 1);
2307
2308 /* Find out if the stub attached to PID (and hence GDB should offer to
2309    detach instead of killing it when bailing out).  */
2310
2311 int
2312 remote_target::remote_query_attached (int pid)
2313 {
2314   struct remote_state *rs = get_remote_state ();
2315   size_t size = get_remote_packet_size ();
2316
2317   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2318     return 0;
2319
2320   if (remote_multi_process_p (rs))
2321     xsnprintf (rs->buf.data (), size, "qAttached:%x", pid);
2322   else
2323     xsnprintf (rs->buf.data (), size, "qAttached");
2324
2325   putpkt (rs->buf);
2326   getpkt (&rs->buf, 0);
2327
2328   switch (packet_ok (rs->buf,
2329                      &remote_protocol_packets[PACKET_qAttached]))
2330     {
2331     case PACKET_OK:
2332       if (strcmp (rs->buf.data (), "1") == 0)
2333         return 1;
2334       break;
2335     case PACKET_ERROR:
2336       warning (_("Remote failure reply: %s"), rs->buf.data ());
2337       break;
2338     case PACKET_UNKNOWN:
2339       break;
2340     }
2341
2342   return 0;
2343 }
2344
2345 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2346    has been invented by GDB, instead of reported by the target.  Since
2347    we can be connected to a remote system before before knowing about
2348    any inferior, mark the target with execution when we find the first
2349    inferior.  If ATTACHED is 1, then we had just attached to this
2350    inferior.  If it is 0, then we just created this inferior.  If it
2351    is -1, then try querying the remote stub to find out if it had
2352    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2353    attempt to open this inferior's executable as the main executable
2354    if no main executable is open already.  */
2355
2356 inferior *
2357 remote_target::remote_add_inferior (bool fake_pid_p, int pid, int attached,
2358                                     int try_open_exec)
2359 {
2360   struct inferior *inf;
2361
2362   /* Check whether this process we're learning about is to be
2363      considered attached, or if is to be considered to have been
2364      spawned by the stub.  */
2365   if (attached == -1)
2366     attached = remote_query_attached (pid);
2367
2368   if (gdbarch_has_global_solist (target_gdbarch ()))
2369     {
2370       /* If the target shares code across all inferiors, then every
2371          attach adds a new inferior.  */
2372       inf = add_inferior (pid);
2373
2374       /* ... and every inferior is bound to the same program space.
2375          However, each inferior may still have its own address
2376          space.  */
2377       inf->aspace = maybe_new_address_space ();
2378       inf->pspace = current_program_space;
2379     }
2380   else
2381     {
2382       /* In the traditional debugging scenario, there's a 1-1 match
2383          between program/address spaces.  We simply bind the inferior
2384          to the program space's address space.  */
2385       inf = current_inferior ();
2386       inferior_appeared (inf, pid);
2387     }
2388
2389   inf->attach_flag = attached;
2390   inf->fake_pid_p = fake_pid_p;
2391
2392   /* If no main executable is currently open then attempt to
2393      open the file that was executed to create this inferior.  */
2394   if (try_open_exec && get_exec_file (0) == NULL)
2395     exec_file_locate_attach (pid, 0, 1);
2396
2397   return inf;
2398 }
2399
2400 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2401 static remote_thread_info *get_remote_thread_info (ptid_t ptid);
2402
2403 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2404    according to RUNNING.  */
2405
2406 thread_info *
2407 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2408 {
2409   struct remote_state *rs = get_remote_state ();
2410   struct thread_info *thread;
2411
2412   /* GDB historically didn't pull threads in the initial connection
2413      setup.  If the remote target doesn't even have a concept of
2414      threads (e.g., a bare-metal target), even if internally we
2415      consider that a single-threaded target, mentioning a new thread
2416      might be confusing to the user.  Be silent then, preserving the
2417      age old behavior.  */
2418   if (rs->starting_up)
2419     thread = add_thread_silent (ptid);
2420   else
2421     thread = add_thread (ptid);
2422
2423   get_remote_thread_info (thread)->vcont_resumed = executing;
2424   set_executing (ptid, executing);
2425   set_running (ptid, running);
2426
2427   return thread;
2428 }
2429
2430 /* Come here when we learn about a thread id from the remote target.
2431    It may be the first time we hear about such thread, so take the
2432    opportunity to add it to GDB's thread list.  In case this is the
2433    first time we're noticing its corresponding inferior, add it to
2434    GDB's inferior list as well.  EXECUTING indicates whether the
2435    thread is (internally) executing or stopped.  */
2436
2437 void
2438 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2439 {
2440   /* In non-stop mode, we assume new found threads are (externally)
2441      running until proven otherwise with a stop reply.  In all-stop,
2442      we can only get here if all threads are stopped.  */
2443   int running = target_is_non_stop_p () ? 1 : 0;
2444
2445   /* If this is a new thread, add it to GDB's thread list.
2446      If we leave it up to WFI to do this, bad things will happen.  */
2447
2448   thread_info *tp = find_thread_ptid (currthread);
2449   if (tp != NULL && tp->state == THREAD_EXITED)
2450     {
2451       /* We're seeing an event on a thread id we knew had exited.
2452          This has to be a new thread reusing the old id.  Add it.  */
2453       remote_add_thread (currthread, running, executing);
2454       return;
2455     }
2456
2457   if (!in_thread_list (currthread))
2458     {
2459       struct inferior *inf = NULL;
2460       int pid = currthread.pid ();
2461
2462       if (inferior_ptid.is_pid ()
2463           && pid == inferior_ptid.pid ())
2464         {
2465           /* inferior_ptid has no thread member yet.  This can happen
2466              with the vAttach -> remote_wait,"TAAthread:" path if the
2467              stub doesn't support qC.  This is the first stop reported
2468              after an attach, so this is the main thread.  Update the
2469              ptid in the thread list.  */
2470           if (in_thread_list (ptid_t (pid)))
2471             thread_change_ptid (inferior_ptid, currthread);
2472           else
2473             {
2474               remote_add_thread (currthread, running, executing);
2475               inferior_ptid = currthread;
2476             }
2477           return;
2478         }
2479
2480       if (magic_null_ptid == inferior_ptid)
2481         {
2482           /* inferior_ptid is not set yet.  This can happen with the
2483              vRun -> remote_wait,"TAAthread:" path if the stub
2484              doesn't support qC.  This is the first stop reported
2485              after an attach, so this is the main thread.  Update the
2486              ptid in the thread list.  */
2487           thread_change_ptid (inferior_ptid, currthread);
2488           return;
2489         }
2490
2491       /* When connecting to a target remote, or to a target
2492          extended-remote which already was debugging an inferior, we
2493          may not know about it yet.  Add it before adding its child
2494          thread, so notifications are emitted in a sensible order.  */
2495       if (find_inferior_pid (currthread.pid ()) == NULL)
2496         {
2497           struct remote_state *rs = get_remote_state ();
2498           bool fake_pid_p = !remote_multi_process_p (rs);
2499
2500           inf = remote_add_inferior (fake_pid_p,
2501                                      currthread.pid (), -1, 1);
2502         }
2503
2504       /* This is really a new thread.  Add it.  */
2505       thread_info *new_thr
2506         = remote_add_thread (currthread, running, executing);
2507
2508       /* If we found a new inferior, let the common code do whatever
2509          it needs to with it (e.g., read shared libraries, insert
2510          breakpoints), unless we're just setting up an all-stop
2511          connection.  */
2512       if (inf != NULL)
2513         {
2514           struct remote_state *rs = get_remote_state ();
2515
2516           if (!rs->starting_up)
2517             notice_new_inferior (new_thr, executing, 0);
2518         }
2519     }
2520 }
2521
2522 /* Return THREAD's private thread data, creating it if necessary.  */
2523
2524 static remote_thread_info *
2525 get_remote_thread_info (thread_info *thread)
2526 {
2527   gdb_assert (thread != NULL);
2528
2529   if (thread->priv == NULL)
2530     thread->priv.reset (new remote_thread_info);
2531
2532   return static_cast<remote_thread_info *> (thread->priv.get ());
2533 }
2534
2535 static remote_thread_info *
2536 get_remote_thread_info (ptid_t ptid)
2537 {
2538   thread_info *thr = find_thread_ptid (ptid);
2539   return get_remote_thread_info (thr);
2540 }
2541
2542 /* Call this function as a result of
2543    1) A halt indication (T packet) containing a thread id
2544    2) A direct query of currthread
2545    3) Successful execution of set thread */
2546
2547 static void
2548 record_currthread (struct remote_state *rs, ptid_t currthread)
2549 {
2550   rs->general_thread = currthread;
2551 }
2552
2553 /* If 'QPassSignals' is supported, tell the remote stub what signals
2554    it can simply pass through to the inferior without reporting.  */
2555
2556 void
2557 remote_target::pass_signals (gdb::array_view<const unsigned char> pass_signals)
2558 {
2559   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2560     {
2561       char *pass_packet, *p;
2562       int count = 0;
2563       struct remote_state *rs = get_remote_state ();
2564
2565       gdb_assert (pass_signals.size () < 256);
2566       for (size_t i = 0; i < pass_signals.size (); i++)
2567         {
2568           if (pass_signals[i])
2569             count++;
2570         }
2571       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2572       strcpy (pass_packet, "QPassSignals:");
2573       p = pass_packet + strlen (pass_packet);
2574       for (size_t i = 0; i < pass_signals.size (); i++)
2575         {
2576           if (pass_signals[i])
2577             {
2578               if (i >= 16)
2579                 *p++ = tohex (i >> 4);
2580               *p++ = tohex (i & 15);
2581               if (count)
2582                 *p++ = ';';
2583               else
2584                 break;
2585               count--;
2586             }
2587         }
2588       *p = 0;
2589       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2590         {
2591           putpkt (pass_packet);
2592           getpkt (&rs->buf, 0);
2593           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2594           if (rs->last_pass_packet)
2595             xfree (rs->last_pass_packet);
2596           rs->last_pass_packet = pass_packet;
2597         }
2598       else
2599         xfree (pass_packet);
2600     }
2601 }
2602
2603 /* If 'QCatchSyscalls' is supported, tell the remote stub
2604    to report syscalls to GDB.  */
2605
2606 int
2607 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2608                                        gdb::array_view<const int> syscall_counts)
2609 {
2610   const char *catch_packet;
2611   enum packet_result result;
2612   int n_sysno = 0;
2613
2614   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2615     {
2616       /* Not supported.  */
2617       return 1;
2618     }
2619
2620   if (needed && any_count == 0)
2621     {
2622       /* Count how many syscalls are to be caught.  */
2623       for (size_t i = 0; i < syscall_counts.size (); i++)
2624         {
2625           if (syscall_counts[i] != 0)
2626             n_sysno++;
2627         }
2628     }
2629
2630   if (remote_debug)
2631     {
2632       fprintf_unfiltered (gdb_stdlog,
2633                           "remote_set_syscall_catchpoint "
2634                           "pid %d needed %d any_count %d n_sysno %d\n",
2635                           pid, needed, any_count, n_sysno);
2636     }
2637
2638   std::string built_packet;
2639   if (needed)
2640     {
2641       /* Prepare a packet with the sysno list, assuming max 8+1
2642          characters for a sysno.  If the resulting packet size is too
2643          big, fallback on the non-selective packet.  */
2644       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2645       built_packet.reserve (maxpktsz);
2646       built_packet = "QCatchSyscalls:1";
2647       if (any_count == 0)
2648         {
2649           /* Add in each syscall to be caught.  */
2650           for (size_t i = 0; i < syscall_counts.size (); i++)
2651             {
2652               if (syscall_counts[i] != 0)
2653                 string_appendf (built_packet, ";%zx", i);
2654             }
2655         }
2656       if (built_packet.size () > get_remote_packet_size ())
2657         {
2658           /* catch_packet too big.  Fallback to less efficient
2659              non selective mode, with GDB doing the filtering.  */
2660           catch_packet = "QCatchSyscalls:1";
2661         }
2662       else
2663         catch_packet = built_packet.c_str ();
2664     }
2665   else
2666     catch_packet = "QCatchSyscalls:0";
2667
2668   struct remote_state *rs = get_remote_state ();
2669
2670   putpkt (catch_packet);
2671   getpkt (&rs->buf, 0);
2672   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2673   if (result == PACKET_OK)
2674     return 0;
2675   else
2676     return -1;
2677 }
2678
2679 /* If 'QProgramSignals' is supported, tell the remote stub what
2680    signals it should pass through to the inferior when detaching.  */
2681
2682 void
2683 remote_target::program_signals (gdb::array_view<const unsigned char> signals)
2684 {
2685   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2686     {
2687       char *packet, *p;
2688       int count = 0;
2689       struct remote_state *rs = get_remote_state ();
2690
2691       gdb_assert (signals.size () < 256);
2692       for (size_t i = 0; i < signals.size (); i++)
2693         {
2694           if (signals[i])
2695             count++;
2696         }
2697       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2698       strcpy (packet, "QProgramSignals:");
2699       p = packet + strlen (packet);
2700       for (size_t i = 0; i < signals.size (); i++)
2701         {
2702           if (signal_pass_state (i))
2703             {
2704               if (i >= 16)
2705                 *p++ = tohex (i >> 4);
2706               *p++ = tohex (i & 15);
2707               if (count)
2708                 *p++ = ';';
2709               else
2710                 break;
2711               count--;
2712             }
2713         }
2714       *p = 0;
2715       if (!rs->last_program_signals_packet
2716           || strcmp (rs->last_program_signals_packet, packet) != 0)
2717         {
2718           putpkt (packet);
2719           getpkt (&rs->buf, 0);
2720           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2721           xfree (rs->last_program_signals_packet);
2722           rs->last_program_signals_packet = packet;
2723         }
2724       else
2725         xfree (packet);
2726     }
2727 }
2728
2729 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2730    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2731    thread.  If GEN is set, set the general thread, if not, then set
2732    the step/continue thread.  */
2733 void
2734 remote_target::set_thread (ptid_t ptid, int gen)
2735 {
2736   struct remote_state *rs = get_remote_state ();
2737   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2738   char *buf = rs->buf.data ();
2739   char *endbuf = buf + get_remote_packet_size ();
2740
2741   if (state == ptid)
2742     return;
2743
2744   *buf++ = 'H';
2745   *buf++ = gen ? 'g' : 'c';
2746   if (ptid == magic_null_ptid)
2747     xsnprintf (buf, endbuf - buf, "0");
2748   else if (ptid == any_thread_ptid)
2749     xsnprintf (buf, endbuf - buf, "0");
2750   else if (ptid == minus_one_ptid)
2751     xsnprintf (buf, endbuf - buf, "-1");
2752   else
2753     write_ptid (buf, endbuf, ptid);
2754   putpkt (rs->buf);
2755   getpkt (&rs->buf, 0);
2756   if (gen)
2757     rs->general_thread = ptid;
2758   else
2759     rs->continue_thread = ptid;
2760 }
2761
2762 void
2763 remote_target::set_general_thread (ptid_t ptid)
2764 {
2765   set_thread (ptid, 1);
2766 }
2767
2768 void
2769 remote_target::set_continue_thread (ptid_t ptid)
2770 {
2771   set_thread (ptid, 0);
2772 }
2773
2774 /* Change the remote current process.  Which thread within the process
2775    ends up selected isn't important, as long as it is the same process
2776    as what INFERIOR_PTID points to.
2777
2778    This comes from that fact that there is no explicit notion of
2779    "selected process" in the protocol.  The selected process for
2780    general operations is the process the selected general thread
2781    belongs to.  */
2782
2783 void
2784 remote_target::set_general_process ()
2785 {
2786   struct remote_state *rs = get_remote_state ();
2787
2788   /* If the remote can't handle multiple processes, don't bother.  */
2789   if (!remote_multi_process_p (rs))
2790     return;
2791
2792   /* We only need to change the remote current thread if it's pointing
2793      at some other process.  */
2794   if (rs->general_thread.pid () != inferior_ptid.pid ())
2795     set_general_thread (inferior_ptid);
2796 }
2797
2798 \f
2799 /* Return nonzero if this is the main thread that we made up ourselves
2800    to model non-threaded targets as single-threaded.  */
2801
2802 static int
2803 remote_thread_always_alive (ptid_t ptid)
2804 {
2805   if (ptid == magic_null_ptid)
2806     /* The main thread is always alive.  */
2807     return 1;
2808
2809   if (ptid.pid () != 0 && ptid.lwp () == 0)
2810     /* The main thread is always alive.  This can happen after a
2811        vAttach, if the remote side doesn't support
2812        multi-threading.  */
2813     return 1;
2814
2815   return 0;
2816 }
2817
2818 /* Return nonzero if the thread PTID is still alive on the remote
2819    system.  */
2820
2821 bool
2822 remote_target::thread_alive (ptid_t ptid)
2823 {
2824   struct remote_state *rs = get_remote_state ();
2825   char *p, *endp;
2826
2827   /* Check if this is a thread that we made up ourselves to model
2828      non-threaded targets as single-threaded.  */
2829   if (remote_thread_always_alive (ptid))
2830     return 1;
2831
2832   p = rs->buf.data ();
2833   endp = p + get_remote_packet_size ();
2834
2835   *p++ = 'T';
2836   write_ptid (p, endp, ptid);
2837
2838   putpkt (rs->buf);
2839   getpkt (&rs->buf, 0);
2840   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2841 }
2842
2843 /* Return a pointer to a thread name if we know it and NULL otherwise.
2844    The thread_info object owns the memory for the name.  */
2845
2846 const char *
2847 remote_target::thread_name (struct thread_info *info)
2848 {
2849   if (info->priv != NULL)
2850     {
2851       const std::string &name = get_remote_thread_info (info)->name;
2852       return !name.empty () ? name.c_str () : NULL;
2853     }
2854
2855   return NULL;
2856 }
2857
2858 /* About these extended threadlist and threadinfo packets.  They are
2859    variable length packets but, the fields within them are often fixed
2860    length.  They are redundent enough to send over UDP as is the
2861    remote protocol in general.  There is a matching unit test module
2862    in libstub.  */
2863
2864 /* WARNING: This threadref data structure comes from the remote O.S.,
2865    libstub protocol encoding, and remote.c.  It is not particularly
2866    changable.  */
2867
2868 /* Right now, the internal structure is int. We want it to be bigger.
2869    Plan to fix this.  */
2870
2871 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2872
2873 /* gdb_ext_thread_info is an internal GDB data structure which is
2874    equivalent to the reply of the remote threadinfo packet.  */
2875
2876 struct gdb_ext_thread_info
2877   {
2878     threadref threadid;         /* External form of thread reference.  */
2879     int active;                 /* Has state interesting to GDB?
2880                                    regs, stack.  */
2881     char display[256];          /* Brief state display, name,
2882                                    blocked/suspended.  */
2883     char shortname[32];         /* To be used to name threads.  */
2884     char more_display[256];     /* Long info, statistics, queue depth,
2885                                    whatever.  */
2886   };
2887
2888 /* The volume of remote transfers can be limited by submitting
2889    a mask containing bits specifying the desired information.
2890    Use a union of these values as the 'selection' parameter to
2891    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2892
2893 #define TAG_THREADID 1
2894 #define TAG_EXISTS 2
2895 #define TAG_DISPLAY 4
2896 #define TAG_THREADNAME 8
2897 #define TAG_MOREDISPLAY 16
2898
2899 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2900
2901 static char *unpack_nibble (char *buf, int *val);
2902
2903 static char *unpack_byte (char *buf, int *value);
2904
2905 static char *pack_int (char *buf, int value);
2906
2907 static char *unpack_int (char *buf, int *value);
2908
2909 static char *unpack_string (char *src, char *dest, int length);
2910
2911 static char *pack_threadid (char *pkt, threadref *id);
2912
2913 static char *unpack_threadid (char *inbuf, threadref *id);
2914
2915 void int_to_threadref (threadref *id, int value);
2916
2917 static int threadref_to_int (threadref *ref);
2918
2919 static void copy_threadref (threadref *dest, threadref *src);
2920
2921 static int threadmatch (threadref *dest, threadref *src);
2922
2923 static char *pack_threadinfo_request (char *pkt, int mode,
2924                                       threadref *id);
2925
2926 static char *pack_threadlist_request (char *pkt, int startflag,
2927                                       int threadcount,
2928                                       threadref *nextthread);
2929
2930 static int remote_newthread_step (threadref *ref, void *context);
2931
2932
2933 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2934    buffer we're allowed to write to.  Returns
2935    BUF+CHARACTERS_WRITTEN.  */
2936
2937 char *
2938 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2939 {
2940   int pid, tid;
2941   struct remote_state *rs = get_remote_state ();
2942
2943   if (remote_multi_process_p (rs))
2944     {
2945       pid = ptid.pid ();
2946       if (pid < 0)
2947         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2948       else
2949         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2950     }
2951   tid = ptid.lwp ();
2952   if (tid < 0)
2953     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2954   else
2955     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2956
2957   return buf;
2958 }
2959
2960 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2961    last parsed char.  Returns null_ptid if no thread id is found, and
2962    throws an error if the thread id has an invalid format.  */
2963
2964 static ptid_t
2965 read_ptid (const char *buf, const char **obuf)
2966 {
2967   const char *p = buf;
2968   const char *pp;
2969   ULONGEST pid = 0, tid = 0;
2970
2971   if (*p == 'p')
2972     {
2973       /* Multi-process ptid.  */
2974       pp = unpack_varlen_hex (p + 1, &pid);
2975       if (*pp != '.')
2976         error (_("invalid remote ptid: %s"), p);
2977
2978       p = pp;
2979       pp = unpack_varlen_hex (p + 1, &tid);
2980       if (obuf)
2981         *obuf = pp;
2982       return ptid_t (pid, tid, 0);
2983     }
2984
2985   /* No multi-process.  Just a tid.  */
2986   pp = unpack_varlen_hex (p, &tid);
2987
2988   /* Return null_ptid when no thread id is found.  */
2989   if (p == pp)
2990     {
2991       if (obuf)
2992         *obuf = pp;
2993       return null_ptid;
2994     }
2995
2996   /* Since the stub is not sending a process id, then default to
2997      what's in inferior_ptid, unless it's null at this point.  If so,
2998      then since there's no way to know the pid of the reported
2999      threads, use the magic number.  */
3000   if (inferior_ptid == null_ptid)
3001     pid = magic_null_ptid.pid ();
3002   else
3003     pid = inferior_ptid.pid ();
3004
3005   if (obuf)
3006     *obuf = pp;
3007   return ptid_t (pid, tid, 0);
3008 }
3009
3010 static int
3011 stubhex (int ch)
3012 {
3013   if (ch >= 'a' && ch <= 'f')
3014     return ch - 'a' + 10;
3015   if (ch >= '0' && ch <= '9')
3016     return ch - '0';
3017   if (ch >= 'A' && ch <= 'F')
3018     return ch - 'A' + 10;
3019   return -1;
3020 }
3021
3022 static int
3023 stub_unpack_int (char *buff, int fieldlength)
3024 {
3025   int nibble;
3026   int retval = 0;
3027
3028   while (fieldlength)
3029     {
3030       nibble = stubhex (*buff++);
3031       retval |= nibble;
3032       fieldlength--;
3033       if (fieldlength)
3034         retval = retval << 4;
3035     }
3036   return retval;
3037 }
3038
3039 static char *
3040 unpack_nibble (char *buf, int *val)
3041 {
3042   *val = fromhex (*buf++);
3043   return buf;
3044 }
3045
3046 static char *
3047 unpack_byte (char *buf, int *value)
3048 {
3049   *value = stub_unpack_int (buf, 2);
3050   return buf + 2;
3051 }
3052
3053 static char *
3054 pack_int (char *buf, int value)
3055 {
3056   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3057   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3058   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3059   buf = pack_hex_byte (buf, (value & 0xff));
3060   return buf;
3061 }
3062
3063 static char *
3064 unpack_int (char *buf, int *value)
3065 {
3066   *value = stub_unpack_int (buf, 8);
3067   return buf + 8;
3068 }
3069
3070 #if 0                   /* Currently unused, uncomment when needed.  */
3071 static char *pack_string (char *pkt, char *string);
3072
3073 static char *
3074 pack_string (char *pkt, char *string)
3075 {
3076   char ch;
3077   int len;
3078
3079   len = strlen (string);
3080   if (len > 200)
3081     len = 200;          /* Bigger than most GDB packets, junk???  */
3082   pkt = pack_hex_byte (pkt, len);
3083   while (len-- > 0)
3084     {
3085       ch = *string++;
3086       if ((ch == '\0') || (ch == '#'))
3087         ch = '*';               /* Protect encapsulation.  */
3088       *pkt++ = ch;
3089     }
3090   return pkt;
3091 }
3092 #endif /* 0 (unused) */
3093
3094 static char *
3095 unpack_string (char *src, char *dest, int length)
3096 {
3097   while (length--)
3098     *dest++ = *src++;
3099   *dest = '\0';
3100   return src;
3101 }
3102
3103 static char *
3104 pack_threadid (char *pkt, threadref *id)
3105 {
3106   char *limit;
3107   unsigned char *altid;
3108
3109   altid = (unsigned char *) id;
3110   limit = pkt + BUF_THREAD_ID_SIZE;
3111   while (pkt < limit)
3112     pkt = pack_hex_byte (pkt, *altid++);
3113   return pkt;
3114 }
3115
3116
3117 static char *
3118 unpack_threadid (char *inbuf, threadref *id)
3119 {
3120   char *altref;
3121   char *limit = inbuf + BUF_THREAD_ID_SIZE;
3122   int x, y;
3123
3124   altref = (char *) id;
3125
3126   while (inbuf < limit)
3127     {
3128       x = stubhex (*inbuf++);
3129       y = stubhex (*inbuf++);
3130       *altref++ = (x << 4) | y;
3131     }
3132   return inbuf;
3133 }
3134
3135 /* Externally, threadrefs are 64 bits but internally, they are still
3136    ints.  This is due to a mismatch of specifications.  We would like
3137    to use 64bit thread references internally.  This is an adapter
3138    function.  */
3139
3140 void
3141 int_to_threadref (threadref *id, int value)
3142 {
3143   unsigned char *scan;
3144
3145   scan = (unsigned char *) id;
3146   {
3147     int i = 4;
3148     while (i--)
3149       *scan++ = 0;
3150   }
3151   *scan++ = (value >> 24) & 0xff;
3152   *scan++ = (value >> 16) & 0xff;
3153   *scan++ = (value >> 8) & 0xff;
3154   *scan++ = (value & 0xff);
3155 }
3156
3157 static int
3158 threadref_to_int (threadref *ref)
3159 {
3160   int i, value = 0;
3161   unsigned char *scan;
3162
3163   scan = *ref;
3164   scan += 4;
3165   i = 4;
3166   while (i-- > 0)
3167     value = (value << 8) | ((*scan++) & 0xff);
3168   return value;
3169 }
3170
3171 static void
3172 copy_threadref (threadref *dest, threadref *src)
3173 {
3174   int i;
3175   unsigned char *csrc, *cdest;
3176
3177   csrc = (unsigned char *) src;
3178   cdest = (unsigned char *) dest;
3179   i = 8;
3180   while (i--)
3181     *cdest++ = *csrc++;
3182 }
3183
3184 static int
3185 threadmatch (threadref *dest, threadref *src)
3186 {
3187   /* Things are broken right now, so just assume we got a match.  */
3188 #if 0
3189   unsigned char *srcp, *destp;
3190   int i, result;
3191   srcp = (char *) src;
3192   destp = (char *) dest;
3193
3194   result = 1;
3195   while (i-- > 0)
3196     result &= (*srcp++ == *destp++) ? 1 : 0;
3197   return result;
3198 #endif
3199   return 1;
3200 }
3201
3202 /*
3203    threadid:1,        # always request threadid
3204    context_exists:2,
3205    display:4,
3206    unique_name:8,
3207    more_display:16
3208  */
3209
3210 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
3211
3212 static char *
3213 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3214 {
3215   *pkt++ = 'q';                         /* Info Query */
3216   *pkt++ = 'P';                         /* process or thread info */
3217   pkt = pack_int (pkt, mode);           /* mode */
3218   pkt = pack_threadid (pkt, id);        /* threadid */
3219   *pkt = '\0';                          /* terminate */
3220   return pkt;
3221 }
3222
3223 /* These values tag the fields in a thread info response packet.  */
3224 /* Tagging the fields allows us to request specific fields and to
3225    add more fields as time goes by.  */
3226
3227 #define TAG_THREADID 1          /* Echo the thread identifier.  */
3228 #define TAG_EXISTS 2            /* Is this process defined enough to
3229                                    fetch registers and its stack?  */
3230 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
3231 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
3232 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
3233                                    the process.  */
3234
3235 int
3236 remote_target::remote_unpack_thread_info_response (char *pkt,
3237                                                    threadref *expectedref,
3238                                                    gdb_ext_thread_info *info)
3239 {
3240   struct remote_state *rs = get_remote_state ();
3241   int mask, length;
3242   int tag;
3243   threadref ref;
3244   char *limit = pkt + rs->buf.size (); /* Plausible parsing limit.  */
3245   int retval = 1;
3246
3247   /* info->threadid = 0; FIXME: implement zero_threadref.  */
3248   info->active = 0;
3249   info->display[0] = '\0';
3250   info->shortname[0] = '\0';
3251   info->more_display[0] = '\0';
3252
3253   /* Assume the characters indicating the packet type have been
3254      stripped.  */
3255   pkt = unpack_int (pkt, &mask);        /* arg mask */
3256   pkt = unpack_threadid (pkt, &ref);
3257
3258   if (mask == 0)
3259     warning (_("Incomplete response to threadinfo request."));
3260   if (!threadmatch (&ref, expectedref))
3261     {                   /* This is an answer to a different request.  */
3262       warning (_("ERROR RMT Thread info mismatch."));
3263       return 0;
3264     }
3265   copy_threadref (&info->threadid, &ref);
3266
3267   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
3268
3269   /* Packets are terminated with nulls.  */
3270   while ((pkt < limit) && mask && *pkt)
3271     {
3272       pkt = unpack_int (pkt, &tag);     /* tag */
3273       pkt = unpack_byte (pkt, &length); /* length */
3274       if (!(tag & mask))                /* Tags out of synch with mask.  */
3275         {
3276           warning (_("ERROR RMT: threadinfo tag mismatch."));
3277           retval = 0;
3278           break;
3279         }
3280       if (tag == TAG_THREADID)
3281         {
3282           if (length != 16)
3283             {
3284               warning (_("ERROR RMT: length of threadid is not 16."));
3285               retval = 0;
3286               break;
3287             }
3288           pkt = unpack_threadid (pkt, &ref);
3289           mask = mask & ~TAG_THREADID;
3290           continue;
3291         }
3292       if (tag == TAG_EXISTS)
3293         {
3294           info->active = stub_unpack_int (pkt, length);
3295           pkt += length;
3296           mask = mask & ~(TAG_EXISTS);
3297           if (length > 8)
3298             {
3299               warning (_("ERROR RMT: 'exists' length too long."));
3300               retval = 0;
3301               break;
3302             }
3303           continue;
3304         }
3305       if (tag == TAG_THREADNAME)
3306         {
3307           pkt = unpack_string (pkt, &info->shortname[0], length);
3308           mask = mask & ~TAG_THREADNAME;
3309           continue;
3310         }
3311       if (tag == TAG_DISPLAY)
3312         {
3313           pkt = unpack_string (pkt, &info->display[0], length);
3314           mask = mask & ~TAG_DISPLAY;
3315           continue;
3316         }
3317       if (tag == TAG_MOREDISPLAY)
3318         {
3319           pkt = unpack_string (pkt, &info->more_display[0], length);
3320           mask = mask & ~TAG_MOREDISPLAY;
3321           continue;
3322         }
3323       warning (_("ERROR RMT: unknown thread info tag."));
3324       break;                    /* Not a tag we know about.  */
3325     }
3326   return retval;
3327 }
3328
3329 int
3330 remote_target::remote_get_threadinfo (threadref *threadid,
3331                                       int fieldset,
3332                                       gdb_ext_thread_info *info)
3333 {
3334   struct remote_state *rs = get_remote_state ();
3335   int result;
3336
3337   pack_threadinfo_request (rs->buf.data (), fieldset, threadid);
3338   putpkt (rs->buf);
3339   getpkt (&rs->buf, 0);
3340
3341   if (rs->buf[0] == '\0')
3342     return 0;
3343
3344   result = remote_unpack_thread_info_response (&rs->buf[2],
3345                                                threadid, info);
3346   return result;
3347 }
3348
3349 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3350
3351 static char *
3352 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3353                          threadref *nextthread)
3354 {
3355   *pkt++ = 'q';                 /* info query packet */
3356   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3357   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3358   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3359   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3360   *pkt = '\0';
3361   return pkt;
3362 }
3363
3364 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3365
3366 int
3367 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3368                                           threadref *original_echo,
3369                                           threadref *resultlist,
3370                                           int *doneflag)
3371 {
3372   struct remote_state *rs = get_remote_state ();
3373   char *limit;
3374   int count, resultcount, done;
3375
3376   resultcount = 0;
3377   /* Assume the 'q' and 'M chars have been stripped.  */
3378   limit = pkt + (rs->buf.size () - BUF_THREAD_ID_SIZE);
3379   /* done parse past here */
3380   pkt = unpack_byte (pkt, &count);      /* count field */
3381   pkt = unpack_nibble (pkt, &done);
3382   /* The first threadid is the argument threadid.  */
3383   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3384   while ((count-- > 0) && (pkt < limit))
3385     {
3386       pkt = unpack_threadid (pkt, resultlist++);
3387       if (resultcount++ >= result_limit)
3388         break;
3389     }
3390   if (doneflag)
3391     *doneflag = done;
3392   return resultcount;
3393 }
3394
3395 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3396    qL packet is not supported, 0 on error and 1 on success.  */
3397
3398 int
3399 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3400                                       int result_limit, int *done, int *result_count,
3401                                       threadref *threadlist)
3402 {
3403   struct remote_state *rs = get_remote_state ();
3404   int result = 1;
3405
3406   /* Trancate result limit to be smaller than the packet size.  */
3407   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3408       >= get_remote_packet_size ())
3409     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3410
3411   pack_threadlist_request (rs->buf.data (), startflag, result_limit,
3412                            nextthread);
3413   putpkt (rs->buf);
3414   getpkt (&rs->buf, 0);
3415   if (rs->buf[0] == '\0')
3416     {
3417       /* Packet not supported.  */
3418       return -1;
3419     }
3420
3421   *result_count =
3422     parse_threadlist_response (&rs->buf[2], result_limit,
3423                                &rs->echo_nextthread, threadlist, done);
3424
3425   if (!threadmatch (&rs->echo_nextthread, nextthread))
3426     {
3427       /* FIXME: This is a good reason to drop the packet.  */
3428       /* Possably, there is a duplicate response.  */
3429       /* Possabilities :
3430          retransmit immediatly - race conditions
3431          retransmit after timeout - yes
3432          exit
3433          wait for packet, then exit
3434        */
3435       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3436       return 0;                 /* I choose simply exiting.  */
3437     }
3438   if (*result_count <= 0)
3439     {
3440       if (*done != 1)
3441         {
3442           warning (_("RMT ERROR : failed to get remote thread list."));
3443           result = 0;
3444         }
3445       return result;            /* break; */
3446     }
3447   if (*result_count > result_limit)
3448     {
3449       *result_count = 0;
3450       warning (_("RMT ERROR: threadlist response longer than requested."));
3451       return 0;
3452     }
3453   return result;
3454 }
3455
3456 /* Fetch the list of remote threads, with the qL packet, and call
3457    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3458    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3459    STEPFUNCTION returns false.  If the packet is not supported,
3460    returns -1.  */
3461
3462 int
3463 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3464                                            void *context, int looplimit)
3465 {
3466   struct remote_state *rs = get_remote_state ();
3467   int done, i, result_count;
3468   int startflag = 1;
3469   int result = 1;
3470   int loopcount = 0;
3471
3472   done = 0;
3473   while (!done)
3474     {
3475       if (loopcount++ > looplimit)
3476         {
3477           result = 0;
3478           warning (_("Remote fetch threadlist -infinite loop-."));
3479           break;
3480         }
3481       result = remote_get_threadlist (startflag, &rs->nextthread,
3482                                       MAXTHREADLISTRESULTS,
3483                                       &done, &result_count,
3484                                       rs->resultthreadlist);
3485       if (result <= 0)
3486         break;
3487       /* Clear for later iterations.  */
3488       startflag = 0;
3489       /* Setup to resume next batch of thread references, set nextthread.  */
3490       if (result_count >= 1)
3491         copy_threadref (&rs->nextthread,
3492                         &rs->resultthreadlist[result_count - 1]);
3493       i = 0;
3494       while (result_count--)
3495         {
3496           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3497             {
3498               result = 0;
3499               break;
3500             }
3501         }
3502     }
3503   return result;
3504 }
3505
3506 /* A thread found on the remote target.  */
3507
3508 struct thread_item
3509 {
3510   explicit thread_item (ptid_t ptid_)
3511   : ptid (ptid_)
3512   {}
3513
3514   thread_item (thread_item &&other) = default;
3515   thread_item &operator= (thread_item &&other) = default;
3516
3517   DISABLE_COPY_AND_ASSIGN (thread_item);
3518
3519   /* The thread's PTID.  */
3520   ptid_t ptid;
3521
3522   /* The thread's extra info.  */
3523   std::string extra;
3524
3525   /* The thread's name.  */
3526   std::string name;
3527
3528   /* The core the thread was running on.  -1 if not known.  */
3529   int core = -1;
3530
3531   /* The thread handle associated with the thread.  */
3532   gdb::byte_vector thread_handle;
3533 };
3534
3535 /* Context passed around to the various methods listing remote
3536    threads.  As new threads are found, they're added to the ITEMS
3537    vector.  */
3538
3539 struct threads_listing_context
3540 {
3541   /* Return true if this object contains an entry for a thread with ptid
3542      PTID.  */
3543
3544   bool contains_thread (ptid_t ptid) const
3545   {
3546     auto match_ptid = [&] (const thread_item &item)
3547       {
3548         return item.ptid == ptid;
3549       };
3550
3551     auto it = std::find_if (this->items.begin (),
3552                             this->items.end (),
3553                             match_ptid);
3554
3555     return it != this->items.end ();
3556   }
3557
3558   /* Remove the thread with ptid PTID.  */
3559
3560   void remove_thread (ptid_t ptid)
3561   {
3562     auto match_ptid = [&] (const thread_item &item)
3563       {
3564         return item.ptid == ptid;
3565       };
3566
3567     auto it = std::remove_if (this->items.begin (),
3568                               this->items.end (),
3569                               match_ptid);
3570
3571     if (it != this->items.end ())
3572       this->items.erase (it);
3573   }
3574
3575   /* The threads found on the remote target.  */
3576   std::vector<thread_item> items;
3577 };
3578
3579 static int
3580 remote_newthread_step (threadref *ref, void *data)
3581 {
3582   struct threads_listing_context *context
3583     = (struct threads_listing_context *) data;
3584   int pid = inferior_ptid.pid ();
3585   int lwp = threadref_to_int (ref);
3586   ptid_t ptid (pid, lwp);
3587
3588   context->items.emplace_back (ptid);
3589
3590   return 1;                     /* continue iterator */
3591 }
3592
3593 #define CRAZY_MAX_THREADS 1000
3594
3595 ptid_t
3596 remote_target::remote_current_thread (ptid_t oldpid)
3597 {
3598   struct remote_state *rs = get_remote_state ();
3599
3600   putpkt ("qC");
3601   getpkt (&rs->buf, 0);
3602   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3603     {
3604       const char *obuf;
3605       ptid_t result;
3606
3607       result = read_ptid (&rs->buf[2], &obuf);
3608       if (*obuf != '\0' && remote_debug)
3609         fprintf_unfiltered (gdb_stdlog,
3610                             "warning: garbage in qC reply\n");
3611
3612       return result;
3613     }
3614   else
3615     return oldpid;
3616 }
3617
3618 /* List remote threads using the deprecated qL packet.  */
3619
3620 int
3621 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3622 {
3623   if (remote_threadlist_iterator (remote_newthread_step, context,
3624                                   CRAZY_MAX_THREADS) >= 0)
3625     return 1;
3626
3627   return 0;
3628 }
3629
3630 #if defined(HAVE_LIBEXPAT)
3631
3632 static void
3633 start_thread (struct gdb_xml_parser *parser,
3634               const struct gdb_xml_element *element,
3635               void *user_data,
3636               std::vector<gdb_xml_value> &attributes)
3637 {
3638   struct threads_listing_context *data
3639     = (struct threads_listing_context *) user_data;
3640   struct gdb_xml_value *attr;
3641
3642   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3643   ptid_t ptid = read_ptid (id, NULL);
3644
3645   data->items.emplace_back (ptid);
3646   thread_item &item = data->items.back ();
3647
3648   attr = xml_find_attribute (attributes, "core");
3649   if (attr != NULL)
3650     item.core = *(ULONGEST *) attr->value.get ();
3651
3652   attr = xml_find_attribute (attributes, "name");
3653   if (attr != NULL)
3654     item.name = (const char *) attr->value.get ();
3655
3656   attr = xml_find_attribute (attributes, "handle");
3657   if (attr != NULL)
3658     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3659 }
3660
3661 static void
3662 end_thread (struct gdb_xml_parser *parser,
3663             const struct gdb_xml_element *element,
3664             void *user_data, const char *body_text)
3665 {
3666   struct threads_listing_context *data
3667     = (struct threads_listing_context *) user_data;
3668
3669   if (body_text != NULL && *body_text != '\0')
3670     data->items.back ().extra = body_text;
3671 }
3672
3673 const struct gdb_xml_attribute thread_attributes[] = {
3674   { "id", GDB_XML_AF_NONE, NULL, NULL },
3675   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3676   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3677   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3678   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3679 };
3680
3681 const struct gdb_xml_element thread_children[] = {
3682   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3683 };
3684
3685 const struct gdb_xml_element threads_children[] = {
3686   { "thread", thread_attributes, thread_children,
3687     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3688     start_thread, end_thread },
3689   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3690 };
3691
3692 const struct gdb_xml_element threads_elements[] = {
3693   { "threads", NULL, threads_children,
3694     GDB_XML_EF_NONE, NULL, NULL },
3695   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3696 };
3697
3698 #endif
3699
3700 /* List remote threads using qXfer:threads:read.  */
3701
3702 int
3703 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3704 {
3705 #if defined(HAVE_LIBEXPAT)
3706   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3707     {
3708       gdb::optional<gdb::char_vector> xml
3709         = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3710
3711       if (xml && (*xml)[0] != '\0')
3712         {
3713           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3714                                threads_elements, xml->data (), context);
3715         }
3716
3717       return 1;
3718     }
3719 #endif
3720
3721   return 0;
3722 }
3723
3724 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3725
3726 int
3727 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3728 {
3729   struct remote_state *rs = get_remote_state ();
3730
3731   if (rs->use_threadinfo_query)
3732     {
3733       const char *bufp;
3734
3735       putpkt ("qfThreadInfo");
3736       getpkt (&rs->buf, 0);
3737       bufp = rs->buf.data ();
3738       if (bufp[0] != '\0')              /* q packet recognized */
3739         {
3740           while (*bufp++ == 'm')        /* reply contains one or more TID */
3741             {
3742               do
3743                 {
3744                   ptid_t ptid = read_ptid (bufp, &bufp);
3745                   context->items.emplace_back (ptid);
3746                 }
3747               while (*bufp++ == ',');   /* comma-separated list */
3748               putpkt ("qsThreadInfo");
3749               getpkt (&rs->buf, 0);
3750               bufp = rs->buf.data ();
3751             }
3752           return 1;
3753         }
3754       else
3755         {
3756           /* Packet not recognized.  */
3757           rs->use_threadinfo_query = 0;
3758         }
3759     }
3760
3761   return 0;
3762 }
3763
3764 /* Implement the to_update_thread_list function for the remote
3765    targets.  */
3766
3767 void
3768 remote_target::update_thread_list ()
3769 {
3770   struct threads_listing_context context;
3771   int got_list = 0;
3772
3773   /* We have a few different mechanisms to fetch the thread list.  Try
3774      them all, starting with the most preferred one first, falling
3775      back to older methods.  */
3776   if (remote_get_threads_with_qxfer (&context)
3777       || remote_get_threads_with_qthreadinfo (&context)
3778       || remote_get_threads_with_ql (&context))
3779     {
3780       got_list = 1;
3781
3782       if (context.items.empty ()
3783           && remote_thread_always_alive (inferior_ptid))
3784         {
3785           /* Some targets don't really support threads, but still
3786              reply an (empty) thread list in response to the thread
3787              listing packets, instead of replying "packet not
3788              supported".  Exit early so we don't delete the main
3789              thread.  */
3790           return;
3791         }
3792
3793       /* CONTEXT now holds the current thread list on the remote
3794          target end.  Delete GDB-side threads no longer found on the
3795          target.  */
3796       for (thread_info *tp : all_threads_safe ())
3797         {
3798           if (!context.contains_thread (tp->ptid))
3799             {
3800               /* Not found.  */
3801               delete_thread (tp);
3802             }
3803         }
3804
3805       /* Remove any unreported fork child threads from CONTEXT so
3806          that we don't interfere with follow fork, which is where
3807          creation of such threads is handled.  */
3808       remove_new_fork_children (&context);
3809
3810       /* And now add threads we don't know about yet to our list.  */
3811       for (thread_item &item : context.items)
3812         {
3813           if (item.ptid != null_ptid)
3814             {
3815               /* In non-stop mode, we assume new found threads are
3816                  executing until proven otherwise with a stop reply.
3817                  In all-stop, we can only get here if all threads are
3818                  stopped.  */
3819               int executing = target_is_non_stop_p () ? 1 : 0;
3820
3821               remote_notice_new_inferior (item.ptid, executing);
3822
3823               thread_info *tp = find_thread_ptid (item.ptid);
3824               remote_thread_info *info = get_remote_thread_info (tp);
3825               info->core = item.core;
3826               info->extra = std::move (item.extra);
3827               info->name = std::move (item.name);
3828               info->thread_handle = std::move (item.thread_handle);
3829             }
3830         }
3831     }
3832
3833   if (!got_list)
3834     {
3835       /* If no thread listing method is supported, then query whether
3836          each known thread is alive, one by one, with the T packet.
3837          If the target doesn't support threads at all, then this is a
3838          no-op.  See remote_thread_alive.  */
3839       prune_threads ();
3840     }
3841 }
3842
3843 /*
3844  * Collect a descriptive string about the given thread.
3845  * The target may say anything it wants to about the thread
3846  * (typically info about its blocked / runnable state, name, etc.).
3847  * This string will appear in the info threads display.
3848  *
3849  * Optional: targets are not required to implement this function.
3850  */
3851
3852 const char *
3853 remote_target::extra_thread_info (thread_info *tp)
3854 {
3855   struct remote_state *rs = get_remote_state ();
3856   int set;
3857   threadref id;
3858   struct gdb_ext_thread_info threadinfo;
3859
3860   if (rs->remote_desc == 0)             /* paranoia */
3861     internal_error (__FILE__, __LINE__,
3862                     _("remote_threads_extra_info"));
3863
3864   if (tp->ptid == magic_null_ptid
3865       || (tp->ptid.pid () != 0 && tp->ptid.lwp () == 0))
3866     /* This is the main thread which was added by GDB.  The remote
3867        server doesn't know about it.  */
3868     return NULL;
3869
3870   std::string &extra = get_remote_thread_info (tp)->extra;
3871
3872   /* If already have cached info, use it.  */
3873   if (!extra.empty ())
3874     return extra.c_str ();
3875
3876   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3877     {
3878       /* If we're using qXfer:threads:read, then the extra info is
3879          included in the XML.  So if we didn't have anything cached,
3880          it's because there's really no extra info.  */
3881       return NULL;
3882     }
3883
3884   if (rs->use_threadextra_query)
3885     {
3886       char *b = rs->buf.data ();
3887       char *endb = b + get_remote_packet_size ();
3888
3889       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3890       b += strlen (b);
3891       write_ptid (b, endb, tp->ptid);
3892
3893       putpkt (rs->buf);
3894       getpkt (&rs->buf, 0);
3895       if (rs->buf[0] != 0)
3896         {
3897           extra.resize (strlen (rs->buf.data ()) / 2);
3898           hex2bin (rs->buf.data (), (gdb_byte *) &extra[0], extra.size ());
3899           return extra.c_str ();
3900         }
3901     }
3902
3903   /* If the above query fails, fall back to the old method.  */
3904   rs->use_threadextra_query = 0;
3905   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3906     | TAG_MOREDISPLAY | TAG_DISPLAY;
3907   int_to_threadref (&id, tp->ptid.lwp ());
3908   if (remote_get_threadinfo (&id, set, &threadinfo))
3909     if (threadinfo.active)
3910       {
3911         if (*threadinfo.shortname)
3912           string_appendf (extra, " Name: %s", threadinfo.shortname);
3913         if (*threadinfo.display)
3914           {
3915             if (!extra.empty ())
3916               extra += ',';
3917             string_appendf (extra, " State: %s", threadinfo.display);
3918           }
3919         if (*threadinfo.more_display)
3920           {
3921             if (!extra.empty ())
3922               extra += ',';
3923             string_appendf (extra, " Priority: %s", threadinfo.more_display);
3924           }
3925         return extra.c_str ();
3926       }
3927   return NULL;
3928 }
3929 \f
3930
3931 bool
3932 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3933                                             struct static_tracepoint_marker *marker)
3934 {
3935   struct remote_state *rs = get_remote_state ();
3936   char *p = rs->buf.data ();
3937
3938   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3939   p += strlen (p);
3940   p += hexnumstr (p, addr);
3941   putpkt (rs->buf);
3942   getpkt (&rs->buf, 0);
3943   p = rs->buf.data ();
3944
3945   if (*p == 'E')
3946     error (_("Remote failure reply: %s"), p);
3947
3948   if (*p++ == 'm')
3949     {
3950       parse_static_tracepoint_marker_definition (p, NULL, marker);
3951       return true;
3952     }
3953
3954   return false;
3955 }
3956
3957 std::vector<static_tracepoint_marker>
3958 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3959 {
3960   struct remote_state *rs = get_remote_state ();
3961   std::vector<static_tracepoint_marker> markers;
3962   const char *p;
3963   static_tracepoint_marker marker;
3964
3965   /* Ask for a first packet of static tracepoint marker
3966      definition.  */
3967   putpkt ("qTfSTM");
3968   getpkt (&rs->buf, 0);
3969   p = rs->buf.data ();
3970   if (*p == 'E')
3971     error (_("Remote failure reply: %s"), p);
3972
3973   while (*p++ == 'm')
3974     {
3975       do
3976         {
3977           parse_static_tracepoint_marker_definition (p, &p, &marker);
3978
3979           if (strid == NULL || marker.str_id == strid)
3980             markers.push_back (std::move (marker));
3981         }
3982       while (*p++ == ',');      /* comma-separated list */
3983       /* Ask for another packet of static tracepoint definition.  */
3984       putpkt ("qTsSTM");
3985       getpkt (&rs->buf, 0);
3986       p = rs->buf.data ();
3987     }
3988
3989   return markers;
3990 }
3991
3992 \f
3993 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3994
3995 ptid_t
3996 remote_target::get_ada_task_ptid (long lwp, long thread)
3997 {
3998   return ptid_t (inferior_ptid.pid (), lwp, 0);
3999 }
4000 \f
4001
4002 /* Restart the remote side; this is an extended protocol operation.  */
4003
4004 void
4005 remote_target::extended_remote_restart ()
4006 {
4007   struct remote_state *rs = get_remote_state ();
4008
4009   /* Send the restart command; for reasons I don't understand the
4010      remote side really expects a number after the "R".  */
4011   xsnprintf (rs->buf.data (), get_remote_packet_size (), "R%x", 0);
4012   putpkt (rs->buf);
4013
4014   remote_fileio_reset ();
4015 }
4016 \f
4017 /* Clean up connection to a remote debugger.  */
4018
4019 void
4020 remote_target::close ()
4021 {
4022   /* Make sure we leave stdin registered in the event loop.  */
4023   terminal_ours ();
4024
4025   /* We don't have a connection to the remote stub anymore.  Get rid
4026      of all the inferiors and their threads we were controlling.
4027      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4028      will be unable to find the thread corresponding to (pid, 0, 0).  */
4029   inferior_ptid = null_ptid;
4030   discard_all_inferiors ();
4031
4032   trace_reset_local_state ();
4033
4034   delete this;
4035 }
4036
4037 remote_target::~remote_target ()
4038 {
4039   struct remote_state *rs = get_remote_state ();
4040
4041   /* Check for NULL because we may get here with a partially
4042      constructed target/connection.  */
4043   if (rs->remote_desc == nullptr)
4044     return;
4045
4046   serial_close (rs->remote_desc);
4047
4048   /* We are destroying the remote target, so we should discard
4049      everything of this target.  */
4050   discard_pending_stop_replies_in_queue ();
4051
4052   if (rs->remote_async_inferior_event_token)
4053     delete_async_event_handler (&rs->remote_async_inferior_event_token);
4054
4055   delete rs->notif_state;
4056 }
4057
4058 /* Query the remote side for the text, data and bss offsets.  */
4059
4060 void
4061 remote_target::get_offsets ()
4062 {
4063   struct remote_state *rs = get_remote_state ();
4064   char *buf;
4065   char *ptr;
4066   int lose, num_segments = 0, do_sections, do_segments;
4067   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4068   struct section_offsets *offs;
4069   struct symfile_segment_data *data;
4070
4071   if (symfile_objfile == NULL)
4072     return;
4073
4074   putpkt ("qOffsets");
4075   getpkt (&rs->buf, 0);
4076   buf = rs->buf.data ();
4077
4078   if (buf[0] == '\000')
4079     return;                     /* Return silently.  Stub doesn't support
4080                                    this command.  */
4081   if (buf[0] == 'E')
4082     {
4083       warning (_("Remote failure reply: %s"), buf);
4084       return;
4085     }
4086
4087   /* Pick up each field in turn.  This used to be done with scanf, but
4088      scanf will make trouble if CORE_ADDR size doesn't match
4089      conversion directives correctly.  The following code will work
4090      with any size of CORE_ADDR.  */
4091   text_addr = data_addr = bss_addr = 0;
4092   ptr = buf;
4093   lose = 0;
4094
4095   if (startswith (ptr, "Text="))
4096     {
4097       ptr += 5;
4098       /* Don't use strtol, could lose on big values.  */
4099       while (*ptr && *ptr != ';')
4100         text_addr = (text_addr << 4) + fromhex (*ptr++);
4101
4102       if (startswith (ptr, ";Data="))
4103         {
4104           ptr += 6;
4105           while (*ptr && *ptr != ';')
4106             data_addr = (data_addr << 4) + fromhex (*ptr++);
4107         }
4108       else
4109         lose = 1;
4110
4111       if (!lose && startswith (ptr, ";Bss="))
4112         {
4113           ptr += 5;
4114           while (*ptr && *ptr != ';')
4115             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4116
4117           if (bss_addr != data_addr)
4118             warning (_("Target reported unsupported offsets: %s"), buf);
4119         }
4120       else
4121         lose = 1;
4122     }
4123   else if (startswith (ptr, "TextSeg="))
4124     {
4125       ptr += 8;
4126       /* Don't use strtol, could lose on big values.  */
4127       while (*ptr && *ptr != ';')
4128         text_addr = (text_addr << 4) + fromhex (*ptr++);
4129       num_segments = 1;
4130
4131       if (startswith (ptr, ";DataSeg="))
4132         {
4133           ptr += 9;
4134           while (*ptr && *ptr != ';')
4135             data_addr = (data_addr << 4) + fromhex (*ptr++);
4136           num_segments++;
4137         }
4138     }
4139   else
4140     lose = 1;
4141
4142   if (lose)
4143     error (_("Malformed response to offset query, %s"), buf);
4144   else if (*ptr != '\0')
4145     warning (_("Target reported unsupported offsets: %s"), buf);
4146
4147   offs = ((struct section_offsets *)
4148           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4149   memcpy (offs, symfile_objfile->section_offsets,
4150           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4151
4152   data = get_symfile_segment_data (symfile_objfile->obfd);
4153   do_segments = (data != NULL);
4154   do_sections = num_segments == 0;
4155
4156   if (num_segments > 0)
4157     {
4158       segments[0] = text_addr;
4159       segments[1] = data_addr;
4160     }
4161   /* If we have two segments, we can still try to relocate everything
4162      by assuming that the .text and .data offsets apply to the whole
4163      text and data segments.  Convert the offsets given in the packet
4164      to base addresses for symfile_map_offsets_to_segments.  */
4165   else if (data && data->num_segments == 2)
4166     {
4167       segments[0] = data->segment_bases[0] + text_addr;
4168       segments[1] = data->segment_bases[1] + data_addr;
4169       num_segments = 2;
4170     }
4171   /* If the object file has only one segment, assume that it is text
4172      rather than data; main programs with no writable data are rare,
4173      but programs with no code are useless.  Of course the code might
4174      have ended up in the data segment... to detect that we would need
4175      the permissions here.  */
4176   else if (data && data->num_segments == 1)
4177     {
4178       segments[0] = data->segment_bases[0] + text_addr;
4179       num_segments = 1;
4180     }
4181   /* There's no way to relocate by segment.  */
4182   else
4183     do_segments = 0;
4184
4185   if (do_segments)
4186     {
4187       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4188                                                  offs, num_segments, segments);
4189
4190       if (ret == 0 && !do_sections)
4191         error (_("Can not handle qOffsets TextSeg "
4192                  "response with this symbol file"));
4193
4194       if (ret > 0)
4195         do_sections = 0;
4196     }
4197
4198   if (data)
4199     free_symfile_segment_data (data);
4200
4201   if (do_sections)
4202     {
4203       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4204
4205       /* This is a temporary kludge to force data and bss to use the
4206          same offsets because that's what nlmconv does now.  The real
4207          solution requires changes to the stub and remote.c that I
4208          don't have time to do right now.  */
4209
4210       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4211       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4212     }
4213
4214   objfile_relocate (symfile_objfile, offs);
4215 }
4216
4217 /* Send interrupt_sequence to remote target.  */
4218
4219 void
4220 remote_target::send_interrupt_sequence ()
4221 {
4222   struct remote_state *rs = get_remote_state ();
4223
4224   if (interrupt_sequence_mode == interrupt_sequence_control_c)
4225     remote_serial_write ("\x03", 1);
4226   else if (interrupt_sequence_mode == interrupt_sequence_break)
4227     serial_send_break (rs->remote_desc);
4228   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4229     {
4230       serial_send_break (rs->remote_desc);
4231       remote_serial_write ("g", 1);
4232     }
4233   else
4234     internal_error (__FILE__, __LINE__,
4235                     _("Invalid value for interrupt_sequence_mode: %s."),
4236                     interrupt_sequence_mode);
4237 }
4238
4239
4240 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4241    and extract the PTID.  Returns NULL_PTID if not found.  */
4242
4243 static ptid_t
4244 stop_reply_extract_thread (char *stop_reply)
4245 {
4246   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4247     {
4248       const char *p;
4249
4250       /* Txx r:val ; r:val (...)  */
4251       p = &stop_reply[3];
4252
4253       /* Look for "register" named "thread".  */
4254       while (*p != '\0')
4255         {
4256           const char *p1;
4257
4258           p1 = strchr (p, ':');
4259           if (p1 == NULL)
4260             return null_ptid;
4261
4262           if (strncmp (p, "thread", p1 - p) == 0)
4263             return read_ptid (++p1, &p);
4264
4265           p1 = strchr (p, ';');
4266           if (p1 == NULL)
4267             return null_ptid;
4268           p1++;
4269
4270           p = p1;
4271         }
4272     }
4273
4274   return null_ptid;
4275 }
4276
4277 /* Determine the remote side's current thread.  If we have a stop
4278    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4279    "thread" register we can extract the current thread from.  If not,
4280    ask the remote which is the current thread with qC.  The former
4281    method avoids a roundtrip.  */
4282
4283 ptid_t
4284 remote_target::get_current_thread (char *wait_status)
4285 {
4286   ptid_t ptid = null_ptid;
4287
4288   /* Note we don't use remote_parse_stop_reply as that makes use of
4289      the target architecture, which we haven't yet fully determined at
4290      this point.  */
4291   if (wait_status != NULL)
4292     ptid = stop_reply_extract_thread (wait_status);
4293   if (ptid == null_ptid)
4294     ptid = remote_current_thread (inferior_ptid);
4295
4296   return ptid;
4297 }
4298
4299 /* Query the remote target for which is the current thread/process,
4300    add it to our tables, and update INFERIOR_PTID.  The caller is
4301    responsible for setting the state such that the remote end is ready
4302    to return the current thread.
4303
4304    This function is called after handling the '?' or 'vRun' packets,
4305    whose response is a stop reply from which we can also try
4306    extracting the thread.  If the target doesn't support the explicit
4307    qC query, we infer the current thread from that stop reply, passed
4308    in in WAIT_STATUS, which may be NULL.  */
4309
4310 void
4311 remote_target::add_current_inferior_and_thread (char *wait_status)
4312 {
4313   struct remote_state *rs = get_remote_state ();
4314   bool fake_pid_p = false;
4315
4316   inferior_ptid = null_ptid;
4317
4318   /* Now, if we have thread information, update inferior_ptid.  */
4319   ptid_t curr_ptid = get_current_thread (wait_status);
4320
4321   if (curr_ptid != null_ptid)
4322     {
4323       if (!remote_multi_process_p (rs))
4324         fake_pid_p = true;
4325     }
4326   else
4327     {
4328       /* Without this, some commands which require an active target
4329          (such as kill) won't work.  This variable serves (at least)
4330          double duty as both the pid of the target process (if it has
4331          such), and as a flag indicating that a target is active.  */
4332       curr_ptid = magic_null_ptid;
4333       fake_pid_p = true;
4334     }
4335
4336   remote_add_inferior (fake_pid_p, curr_ptid.pid (), -1, 1);
4337
4338   /* Add the main thread and switch to it.  Don't try reading
4339      registers yet, since we haven't fetched the target description
4340      yet.  */
4341   thread_info *tp = add_thread_silent (curr_ptid);
4342   switch_to_thread_no_regs (tp);
4343 }
4344
4345 /* Print info about a thread that was found already stopped on
4346    connection.  */
4347
4348 static void
4349 print_one_stopped_thread (struct thread_info *thread)
4350 {
4351   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4352
4353   switch_to_thread (thread);
4354   thread->suspend.stop_pc = get_frame_pc (get_current_frame ());
4355   set_current_sal_from_frame (get_current_frame ());
4356
4357   thread->suspend.waitstatus_pending_p = 0;
4358
4359   if (ws->kind == TARGET_WAITKIND_STOPPED)
4360     {
4361       enum gdb_signal sig = ws->value.sig;
4362
4363       if (signal_print_state (sig))
4364         gdb::observers::signal_received.notify (sig);
4365     }
4366   gdb::observers::normal_stop.notify (NULL, 1);
4367 }
4368
4369 /* Process all initial stop replies the remote side sent in response
4370    to the ? packet.  These indicate threads that were already stopped
4371    on initial connection.  We mark these threads as stopped and print
4372    their current frame before giving the user the prompt.  */
4373
4374 void
4375 remote_target::process_initial_stop_replies (int from_tty)
4376 {
4377   int pending_stop_replies = stop_reply_queue_length ();
4378   struct thread_info *selected = NULL;
4379   struct thread_info *lowest_stopped = NULL;
4380   struct thread_info *first = NULL;
4381
4382   /* Consume the initial pending events.  */
4383   while (pending_stop_replies-- > 0)
4384     {
4385       ptid_t waiton_ptid = minus_one_ptid;
4386       ptid_t event_ptid;
4387       struct target_waitstatus ws;
4388       int ignore_event = 0;
4389
4390       memset (&ws, 0, sizeof (ws));
4391       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4392       if (remote_debug)
4393         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4394
4395       switch (ws.kind)
4396         {
4397         case TARGET_WAITKIND_IGNORE:
4398         case TARGET_WAITKIND_NO_RESUMED:
4399         case TARGET_WAITKIND_SIGNALLED:
4400         case TARGET_WAITKIND_EXITED:
4401           /* We shouldn't see these, but if we do, just ignore.  */
4402           if (remote_debug)
4403             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4404           ignore_event = 1;
4405           break;
4406
4407         case TARGET_WAITKIND_EXECD:
4408           xfree (ws.value.execd_pathname);
4409           break;
4410         default:
4411           break;
4412         }
4413
4414       if (ignore_event)
4415         continue;
4416
4417       struct thread_info *evthread = find_thread_ptid (event_ptid);
4418
4419       if (ws.kind == TARGET_WAITKIND_STOPPED)
4420         {
4421           enum gdb_signal sig = ws.value.sig;
4422
4423           /* Stubs traditionally report SIGTRAP as initial signal,
4424              instead of signal 0.  Suppress it.  */
4425           if (sig == GDB_SIGNAL_TRAP)
4426             sig = GDB_SIGNAL_0;
4427           evthread->suspend.stop_signal = sig;
4428           ws.value.sig = sig;
4429         }
4430
4431       evthread->suspend.waitstatus = ws;
4432
4433       if (ws.kind != TARGET_WAITKIND_STOPPED
4434           || ws.value.sig != GDB_SIGNAL_0)
4435         evthread->suspend.waitstatus_pending_p = 1;
4436
4437       set_executing (event_ptid, 0);
4438       set_running (event_ptid, 0);
4439       get_remote_thread_info (evthread)->vcont_resumed = 0;
4440     }
4441
4442   /* "Notice" the new inferiors before anything related to
4443      registers/memory.  */
4444   for (inferior *inf : all_non_exited_inferiors ())
4445     {
4446       inf->needs_setup = 1;
4447
4448       if (non_stop)
4449         {
4450           thread_info *thread = any_live_thread_of_inferior (inf);
4451           notice_new_inferior (thread, thread->state == THREAD_RUNNING,
4452                                from_tty);
4453         }
4454     }
4455
4456   /* If all-stop on top of non-stop, pause all threads.  Note this
4457      records the threads' stop pc, so must be done after "noticing"
4458      the inferiors.  */
4459   if (!non_stop)
4460     {
4461       stop_all_threads ();
4462
4463       /* If all threads of an inferior were already stopped, we
4464          haven't setup the inferior yet.  */
4465       for (inferior *inf : all_non_exited_inferiors ())
4466         {
4467           if (inf->needs_setup)
4468             {
4469               thread_info *thread = any_live_thread_of_inferior (inf);
4470               switch_to_thread_no_regs (thread);
4471               setup_inferior (0);
4472             }
4473         }
4474     }
4475
4476   /* Now go over all threads that are stopped, and print their current
4477      frame.  If all-stop, then if there's a signalled thread, pick
4478      that as current.  */
4479   for (thread_info *thread : all_non_exited_threads ())
4480     {
4481       if (first == NULL)
4482         first = thread;
4483
4484       if (!non_stop)
4485         thread->set_running (false);
4486       else if (thread->state != THREAD_STOPPED)
4487         continue;
4488
4489       if (selected == NULL
4490           && thread->suspend.waitstatus_pending_p)
4491         selected = thread;
4492
4493       if (lowest_stopped == NULL
4494           || thread->inf->num < lowest_stopped->inf->num
4495           || thread->per_inf_num < lowest_stopped->per_inf_num)
4496         lowest_stopped = thread;
4497
4498       if (non_stop)
4499         print_one_stopped_thread (thread);
4500     }
4501
4502   /* In all-stop, we only print the status of one thread, and leave
4503      others with their status pending.  */
4504   if (!non_stop)
4505     {
4506       thread_info *thread = selected;
4507       if (thread == NULL)
4508         thread = lowest_stopped;
4509       if (thread == NULL)
4510         thread = first;
4511
4512       print_one_stopped_thread (thread);
4513     }
4514
4515   /* For "info program".  */
4516   thread_info *thread = inferior_thread ();
4517   if (thread->state == THREAD_STOPPED)
4518     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4519 }
4520
4521 /* Start the remote connection and sync state.  */
4522
4523 void
4524 remote_target::start_remote (int from_tty, int extended_p)
4525 {
4526   struct remote_state *rs = get_remote_state ();
4527   struct packet_config *noack_config;
4528   char *wait_status = NULL;
4529
4530   /* Signal other parts that we're going through the initial setup,
4531      and so things may not be stable yet.  E.g., we don't try to
4532      install tracepoints until we've relocated symbols.  Also, a
4533      Ctrl-C before we're connected and synced up can't interrupt the
4534      target.  Instead, it offers to drop the (potentially wedged)
4535      connection.  */
4536   rs->starting_up = 1;
4537
4538   QUIT;
4539
4540   if (interrupt_on_connect)
4541     send_interrupt_sequence ();
4542
4543   /* Ack any packet which the remote side has already sent.  */
4544   remote_serial_write ("+", 1);
4545
4546   /* The first packet we send to the target is the optional "supported
4547      packets" request.  If the target can answer this, it will tell us
4548      which later probes to skip.  */
4549   remote_query_supported ();
4550
4551   /* If the stub wants to get a QAllow, compose one and send it.  */
4552   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4553     set_permissions ();
4554
4555   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4556      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4557      as a reply to known packet.  For packet "vFile:setfs:" it is an
4558      invalid reply and GDB would return error in
4559      remote_hostio_set_filesystem, making remote files access impossible.
4560      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4561      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4562   {
4563     const char v_mustreplyempty[] = "vMustReplyEmpty";
4564
4565     putpkt (v_mustreplyempty);
4566     getpkt (&rs->buf, 0);
4567     if (strcmp (rs->buf.data (), "OK") == 0)
4568       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4569     else if (strcmp (rs->buf.data (), "") != 0)
4570       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4571              rs->buf.data ());
4572   }
4573
4574   /* Next, we possibly activate noack mode.
4575
4576      If the QStartNoAckMode packet configuration is set to AUTO,
4577      enable noack mode if the stub reported a wish for it with
4578      qSupported.
4579
4580      If set to TRUE, then enable noack mode even if the stub didn't
4581      report it in qSupported.  If the stub doesn't reply OK, the
4582      session ends with an error.
4583
4584      If FALSE, then don't activate noack mode, regardless of what the
4585      stub claimed should be the default with qSupported.  */
4586
4587   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4588   if (packet_config_support (noack_config) != PACKET_DISABLE)
4589     {
4590       putpkt ("QStartNoAckMode");
4591       getpkt (&rs->buf, 0);
4592       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4593         rs->noack_mode = 1;
4594     }
4595
4596   if (extended_p)
4597     {
4598       /* Tell the remote that we are using the extended protocol.  */
4599       putpkt ("!");
4600       getpkt (&rs->buf, 0);
4601     }
4602
4603   /* Let the target know which signals it is allowed to pass down to
4604      the program.  */
4605   update_signals_program_target ();
4606
4607   /* Next, if the target can specify a description, read it.  We do
4608      this before anything involving memory or registers.  */
4609   target_find_description ();
4610
4611   /* Next, now that we know something about the target, update the
4612      address spaces in the program spaces.  */
4613   update_address_spaces ();
4614
4615   /* On OSs where the list of libraries is global to all
4616      processes, we fetch them early.  */
4617   if (gdbarch_has_global_solist (target_gdbarch ()))
4618     solib_add (NULL, from_tty, auto_solib_add);
4619
4620   if (target_is_non_stop_p ())
4621     {
4622       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4623         error (_("Non-stop mode requested, but remote "
4624                  "does not support non-stop"));
4625
4626       putpkt ("QNonStop:1");
4627       getpkt (&rs->buf, 0);
4628
4629       if (strcmp (rs->buf.data (), "OK") != 0)
4630         error (_("Remote refused setting non-stop mode with: %s"),
4631                rs->buf.data ());
4632
4633       /* Find about threads and processes the stub is already
4634          controlling.  We default to adding them in the running state.
4635          The '?' query below will then tell us about which threads are
4636          stopped.  */
4637       this->update_thread_list ();
4638     }
4639   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4640     {
4641       /* Don't assume that the stub can operate in all-stop mode.
4642          Request it explicitly.  */
4643       putpkt ("QNonStop:0");
4644       getpkt (&rs->buf, 0);
4645
4646       if (strcmp (rs->buf.data (), "OK") != 0)
4647         error (_("Remote refused setting all-stop mode with: %s"),
4648                rs->buf.data ());
4649     }
4650
4651   /* Upload TSVs regardless of whether the target is running or not.  The
4652      remote stub, such as GDBserver, may have some predefined or builtin
4653      TSVs, even if the target is not running.  */
4654   if (get_trace_status (current_trace_status ()) != -1)
4655     {
4656       struct uploaded_tsv *uploaded_tsvs = NULL;
4657
4658       upload_trace_state_variables (&uploaded_tsvs);
4659       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4660     }
4661
4662   /* Check whether the target is running now.  */
4663   putpkt ("?");
4664   getpkt (&rs->buf, 0);
4665
4666   if (!target_is_non_stop_p ())
4667     {
4668       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4669         {
4670           if (!extended_p)
4671             error (_("The target is not running (try extended-remote?)"));
4672
4673           /* We're connected, but not running.  Drop out before we
4674              call start_remote.  */
4675           rs->starting_up = 0;
4676           return;
4677         }
4678       else
4679         {
4680           /* Save the reply for later.  */
4681           wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
4682           strcpy (wait_status, rs->buf.data ());
4683         }
4684
4685       /* Fetch thread list.  */
4686       target_update_thread_list ();
4687
4688       /* Let the stub know that we want it to return the thread.  */
4689       set_continue_thread (minus_one_ptid);
4690
4691       if (thread_count () == 0)
4692         {
4693           /* Target has no concept of threads at all.  GDB treats
4694              non-threaded target as single-threaded; add a main
4695              thread.  */
4696           add_current_inferior_and_thread (wait_status);
4697         }
4698       else
4699         {
4700           /* We have thread information; select the thread the target
4701              says should be current.  If we're reconnecting to a
4702              multi-threaded program, this will ideally be the thread
4703              that last reported an event before GDB disconnected.  */
4704           inferior_ptid = get_current_thread (wait_status);
4705           if (inferior_ptid == null_ptid)
4706             {
4707               /* Odd... The target was able to list threads, but not
4708                  tell us which thread was current (no "thread"
4709                  register in T stop reply?).  Just pick the first
4710                  thread in the thread list then.  */
4711               
4712               if (remote_debug)
4713                 fprintf_unfiltered (gdb_stdlog,
4714                                     "warning: couldn't determine remote "
4715                                     "current thread; picking first in list.\n");
4716
4717               inferior_ptid = inferior_list->thread_list->ptid;
4718             }
4719         }
4720
4721       /* init_wait_for_inferior should be called before get_offsets in order
4722          to manage `inserted' flag in bp loc in a correct state.
4723          breakpoint_init_inferior, called from init_wait_for_inferior, set
4724          `inserted' flag to 0, while before breakpoint_re_set, called from
4725          start_remote, set `inserted' flag to 1.  In the initialization of
4726          inferior, breakpoint_init_inferior should be called first, and then
4727          breakpoint_re_set can be called.  If this order is broken, state of
4728          `inserted' flag is wrong, and cause some problems on breakpoint
4729          manipulation.  */
4730       init_wait_for_inferior ();
4731
4732       get_offsets ();           /* Get text, data & bss offsets.  */
4733
4734       /* If we could not find a description using qXfer, and we know
4735          how to do it some other way, try again.  This is not
4736          supported for non-stop; it could be, but it is tricky if
4737          there are no stopped threads when we connect.  */
4738       if (remote_read_description_p (this)
4739           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4740         {
4741           target_clear_description ();
4742           target_find_description ();
4743         }
4744
4745       /* Use the previously fetched status.  */
4746       gdb_assert (wait_status != NULL);
4747       strcpy (rs->buf.data (), wait_status);
4748       rs->cached_wait_status = 1;
4749
4750       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4751     }
4752   else
4753     {
4754       /* Clear WFI global state.  Do this before finding about new
4755          threads and inferiors, and setting the current inferior.
4756          Otherwise we would clear the proceed status of the current
4757          inferior when we want its stop_soon state to be preserved
4758          (see notice_new_inferior).  */
4759       init_wait_for_inferior ();
4760
4761       /* In non-stop, we will either get an "OK", meaning that there
4762          are no stopped threads at this time; or, a regular stop
4763          reply.  In the latter case, there may be more than one thread
4764          stopped --- we pull them all out using the vStopped
4765          mechanism.  */
4766       if (strcmp (rs->buf.data (), "OK") != 0)
4767         {
4768           struct notif_client *notif = &notif_client_stop;
4769
4770           /* remote_notif_get_pending_replies acks this one, and gets
4771              the rest out.  */
4772           rs->notif_state->pending_event[notif_client_stop.id]
4773             = remote_notif_parse (this, notif, rs->buf.data ());
4774           remote_notif_get_pending_events (notif);
4775         }
4776
4777       if (thread_count () == 0)
4778         {
4779           if (!extended_p)
4780             error (_("The target is not running (try extended-remote?)"));
4781
4782           /* We're connected, but not running.  Drop out before we
4783              call start_remote.  */
4784           rs->starting_up = 0;
4785           return;
4786         }
4787
4788       /* In non-stop mode, any cached wait status will be stored in
4789          the stop reply queue.  */
4790       gdb_assert (wait_status == NULL);
4791
4792       /* Report all signals during attach/startup.  */
4793       pass_signals ({});
4794
4795       /* If there are already stopped threads, mark them stopped and
4796          report their stops before giving the prompt to the user.  */
4797       process_initial_stop_replies (from_tty);
4798
4799       if (target_can_async_p ())
4800         target_async (1);
4801     }
4802
4803   /* If we connected to a live target, do some additional setup.  */
4804   if (target_has_execution)
4805     {
4806       if (symfile_objfile)      /* No use without a symbol-file.  */
4807         remote_check_symbols ();
4808     }
4809
4810   /* Possibly the target has been engaged in a trace run started
4811      previously; find out where things are at.  */
4812   if (get_trace_status (current_trace_status ()) != -1)
4813     {
4814       struct uploaded_tp *uploaded_tps = NULL;
4815
4816       if (current_trace_status ()->running)
4817         printf_filtered (_("Trace is already running on the target.\n"));
4818
4819       upload_tracepoints (&uploaded_tps);
4820
4821       merge_uploaded_tracepoints (&uploaded_tps);
4822     }
4823
4824   /* Possibly the target has been engaged in a btrace record started
4825      previously; find out where things are at.  */
4826   remote_btrace_maybe_reopen ();
4827
4828   /* The thread and inferior lists are now synchronized with the
4829      target, our symbols have been relocated, and we're merged the
4830      target's tracepoints with ours.  We're done with basic start
4831      up.  */
4832   rs->starting_up = 0;
4833
4834   /* Maybe breakpoints are global and need to be inserted now.  */
4835   if (breakpoints_should_be_inserted_now ())
4836     insert_breakpoints ();
4837 }
4838
4839 /* Open a connection to a remote debugger.
4840    NAME is the filename used for communication.  */
4841
4842 void
4843 remote_target::open (const char *name, int from_tty)
4844 {
4845   open_1 (name, from_tty, 0);
4846 }
4847
4848 /* Open a connection to a remote debugger using the extended
4849    remote gdb protocol.  NAME is the filename used for communication.  */
4850
4851 void
4852 extended_remote_target::open (const char *name, int from_tty)
4853 {
4854   open_1 (name, from_tty, 1 /*extended_p */);
4855 }
4856
4857 /* Reset all packets back to "unknown support".  Called when opening a
4858    new connection to a remote target.  */
4859
4860 static void
4861 reset_all_packet_configs_support (void)
4862 {
4863   int i;
4864
4865   for (i = 0; i < PACKET_MAX; i++)
4866     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4867 }
4868
4869 /* Initialize all packet configs.  */
4870
4871 static void
4872 init_all_packet_configs (void)
4873 {
4874   int i;
4875
4876   for (i = 0; i < PACKET_MAX; i++)
4877     {
4878       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4879       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4880     }
4881 }
4882
4883 /* Symbol look-up.  */
4884
4885 void
4886 remote_target::remote_check_symbols ()
4887 {
4888   char *tmp;
4889   int end;
4890
4891   /* The remote side has no concept of inferiors that aren't running
4892      yet, it only knows about running processes.  If we're connected
4893      but our current inferior is not running, we should not invite the
4894      remote target to request symbol lookups related to its
4895      (unrelated) current process.  */
4896   if (!target_has_execution)
4897     return;
4898
4899   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4900     return;
4901
4902   /* Make sure the remote is pointing at the right process.  Note
4903      there's no way to select "no process".  */
4904   set_general_process ();
4905
4906   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4907      because we need both at the same time.  */
4908   gdb::char_vector msg (get_remote_packet_size ());
4909   gdb::char_vector reply (get_remote_packet_size ());
4910
4911   /* Invite target to request symbol lookups.  */
4912
4913   putpkt ("qSymbol::");
4914   getpkt (&reply, 0);
4915   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4916
4917   while (startswith (reply.data (), "qSymbol:"))
4918     {
4919       struct bound_minimal_symbol sym;
4920
4921       tmp = &reply[8];
4922       end = hex2bin (tmp, reinterpret_cast <gdb_byte *> (msg.data ()),
4923                      strlen (tmp) / 2);
4924       msg[end] = '\0';
4925       sym = lookup_minimal_symbol (msg.data (), NULL, NULL);
4926       if (sym.minsym == NULL)
4927         xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol::%s",
4928                    &reply[8]);
4929       else
4930         {
4931           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4932           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4933
4934           /* If this is a function address, return the start of code
4935              instead of any data function descriptor.  */
4936           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4937                                                          sym_addr,
4938                                                          current_top_target ());
4939
4940           xsnprintf (msg.data (), get_remote_packet_size (), "qSymbol:%s:%s",
4941                      phex_nz (sym_addr, addr_size), &reply[8]);
4942         }
4943
4944       putpkt (msg.data ());
4945       getpkt (&reply, 0);
4946     }
4947 }
4948
4949 static struct serial *
4950 remote_serial_open (const char *name)
4951 {
4952   static int udp_warning = 0;
4953
4954   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4955      of in ser-tcp.c, because it is the remote protocol assuming that the
4956      serial connection is reliable and not the serial connection promising
4957      to be.  */
4958   if (!udp_warning && startswith (name, "udp:"))
4959     {
4960       warning (_("The remote protocol may be unreliable over UDP.\n"
4961                  "Some events may be lost, rendering further debugging "
4962                  "impossible."));
4963       udp_warning = 1;
4964     }
4965
4966   return serial_open (name);
4967 }
4968
4969 /* Inform the target of our permission settings.  The permission flags
4970    work without this, but if the target knows the settings, it can do
4971    a couple things.  First, it can add its own check, to catch cases
4972    that somehow manage to get by the permissions checks in target
4973    methods.  Second, if the target is wired to disallow particular
4974    settings (for instance, a system in the field that is not set up to
4975    be able to stop at a breakpoint), it can object to any unavailable
4976    permissions.  */
4977
4978 void
4979 remote_target::set_permissions ()
4980 {
4981   struct remote_state *rs = get_remote_state ();
4982
4983   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAllow:"
4984              "WriteReg:%x;WriteMem:%x;"
4985              "InsertBreak:%x;InsertTrace:%x;"
4986              "InsertFastTrace:%x;Stop:%x",
4987              may_write_registers, may_write_memory,
4988              may_insert_breakpoints, may_insert_tracepoints,
4989              may_insert_fast_tracepoints, may_stop);
4990   putpkt (rs->buf);
4991   getpkt (&rs->buf, 0);
4992
4993   /* If the target didn't like the packet, warn the user.  Do not try
4994      to undo the user's settings, that would just be maddening.  */
4995   if (strcmp (rs->buf.data (), "OK") != 0)
4996     warning (_("Remote refused setting permissions with: %s"),
4997              rs->buf.data ());
4998 }
4999
5000 /* This type describes each known response to the qSupported
5001    packet.  */
5002 struct protocol_feature
5003 {
5004   /* The name of this protocol feature.  */
5005   const char *name;
5006
5007   /* The default for this protocol feature.  */
5008   enum packet_support default_support;
5009
5010   /* The function to call when this feature is reported, or after
5011      qSupported processing if the feature is not supported.
5012      The first argument points to this structure.  The second
5013      argument indicates whether the packet requested support be
5014      enabled, disabled, or probed (or the default, if this function
5015      is being called at the end of processing and this feature was
5016      not reported).  The third argument may be NULL; if not NULL, it
5017      is a NUL-terminated string taken from the packet following
5018      this feature's name and an equals sign.  */
5019   void (*func) (remote_target *remote, const struct protocol_feature *,
5020                 enum packet_support, const char *);
5021
5022   /* The corresponding packet for this feature.  Only used if
5023      FUNC is remote_supported_packet.  */
5024   int packet;
5025 };
5026
5027 static void
5028 remote_supported_packet (remote_target *remote,
5029                          const struct protocol_feature *feature,
5030                          enum packet_support support,
5031                          const char *argument)
5032 {
5033   if (argument)
5034     {
5035       warning (_("Remote qSupported response supplied an unexpected value for"
5036                  " \"%s\"."), feature->name);
5037       return;
5038     }
5039
5040   remote_protocol_packets[feature->packet].support = support;
5041 }
5042
5043 void
5044 remote_target::remote_packet_size (const protocol_feature *feature,
5045                                    enum packet_support support, const char *value)
5046 {
5047   struct remote_state *rs = get_remote_state ();
5048
5049   int packet_size;
5050   char *value_end;
5051
5052   if (support != PACKET_ENABLE)
5053     return;
5054
5055   if (value == NULL || *value == '\0')
5056     {
5057       warning (_("Remote target reported \"%s\" without a size."),
5058                feature->name);
5059       return;
5060     }
5061
5062   errno = 0;
5063   packet_size = strtol (value, &value_end, 16);
5064   if (errno != 0 || *value_end != '\0' || packet_size < 0)
5065     {
5066       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5067                feature->name, value);
5068       return;
5069     }
5070
5071   /* Record the new maximum packet size.  */
5072   rs->explicit_packet_size = packet_size;
5073 }
5074
5075 void
5076 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5077                     enum packet_support support, const char *value)
5078 {
5079   remote->remote_packet_size (feature, support, value);
5080 }
5081
5082 static const struct protocol_feature remote_protocol_features[] = {
5083   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5084   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5085     PACKET_qXfer_auxv },
5086   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5087     PACKET_qXfer_exec_file },
5088   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5089     PACKET_qXfer_features },
5090   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5091     PACKET_qXfer_libraries },
5092   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5093     PACKET_qXfer_libraries_svr4 },
5094   { "augmented-libraries-svr4-read", PACKET_DISABLE,
5095     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5096   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5097     PACKET_qXfer_memory_map },
5098   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5099     PACKET_qXfer_spu_read },
5100   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5101     PACKET_qXfer_spu_write },
5102   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5103     PACKET_qXfer_osdata },
5104   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5105     PACKET_qXfer_threads },
5106   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5107     PACKET_qXfer_traceframe_info },
5108   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5109     PACKET_QPassSignals },
5110   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5111     PACKET_QCatchSyscalls },
5112   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5113     PACKET_QProgramSignals },
5114   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5115     PACKET_QSetWorkingDir },
5116   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5117     PACKET_QStartupWithShell },
5118   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5119     PACKET_QEnvironmentHexEncoded },
5120   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5121     PACKET_QEnvironmentReset },
5122   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5123     PACKET_QEnvironmentUnset },
5124   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5125     PACKET_QStartNoAckMode },
5126   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5127     PACKET_multiprocess_feature },
5128   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5129   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5130     PACKET_qXfer_siginfo_read },
5131   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5132     PACKET_qXfer_siginfo_write },
5133   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5134     PACKET_ConditionalTracepoints },
5135   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5136     PACKET_ConditionalBreakpoints },
5137   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5138     PACKET_BreakpointCommands },
5139   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5140     PACKET_FastTracepoints },
5141   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5142     PACKET_StaticTracepoints },
5143   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5144    PACKET_InstallInTrace},
5145   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5146     PACKET_DisconnectedTracing_feature },
5147   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5148     PACKET_bc },
5149   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5150     PACKET_bs },
5151   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5152     PACKET_TracepointSource },
5153   { "QAllow", PACKET_DISABLE, remote_supported_packet,
5154     PACKET_QAllow },
5155   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5156     PACKET_EnableDisableTracepoints_feature },
5157   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5158     PACKET_qXfer_fdpic },
5159   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5160     PACKET_qXfer_uib },
5161   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5162     PACKET_QDisableRandomization },
5163   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5164   { "QTBuffer:size", PACKET_DISABLE,
5165     remote_supported_packet, PACKET_QTBuffer_size},
5166   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5167   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5168   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5169   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5170   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5171     PACKET_qXfer_btrace },
5172   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5173     PACKET_qXfer_btrace_conf },
5174   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5175     PACKET_Qbtrace_conf_bts_size },
5176   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5177   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5178   { "fork-events", PACKET_DISABLE, remote_supported_packet,
5179     PACKET_fork_event_feature },
5180   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5181     PACKET_vfork_event_feature },
5182   { "exec-events", PACKET_DISABLE, remote_supported_packet,
5183     PACKET_exec_event_feature },
5184   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5185     PACKET_Qbtrace_conf_pt_size },
5186   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5187   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5188   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5189 };
5190
5191 static char *remote_support_xml;
5192
5193 /* Register string appended to "xmlRegisters=" in qSupported query.  */
5194
5195 void
5196 register_remote_support_xml (const char *xml)
5197 {
5198 #if defined(HAVE_LIBEXPAT)
5199   if (remote_support_xml == NULL)
5200     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5201   else
5202     {
5203       char *copy = xstrdup (remote_support_xml + 13);
5204       char *p = strtok (copy, ",");
5205
5206       do
5207         {
5208           if (strcmp (p, xml) == 0)
5209             {
5210               /* already there */
5211               xfree (copy);
5212               return;
5213             }
5214         }
5215       while ((p = strtok (NULL, ",")) != NULL);
5216       xfree (copy);
5217
5218       remote_support_xml = reconcat (remote_support_xml,
5219                                      remote_support_xml, ",", xml,
5220                                      (char *) NULL);
5221     }
5222 #endif
5223 }
5224
5225 static void
5226 remote_query_supported_append (std::string *msg, const char *append)
5227 {
5228   if (!msg->empty ())
5229     msg->append (";");
5230   msg->append (append);
5231 }
5232
5233 void
5234 remote_target::remote_query_supported ()
5235 {
5236   struct remote_state *rs = get_remote_state ();
5237   char *next;
5238   int i;
5239   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5240
5241   /* The packet support flags are handled differently for this packet
5242      than for most others.  We treat an error, a disabled packet, and
5243      an empty response identically: any features which must be reported
5244      to be used will be automatically disabled.  An empty buffer
5245      accomplishes this, since that is also the representation for a list
5246      containing no features.  */
5247
5248   rs->buf[0] = 0;
5249   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5250     {
5251       std::string q;
5252
5253       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5254         remote_query_supported_append (&q, "multiprocess+");
5255
5256       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5257         remote_query_supported_append (&q, "swbreak+");
5258       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5259         remote_query_supported_append (&q, "hwbreak+");
5260
5261       remote_query_supported_append (&q, "qRelocInsn+");
5262
5263       if (packet_set_cmd_state (PACKET_fork_event_feature)
5264           != AUTO_BOOLEAN_FALSE)
5265         remote_query_supported_append (&q, "fork-events+");
5266       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5267           != AUTO_BOOLEAN_FALSE)
5268         remote_query_supported_append (&q, "vfork-events+");
5269       if (packet_set_cmd_state (PACKET_exec_event_feature)
5270           != AUTO_BOOLEAN_FALSE)
5271         remote_query_supported_append (&q, "exec-events+");
5272
5273       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5274         remote_query_supported_append (&q, "vContSupported+");
5275
5276       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5277         remote_query_supported_append (&q, "QThreadEvents+");
5278
5279       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5280         remote_query_supported_append (&q, "no-resumed+");
5281
5282       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5283          the qSupported:xmlRegisters=i386 handling.  */
5284       if (remote_support_xml != NULL
5285           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5286         remote_query_supported_append (&q, remote_support_xml);
5287
5288       q = "qSupported:" + q;
5289       putpkt (q.c_str ());
5290
5291       getpkt (&rs->buf, 0);
5292
5293       /* If an error occured, warn, but do not return - just reset the
5294          buffer to empty and go on to disable features.  */
5295       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5296           == PACKET_ERROR)
5297         {
5298           warning (_("Remote failure reply: %s"), rs->buf.data ());
5299           rs->buf[0] = 0;
5300         }
5301     }
5302
5303   memset (seen, 0, sizeof (seen));
5304
5305   next = rs->buf.data ();
5306   while (*next)
5307     {
5308       enum packet_support is_supported;
5309       char *p, *end, *name_end, *value;
5310
5311       /* First separate out this item from the rest of the packet.  If
5312          there's another item after this, we overwrite the separator
5313          (terminated strings are much easier to work with).  */
5314       p = next;
5315       end = strchr (p, ';');
5316       if (end == NULL)
5317         {
5318           end = p + strlen (p);
5319           next = end;
5320         }
5321       else
5322         {
5323           *end = '\0';
5324           next = end + 1;
5325
5326           if (end == p)
5327             {
5328               warning (_("empty item in \"qSupported\" response"));
5329               continue;
5330             }
5331         }
5332
5333       name_end = strchr (p, '=');
5334       if (name_end)
5335         {
5336           /* This is a name=value entry.  */
5337           is_supported = PACKET_ENABLE;
5338           value = name_end + 1;
5339           *name_end = '\0';
5340         }
5341       else
5342         {
5343           value = NULL;
5344           switch (end[-1])
5345             {
5346             case '+':
5347               is_supported = PACKET_ENABLE;
5348               break;
5349
5350             case '-':
5351               is_supported = PACKET_DISABLE;
5352               break;
5353
5354             case '?':
5355               is_supported = PACKET_SUPPORT_UNKNOWN;
5356               break;
5357
5358             default:
5359               warning (_("unrecognized item \"%s\" "
5360                          "in \"qSupported\" response"), p);
5361               continue;
5362             }
5363           end[-1] = '\0';
5364         }
5365
5366       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5367         if (strcmp (remote_protocol_features[i].name, p) == 0)
5368           {
5369             const struct protocol_feature *feature;
5370
5371             seen[i] = 1;
5372             feature = &remote_protocol_features[i];
5373             feature->func (this, feature, is_supported, value);
5374             break;
5375           }
5376     }
5377
5378   /* If we increased the packet size, make sure to increase the global
5379      buffer size also.  We delay this until after parsing the entire
5380      qSupported packet, because this is the same buffer we were
5381      parsing.  */
5382   if (rs->buf.size () < rs->explicit_packet_size)
5383     rs->buf.resize (rs->explicit_packet_size);
5384
5385   /* Handle the defaults for unmentioned features.  */
5386   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5387     if (!seen[i])
5388       {
5389         const struct protocol_feature *feature;
5390
5391         feature = &remote_protocol_features[i];
5392         feature->func (this, feature, feature->default_support, NULL);
5393       }
5394 }
5395
5396 /* Serial QUIT handler for the remote serial descriptor.
5397
5398    Defers handling a Ctrl-C until we're done with the current
5399    command/response packet sequence, unless:
5400
5401    - We're setting up the connection.  Don't send a remote interrupt
5402      request, as we're not fully synced yet.  Quit immediately
5403      instead.
5404
5405    - The target has been resumed in the foreground
5406      (target_terminal::is_ours is false) with a synchronous resume
5407      packet, and we're blocked waiting for the stop reply, thus a
5408      Ctrl-C should be immediately sent to the target.
5409
5410    - We get a second Ctrl-C while still within the same serial read or
5411      write.  In that case the serial is seemingly wedged --- offer to
5412      quit/disconnect.
5413
5414    - We see a second Ctrl-C without target response, after having
5415      previously interrupted the target.  In that case the target/stub
5416      is probably wedged --- offer to quit/disconnect.
5417 */
5418
5419 void
5420 remote_target::remote_serial_quit_handler ()
5421 {
5422   struct remote_state *rs = get_remote_state ();
5423
5424   if (check_quit_flag ())
5425     {
5426       /* If we're starting up, we're not fully synced yet.  Quit
5427          immediately.  */
5428       if (rs->starting_up)
5429         quit ();
5430       else if (rs->got_ctrlc_during_io)
5431         {
5432           if (query (_("The target is not responding to GDB commands.\n"
5433                        "Stop debugging it? ")))
5434             remote_unpush_and_throw ();
5435         }
5436       /* If ^C has already been sent once, offer to disconnect.  */
5437       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5438         interrupt_query ();
5439       /* All-stop protocol, and blocked waiting for stop reply.  Send
5440          an interrupt request.  */
5441       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5442         target_interrupt ();
5443       else
5444         rs->got_ctrlc_during_io = 1;
5445     }
5446 }
5447
5448 /* The remote_target that is current while the quit handler is
5449    overridden with remote_serial_quit_handler.  */
5450 static remote_target *curr_quit_handler_target;
5451
5452 static void
5453 remote_serial_quit_handler ()
5454 {
5455   curr_quit_handler_target->remote_serial_quit_handler ();
5456 }
5457
5458 /* Remove any of the remote.c targets from target stack.  Upper targets depend
5459    on it so remove them first.  */
5460
5461 static void
5462 remote_unpush_target (void)
5463 {
5464   pop_all_targets_at_and_above (process_stratum);
5465 }
5466
5467 static void
5468 remote_unpush_and_throw (void)
5469 {
5470   remote_unpush_target ();
5471   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5472 }
5473
5474 void
5475 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5476 {
5477   remote_target *curr_remote = get_current_remote_target ();
5478
5479   if (name == 0)
5480     error (_("To open a remote debug connection, you need to specify what\n"
5481            "serial device is attached to the remote system\n"
5482            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5483
5484   /* If we're connected to a running target, target_preopen will kill it.
5485      Ask this question first, before target_preopen has a chance to kill
5486      anything.  */
5487   if (curr_remote != NULL && !have_inferiors ())
5488     {
5489       if (from_tty
5490           && !query (_("Already connected to a remote target.  Disconnect? ")))
5491         error (_("Still connected."));
5492     }
5493
5494   /* Here the possibly existing remote target gets unpushed.  */
5495   target_preopen (from_tty);
5496
5497   remote_fileio_reset ();
5498   reopen_exec_file ();
5499   reread_symbols ();
5500
5501   remote_target *remote
5502     = (extended_p ? new extended_remote_target () : new remote_target ());
5503   target_ops_up target_holder (remote);
5504
5505   remote_state *rs = remote->get_remote_state ();
5506
5507   /* See FIXME above.  */
5508   if (!target_async_permitted)
5509     rs->wait_forever_enabled_p = 1;
5510
5511   rs->remote_desc = remote_serial_open (name);
5512   if (!rs->remote_desc)
5513     perror_with_name (name);
5514
5515   if (baud_rate != -1)
5516     {
5517       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5518         {
5519           /* The requested speed could not be set.  Error out to
5520              top level after closing remote_desc.  Take care to
5521              set remote_desc to NULL to avoid closing remote_desc
5522              more than once.  */
5523           serial_close (rs->remote_desc);
5524           rs->remote_desc = NULL;
5525           perror_with_name (name);
5526         }
5527     }
5528
5529   serial_setparity (rs->remote_desc, serial_parity);
5530   serial_raw (rs->remote_desc);
5531
5532   /* If there is something sitting in the buffer we might take it as a
5533      response to a command, which would be bad.  */
5534   serial_flush_input (rs->remote_desc);
5535
5536   if (from_tty)
5537     {
5538       puts_filtered ("Remote debugging using ");
5539       puts_filtered (name);
5540       puts_filtered ("\n");
5541     }
5542
5543   /* Switch to using the remote target now.  */
5544   push_target (std::move (target_holder));
5545
5546   /* Register extra event sources in the event loop.  */
5547   rs->remote_async_inferior_event_token
5548     = create_async_event_handler (remote_async_inferior_event_handler,
5549                                   remote);
5550   rs->notif_state = remote_notif_state_allocate (remote);
5551
5552   /* Reset the target state; these things will be queried either by
5553      remote_query_supported or as they are needed.  */
5554   reset_all_packet_configs_support ();
5555   rs->cached_wait_status = 0;
5556   rs->explicit_packet_size = 0;
5557   rs->noack_mode = 0;
5558   rs->extended = extended_p;
5559   rs->waiting_for_stop_reply = 0;
5560   rs->ctrlc_pending_p = 0;
5561   rs->got_ctrlc_during_io = 0;
5562
5563   rs->general_thread = not_sent_ptid;
5564   rs->continue_thread = not_sent_ptid;
5565   rs->remote_traceframe_number = -1;
5566
5567   rs->last_resume_exec_dir = EXEC_FORWARD;
5568
5569   /* Probe for ability to use "ThreadInfo" query, as required.  */
5570   rs->use_threadinfo_query = 1;
5571   rs->use_threadextra_query = 1;
5572
5573   rs->readahead_cache.invalidate ();
5574
5575   if (target_async_permitted)
5576     {
5577       /* FIXME: cagney/1999-09-23: During the initial connection it is
5578          assumed that the target is already ready and able to respond to
5579          requests.  Unfortunately remote_start_remote() eventually calls
5580          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5581          around this.  Eventually a mechanism that allows
5582          wait_for_inferior() to expect/get timeouts will be
5583          implemented.  */
5584       rs->wait_forever_enabled_p = 0;
5585     }
5586
5587   /* First delete any symbols previously loaded from shared libraries.  */
5588   no_shared_libraries (NULL, 0);
5589
5590   /* Start the remote connection.  If error() or QUIT, discard this
5591      target (we'd otherwise be in an inconsistent state) and then
5592      propogate the error on up the exception chain.  This ensures that
5593      the caller doesn't stumble along blindly assuming that the
5594      function succeeded.  The CLI doesn't have this problem but other
5595      UI's, such as MI do.
5596
5597      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5598      this function should return an error indication letting the
5599      caller restore the previous state.  Unfortunately the command
5600      ``target remote'' is directly wired to this function making that
5601      impossible.  On a positive note, the CLI side of this problem has
5602      been fixed - the function set_cmd_context() makes it possible for
5603      all the ``target ....'' commands to share a common callback
5604      function.  See cli-dump.c.  */
5605   {
5606
5607     try
5608       {
5609         remote->start_remote (from_tty, extended_p);
5610       }
5611     catch (const gdb_exception &ex)
5612       {
5613         /* Pop the partially set up target - unless something else did
5614            already before throwing the exception.  */
5615         if (ex.error != TARGET_CLOSE_ERROR)
5616           remote_unpush_target ();
5617         throw;
5618       }
5619   }
5620
5621   remote_btrace_reset (rs);
5622
5623   if (target_async_permitted)
5624     rs->wait_forever_enabled_p = 1;
5625 }
5626
5627 /* Detach the specified process.  */
5628
5629 void
5630 remote_target::remote_detach_pid (int pid)
5631 {
5632   struct remote_state *rs = get_remote_state ();
5633
5634   /* This should not be necessary, but the handling for D;PID in
5635      GDBserver versions prior to 8.2 incorrectly assumes that the
5636      selected process points to the same process we're detaching,
5637      leading to misbehavior (and possibly GDBserver crashing) when it
5638      does not.  Since it's easy and cheap, work around it by forcing
5639      GDBserver to select GDB's current process.  */
5640   set_general_process ();
5641
5642   if (remote_multi_process_p (rs))
5643     xsnprintf (rs->buf.data (), get_remote_packet_size (), "D;%x", pid);
5644   else
5645     strcpy (rs->buf.data (), "D");
5646
5647   putpkt (rs->buf);
5648   getpkt (&rs->buf, 0);
5649
5650   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5651     ;
5652   else if (rs->buf[0] == '\0')
5653     error (_("Remote doesn't know how to detach"));
5654   else
5655     error (_("Can't detach process."));
5656 }
5657
5658 /* This detaches a program to which we previously attached, using
5659    inferior_ptid to identify the process.  After this is done, GDB
5660    can be used to debug some other program.  We better not have left
5661    any breakpoints in the target program or it'll die when it hits
5662    one.  */
5663
5664 void
5665 remote_target::remote_detach_1 (inferior *inf, int from_tty)
5666 {
5667   int pid = inferior_ptid.pid ();
5668   struct remote_state *rs = get_remote_state ();
5669   int is_fork_parent;
5670
5671   if (!target_has_execution)
5672     error (_("No process to detach from."));
5673
5674   target_announce_detach (from_tty);
5675
5676   /* Tell the remote target to detach.  */
5677   remote_detach_pid (pid);
5678
5679   /* Exit only if this is the only active inferior.  */
5680   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5681     puts_filtered (_("Ending remote debugging.\n"));
5682
5683   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5684
5685   /* Check to see if we are detaching a fork parent.  Note that if we
5686      are detaching a fork child, tp == NULL.  */
5687   is_fork_parent = (tp != NULL
5688                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5689
5690   /* If doing detach-on-fork, we don't mourn, because that will delete
5691      breakpoints that should be available for the followed inferior.  */
5692   if (!is_fork_parent)
5693     {
5694       /* Save the pid as a string before mourning, since that will
5695          unpush the remote target, and we need the string after.  */
5696       std::string infpid = target_pid_to_str (ptid_t (pid));
5697
5698       target_mourn_inferior (inferior_ptid);
5699       if (print_inferior_events)
5700         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5701                            inf->num, infpid.c_str ());
5702     }
5703   else
5704     {
5705       inferior_ptid = null_ptid;
5706       detach_inferior (current_inferior ());
5707     }
5708 }
5709
5710 void
5711 remote_target::detach (inferior *inf, int from_tty)
5712 {
5713   remote_detach_1 (inf, from_tty);
5714 }
5715
5716 void
5717 extended_remote_target::detach (inferior *inf, int from_tty)
5718 {
5719   remote_detach_1 (inf, from_tty);
5720 }
5721
5722 /* Target follow-fork function for remote targets.  On entry, and
5723    at return, the current inferior is the fork parent.
5724
5725    Note that although this is currently only used for extended-remote,
5726    it is named remote_follow_fork in anticipation of using it for the
5727    remote target as well.  */
5728
5729 int
5730 remote_target::follow_fork (int follow_child, int detach_fork)
5731 {
5732   struct remote_state *rs = get_remote_state ();
5733   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5734
5735   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5736       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5737     {
5738       /* When following the parent and detaching the child, we detach
5739          the child here.  For the case of following the child and
5740          detaching the parent, the detach is done in the target-
5741          independent follow fork code in infrun.c.  We can't use
5742          target_detach when detaching an unfollowed child because
5743          the client side doesn't know anything about the child.  */
5744       if (detach_fork && !follow_child)
5745         {
5746           /* Detach the fork child.  */
5747           ptid_t child_ptid;
5748           pid_t child_pid;
5749
5750           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5751           child_pid = child_ptid.pid ();
5752
5753           remote_detach_pid (child_pid);
5754         }
5755     }
5756   return 0;
5757 }
5758
5759 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5760    in the program space of the new inferior.  On entry and at return the
5761    current inferior is the exec'ing inferior.  INF is the new exec'd
5762    inferior, which may be the same as the exec'ing inferior unless
5763    follow-exec-mode is "new".  */
5764
5765 void
5766 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5767 {
5768   /* We know that this is a target file name, so if it has the "target:"
5769      prefix we strip it off before saving it in the program space.  */
5770   if (is_target_filename (execd_pathname))
5771     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5772
5773   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5774 }
5775
5776 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5777
5778 void
5779 remote_target::disconnect (const char *args, int from_tty)
5780 {
5781   if (args)
5782     error (_("Argument given to \"disconnect\" when remotely debugging."));
5783
5784   /* Make sure we unpush even the extended remote targets.  Calling
5785      target_mourn_inferior won't unpush, and remote_mourn won't
5786      unpush if there is more than one inferior left.  */
5787   unpush_target (this);
5788   generic_mourn_inferior ();
5789
5790   if (from_tty)
5791     puts_filtered ("Ending remote debugging.\n");
5792 }
5793
5794 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5795    be chatty about it.  */
5796
5797 void
5798 extended_remote_target::attach (const char *args, int from_tty)
5799 {
5800   struct remote_state *rs = get_remote_state ();
5801   int pid;
5802   char *wait_status = NULL;
5803
5804   pid = parse_pid_to_attach (args);
5805
5806   /* Remote PID can be freely equal to getpid, do not check it here the same
5807      way as in other targets.  */
5808
5809   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5810     error (_("This target does not support attaching to a process"));
5811
5812   if (from_tty)
5813     {
5814       char *exec_file = get_exec_file (0);
5815
5816       if (exec_file)
5817         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5818                            target_pid_to_str (ptid_t (pid)).c_str ());
5819       else
5820         printf_unfiltered (_("Attaching to %s\n"),
5821                            target_pid_to_str (ptid_t (pid)).c_str ());
5822     }
5823
5824   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vAttach;%x", pid);
5825   putpkt (rs->buf);
5826   getpkt (&rs->buf, 0);
5827
5828   switch (packet_ok (rs->buf,
5829                      &remote_protocol_packets[PACKET_vAttach]))
5830     {
5831     case PACKET_OK:
5832       if (!target_is_non_stop_p ())
5833         {
5834           /* Save the reply for later.  */
5835           wait_status = (char *) alloca (strlen (rs->buf.data ()) + 1);
5836           strcpy (wait_status, rs->buf.data ());
5837         }
5838       else if (strcmp (rs->buf.data (), "OK") != 0)
5839         error (_("Attaching to %s failed with: %s"),
5840                target_pid_to_str (ptid_t (pid)).c_str (),
5841                rs->buf.data ());
5842       break;
5843     case PACKET_UNKNOWN:
5844       error (_("This target does not support attaching to a process"));
5845     default:
5846       error (_("Attaching to %s failed"),
5847              target_pid_to_str (ptid_t (pid)).c_str ());
5848     }
5849
5850   set_current_inferior (remote_add_inferior (false, pid, 1, 0));
5851
5852   inferior_ptid = ptid_t (pid);
5853
5854   if (target_is_non_stop_p ())
5855     {
5856       struct thread_info *thread;
5857
5858       /* Get list of threads.  */
5859       update_thread_list ();
5860
5861       thread = first_thread_of_inferior (current_inferior ());
5862       if (thread)
5863         inferior_ptid = thread->ptid;
5864       else
5865         inferior_ptid = ptid_t (pid);
5866
5867       /* Invalidate our notion of the remote current thread.  */
5868       record_currthread (rs, minus_one_ptid);
5869     }
5870   else
5871     {
5872       /* Now, if we have thread information, update inferior_ptid.  */
5873       inferior_ptid = remote_current_thread (inferior_ptid);
5874
5875       /* Add the main thread to the thread list.  */
5876       thread_info *thr = add_thread_silent (inferior_ptid);
5877       /* Don't consider the thread stopped until we've processed the
5878          saved stop reply.  */
5879       set_executing (thr->ptid, true);
5880     }
5881
5882   /* Next, if the target can specify a description, read it.  We do
5883      this before anything involving memory or registers.  */
5884   target_find_description ();
5885
5886   if (!target_is_non_stop_p ())
5887     {
5888       /* Use the previously fetched status.  */
5889       gdb_assert (wait_status != NULL);
5890
5891       if (target_can_async_p ())
5892         {
5893           struct notif_event *reply
5894             =  remote_notif_parse (this, &notif_client_stop, wait_status);
5895
5896           push_stop_reply ((struct stop_reply *) reply);
5897
5898           target_async (1);
5899         }
5900       else
5901         {
5902           gdb_assert (wait_status != NULL);
5903           strcpy (rs->buf.data (), wait_status);
5904           rs->cached_wait_status = 1;
5905         }
5906     }
5907   else
5908     gdb_assert (wait_status == NULL);
5909 }
5910
5911 /* Implementation of the to_post_attach method.  */
5912
5913 void
5914 extended_remote_target::post_attach (int pid)
5915 {
5916   /* Get text, data & bss offsets.  */
5917   get_offsets ();
5918
5919   /* In certain cases GDB might not have had the chance to start
5920      symbol lookup up until now.  This could happen if the debugged
5921      binary is not using shared libraries, the vsyscall page is not
5922      present (on Linux) and the binary itself hadn't changed since the
5923      debugging process was started.  */
5924   if (symfile_objfile != NULL)
5925     remote_check_symbols();
5926 }
5927
5928 \f
5929 /* Check for the availability of vCont.  This function should also check
5930    the response.  */
5931
5932 void
5933 remote_target::remote_vcont_probe ()
5934 {
5935   remote_state *rs = get_remote_state ();
5936   char *buf;
5937
5938   strcpy (rs->buf.data (), "vCont?");
5939   putpkt (rs->buf);
5940   getpkt (&rs->buf, 0);
5941   buf = rs->buf.data ();
5942
5943   /* Make sure that the features we assume are supported.  */
5944   if (startswith (buf, "vCont"))
5945     {
5946       char *p = &buf[5];
5947       int support_c, support_C;
5948
5949       rs->supports_vCont.s = 0;
5950       rs->supports_vCont.S = 0;
5951       support_c = 0;
5952       support_C = 0;
5953       rs->supports_vCont.t = 0;
5954       rs->supports_vCont.r = 0;
5955       while (p && *p == ';')
5956         {
5957           p++;
5958           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5959             rs->supports_vCont.s = 1;
5960           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5961             rs->supports_vCont.S = 1;
5962           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5963             support_c = 1;
5964           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5965             support_C = 1;
5966           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5967             rs->supports_vCont.t = 1;
5968           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5969             rs->supports_vCont.r = 1;
5970
5971           p = strchr (p, ';');
5972         }
5973
5974       /* If c, and C are not all supported, we can't use vCont.  Clearing
5975          BUF will make packet_ok disable the packet.  */
5976       if (!support_c || !support_C)
5977         buf[0] = 0;
5978     }
5979
5980   packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCont]);
5981 }
5982
5983 /* Helper function for building "vCont" resumptions.  Write a
5984    resumption to P.  ENDP points to one-passed-the-end of the buffer
5985    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5986    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5987    resumed thread should be single-stepped and/or signalled.  If PTID
5988    equals minus_one_ptid, then all threads are resumed; if PTID
5989    represents a process, then all threads of the process are resumed;
5990    the thread to be stepped and/or signalled is given in the global
5991    INFERIOR_PTID.  */
5992
5993 char *
5994 remote_target::append_resumption (char *p, char *endp,
5995                                   ptid_t ptid, int step, gdb_signal siggnal)
5996 {
5997   struct remote_state *rs = get_remote_state ();
5998
5999   if (step && siggnal != GDB_SIGNAL_0)
6000     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
6001   else if (step
6002            /* GDB is willing to range step.  */
6003            && use_range_stepping
6004            /* Target supports range stepping.  */
6005            && rs->supports_vCont.r
6006            /* We don't currently support range stepping multiple
6007               threads with a wildcard (though the protocol allows it,
6008               so stubs shouldn't make an active effort to forbid
6009               it).  */
6010            && !(remote_multi_process_p (rs) && ptid.is_pid ()))
6011     {
6012       struct thread_info *tp;
6013
6014       if (ptid == minus_one_ptid)
6015         {
6016           /* If we don't know about the target thread's tid, then
6017              we're resuming magic_null_ptid (see caller).  */
6018           tp = find_thread_ptid (magic_null_ptid);
6019         }
6020       else
6021         tp = find_thread_ptid (ptid);
6022       gdb_assert (tp != NULL);
6023
6024       if (tp->control.may_range_step)
6025         {
6026           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6027
6028           p += xsnprintf (p, endp - p, ";r%s,%s",
6029                           phex_nz (tp->control.step_range_start,
6030                                    addr_size),
6031                           phex_nz (tp->control.step_range_end,
6032                                    addr_size));
6033         }
6034       else
6035         p += xsnprintf (p, endp - p, ";s");
6036     }
6037   else if (step)
6038     p += xsnprintf (p, endp - p, ";s");
6039   else if (siggnal != GDB_SIGNAL_0)
6040     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6041   else
6042     p += xsnprintf (p, endp - p, ";c");
6043
6044   if (remote_multi_process_p (rs) && ptid.is_pid ())
6045     {
6046       ptid_t nptid;
6047
6048       /* All (-1) threads of process.  */
6049       nptid = ptid_t (ptid.pid (), -1, 0);
6050
6051       p += xsnprintf (p, endp - p, ":");
6052       p = write_ptid (p, endp, nptid);
6053     }
6054   else if (ptid != minus_one_ptid)
6055     {
6056       p += xsnprintf (p, endp - p, ":");
6057       p = write_ptid (p, endp, ptid);
6058     }
6059
6060   return p;
6061 }
6062
6063 /* Clear the thread's private info on resume.  */
6064
6065 static void
6066 resume_clear_thread_private_info (struct thread_info *thread)
6067 {
6068   if (thread->priv != NULL)
6069     {
6070       remote_thread_info *priv = get_remote_thread_info (thread);
6071
6072       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6073       priv->watch_data_address = 0;
6074     }
6075 }
6076
6077 /* Append a vCont continue-with-signal action for threads that have a
6078    non-zero stop signal.  */
6079
6080 char *
6081 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6082                                                   ptid_t ptid)
6083 {
6084   for (thread_info *thread : all_non_exited_threads (ptid))
6085     if (inferior_ptid != thread->ptid
6086         && thread->suspend.stop_signal != GDB_SIGNAL_0)
6087       {
6088         p = append_resumption (p, endp, thread->ptid,
6089                                0, thread->suspend.stop_signal);
6090         thread->suspend.stop_signal = GDB_SIGNAL_0;
6091         resume_clear_thread_private_info (thread);
6092       }
6093
6094   return p;
6095 }
6096
6097 /* Set the target running, using the packets that use Hc
6098    (c/s/C/S).  */
6099
6100 void
6101 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6102                                       gdb_signal siggnal)
6103 {
6104   struct remote_state *rs = get_remote_state ();
6105   char *buf;
6106
6107   rs->last_sent_signal = siggnal;
6108   rs->last_sent_step = step;
6109
6110   /* The c/s/C/S resume packets use Hc, so set the continue
6111      thread.  */
6112   if (ptid == minus_one_ptid)
6113     set_continue_thread (any_thread_ptid);
6114   else
6115     set_continue_thread (ptid);
6116
6117   for (thread_info *thread : all_non_exited_threads ())
6118     resume_clear_thread_private_info (thread);
6119
6120   buf = rs->buf.data ();
6121   if (::execution_direction == EXEC_REVERSE)
6122     {
6123       /* We don't pass signals to the target in reverse exec mode.  */
6124       if (info_verbose && siggnal != GDB_SIGNAL_0)
6125         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6126                  siggnal);
6127
6128       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6129         error (_("Remote reverse-step not supported."));
6130       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6131         error (_("Remote reverse-continue not supported."));
6132
6133       strcpy (buf, step ? "bs" : "bc");
6134     }
6135   else if (siggnal != GDB_SIGNAL_0)
6136     {
6137       buf[0] = step ? 'S' : 'C';
6138       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6139       buf[2] = tohex (((int) siggnal) & 0xf);
6140       buf[3] = '\0';
6141     }
6142   else
6143     strcpy (buf, step ? "s" : "c");
6144
6145   putpkt (buf);
6146 }
6147
6148 /* Resume the remote inferior by using a "vCont" packet.  The thread
6149    to be resumed is PTID; STEP and SIGGNAL indicate whether the
6150    resumed thread should be single-stepped and/or signalled.  If PTID
6151    equals minus_one_ptid, then all threads are resumed; the thread to
6152    be stepped and/or signalled is given in the global INFERIOR_PTID.
6153    This function returns non-zero iff it resumes the inferior.
6154
6155    This function issues a strict subset of all possible vCont commands
6156    at the moment.  */
6157
6158 int
6159 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6160                                          enum gdb_signal siggnal)
6161 {
6162   struct remote_state *rs = get_remote_state ();
6163   char *p;
6164   char *endp;
6165
6166   /* No reverse execution actions defined for vCont.  */
6167   if (::execution_direction == EXEC_REVERSE)
6168     return 0;
6169
6170   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6171     remote_vcont_probe ();
6172
6173   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6174     return 0;
6175
6176   p = rs->buf.data ();
6177   endp = p + get_remote_packet_size ();
6178
6179   /* If we could generate a wider range of packets, we'd have to worry
6180      about overflowing BUF.  Should there be a generic
6181      "multi-part-packet" packet?  */
6182
6183   p += xsnprintf (p, endp - p, "vCont");
6184
6185   if (ptid == magic_null_ptid)
6186     {
6187       /* MAGIC_NULL_PTID means that we don't have any active threads,
6188          so we don't have any TID numbers the inferior will
6189          understand.  Make sure to only send forms that do not specify
6190          a TID.  */
6191       append_resumption (p, endp, minus_one_ptid, step, siggnal);
6192     }
6193   else if (ptid == minus_one_ptid || ptid.is_pid ())
6194     {
6195       /* Resume all threads (of all processes, or of a single
6196          process), with preference for INFERIOR_PTID.  This assumes
6197          inferior_ptid belongs to the set of all threads we are about
6198          to resume.  */
6199       if (step || siggnal != GDB_SIGNAL_0)
6200         {
6201           /* Step inferior_ptid, with or without signal.  */
6202           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6203         }
6204
6205       /* Also pass down any pending signaled resumption for other
6206          threads not the current.  */
6207       p = append_pending_thread_resumptions (p, endp, ptid);
6208
6209       /* And continue others without a signal.  */
6210       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6211     }
6212   else
6213     {
6214       /* Scheduler locking; resume only PTID.  */
6215       append_resumption (p, endp, ptid, step, siggnal);
6216     }
6217
6218   gdb_assert (strlen (rs->buf.data ()) < get_remote_packet_size ());
6219   putpkt (rs->buf);
6220
6221   if (target_is_non_stop_p ())
6222     {
6223       /* In non-stop, the stub replies to vCont with "OK".  The stop
6224          reply will be reported asynchronously by means of a `%Stop'
6225          notification.  */
6226       getpkt (&rs->buf, 0);
6227       if (strcmp (rs->buf.data (), "OK") != 0)
6228         error (_("Unexpected vCont reply in non-stop mode: %s"),
6229                rs->buf.data ());
6230     }
6231
6232   return 1;
6233 }
6234
6235 /* Tell the remote machine to resume.  */
6236
6237 void
6238 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6239 {
6240   struct remote_state *rs = get_remote_state ();
6241
6242   /* When connected in non-stop mode, the core resumes threads
6243      individually.  Resuming remote threads directly in target_resume
6244      would thus result in sending one packet per thread.  Instead, to
6245      minimize roundtrip latency, here we just store the resume
6246      request; the actual remote resumption will be done in
6247      target_commit_resume / remote_commit_resume, where we'll be able
6248      to do vCont action coalescing.  */
6249   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6250     {
6251       remote_thread_info *remote_thr;
6252
6253       if (minus_one_ptid == ptid || ptid.is_pid ())
6254         remote_thr = get_remote_thread_info (inferior_ptid);
6255       else
6256         remote_thr = get_remote_thread_info (ptid);
6257
6258       remote_thr->last_resume_step = step;
6259       remote_thr->last_resume_sig = siggnal;
6260       return;
6261     }
6262
6263   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6264      (explained in remote-notif.c:handle_notification) so
6265      remote_notif_process is not called.  We need find a place where
6266      it is safe to start a 'vNotif' sequence.  It is good to do it
6267      before resuming inferior, because inferior was stopped and no RSP
6268      traffic at that moment.  */
6269   if (!target_is_non_stop_p ())
6270     remote_notif_process (rs->notif_state, &notif_client_stop);
6271
6272   rs->last_resume_exec_dir = ::execution_direction;
6273
6274   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6275   if (!remote_resume_with_vcont (ptid, step, siggnal))
6276     remote_resume_with_hc (ptid, step, siggnal);
6277
6278   /* We are about to start executing the inferior, let's register it
6279      with the event loop.  NOTE: this is the one place where all the
6280      execution commands end up.  We could alternatively do this in each
6281      of the execution commands in infcmd.c.  */
6282   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6283      into infcmd.c in order to allow inferior function calls to work
6284      NOT asynchronously.  */
6285   if (target_can_async_p ())
6286     target_async (1);
6287
6288   /* We've just told the target to resume.  The remote server will
6289      wait for the inferior to stop, and then send a stop reply.  In
6290      the mean time, we can't start another command/query ourselves
6291      because the stub wouldn't be ready to process it.  This applies
6292      only to the base all-stop protocol, however.  In non-stop (which
6293      only supports vCont), the stub replies with an "OK", and is
6294      immediate able to process further serial input.  */
6295   if (!target_is_non_stop_p ())
6296     rs->waiting_for_stop_reply = 1;
6297 }
6298
6299 static int is_pending_fork_parent_thread (struct thread_info *thread);
6300
6301 /* Private per-inferior info for target remote processes.  */
6302
6303 struct remote_inferior : public private_inferior
6304 {
6305   /* Whether we can send a wildcard vCont for this process.  */
6306   bool may_wildcard_vcont = true;
6307 };
6308
6309 /* Get the remote private inferior data associated to INF.  */
6310
6311 static remote_inferior *
6312 get_remote_inferior (inferior *inf)
6313 {
6314   if (inf->priv == NULL)
6315     inf->priv.reset (new remote_inferior);
6316
6317   return static_cast<remote_inferior *> (inf->priv.get ());
6318 }
6319
6320 /* Class used to track the construction of a vCont packet in the
6321    outgoing packet buffer.  This is used to send multiple vCont
6322    packets if we have more actions than would fit a single packet.  */
6323
6324 class vcont_builder
6325 {
6326 public:
6327   explicit vcont_builder (remote_target *remote)
6328     : m_remote (remote)
6329   {
6330     restart ();
6331   }
6332
6333   void flush ();
6334   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6335
6336 private:
6337   void restart ();
6338
6339   /* The remote target.  */
6340   remote_target *m_remote;
6341
6342   /* Pointer to the first action.  P points here if no action has been
6343      appended yet.  */
6344   char *m_first_action;
6345
6346   /* Where the next action will be appended.  */
6347   char *m_p;
6348
6349   /* The end of the buffer.  Must never write past this.  */
6350   char *m_endp;
6351 };
6352
6353 /* Prepare the outgoing buffer for a new vCont packet.  */
6354
6355 void
6356 vcont_builder::restart ()
6357 {
6358   struct remote_state *rs = m_remote->get_remote_state ();
6359
6360   m_p = rs->buf.data ();
6361   m_endp = m_p + m_remote->get_remote_packet_size ();
6362   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6363   m_first_action = m_p;
6364 }
6365
6366 /* If the vCont packet being built has any action, send it to the
6367    remote end.  */
6368
6369 void
6370 vcont_builder::flush ()
6371 {
6372   struct remote_state *rs;
6373
6374   if (m_p == m_first_action)
6375     return;
6376
6377   rs = m_remote->get_remote_state ();
6378   m_remote->putpkt (rs->buf);
6379   m_remote->getpkt (&rs->buf, 0);
6380   if (strcmp (rs->buf.data (), "OK") != 0)
6381     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf.data ());
6382 }
6383
6384 /* The largest action is range-stepping, with its two addresses.  This
6385    is more than sufficient.  If a new, bigger action is created, it'll
6386    quickly trigger a failed assertion in append_resumption (and we'll
6387    just bump this).  */
6388 #define MAX_ACTION_SIZE 200
6389
6390 /* Append a new vCont action in the outgoing packet being built.  If
6391    the action doesn't fit the packet along with previous actions, push
6392    what we've got so far to the remote end and start over a new vCont
6393    packet (with the new action).  */
6394
6395 void
6396 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6397 {
6398   char buf[MAX_ACTION_SIZE + 1];
6399
6400   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6401                                             ptid, step, siggnal);
6402
6403   /* Check whether this new action would fit in the vCont packet along
6404      with previous actions.  If not, send what we've got so far and
6405      start a new vCont packet.  */
6406   size_t rsize = endp - buf;
6407   if (rsize > m_endp - m_p)
6408     {
6409       flush ();
6410       restart ();
6411
6412       /* Should now fit.  */
6413       gdb_assert (rsize <= m_endp - m_p);
6414     }
6415
6416   memcpy (m_p, buf, rsize);
6417   m_p += rsize;
6418   *m_p = '\0';
6419 }
6420
6421 /* to_commit_resume implementation.  */
6422
6423 void
6424 remote_target::commit_resume ()
6425 {
6426   int any_process_wildcard;
6427   int may_global_wildcard_vcont;
6428
6429   /* If connected in all-stop mode, we'd send the remote resume
6430      request directly from remote_resume.  Likewise if
6431      reverse-debugging, as there are no defined vCont actions for
6432      reverse execution.  */
6433   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6434     return;
6435
6436   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6437      instead of resuming all threads of each process individually.
6438      However, if any thread of a process must remain halted, we can't
6439      send wildcard resumes and must send one action per thread.
6440
6441      Care must be taken to not resume threads/processes the server
6442      side already told us are stopped, but the core doesn't know about
6443      yet, because the events are still in the vStopped notification
6444      queue.  For example:
6445
6446        #1 => vCont s:p1.1;c
6447        #2 <= OK
6448        #3 <= %Stopped T05 p1.1
6449        #4 => vStopped
6450        #5 <= T05 p1.2
6451        #6 => vStopped
6452        #7 <= OK
6453        #8 (infrun handles the stop for p1.1 and continues stepping)
6454        #9 => vCont s:p1.1;c
6455
6456      The last vCont above would resume thread p1.2 by mistake, because
6457      the server has no idea that the event for p1.2 had not been
6458      handled yet.
6459
6460      The server side must similarly ignore resume actions for the
6461      thread that has a pending %Stopped notification (and any other
6462      threads with events pending), until GDB acks the notification
6463      with vStopped.  Otherwise, e.g., the following case is
6464      mishandled:
6465
6466        #1 => g  (or any other packet)
6467        #2 <= [registers]
6468        #3 <= %Stopped T05 p1.2
6469        #4 => vCont s:p1.1;c
6470        #5 <= OK
6471
6472      Above, the server must not resume thread p1.2.  GDB can't know
6473      that p1.2 stopped until it acks the %Stopped notification, and
6474      since from GDB's perspective all threads should be running, it
6475      sends a "c" action.
6476
6477      Finally, special care must also be given to handling fork/vfork
6478      events.  A (v)fork event actually tells us that two processes
6479      stopped -- the parent and the child.  Until we follow the fork,
6480      we must not resume the child.  Therefore, if we have a pending
6481      fork follow, we must not send a global wildcard resume action
6482      (vCont;c).  We can still send process-wide wildcards though.  */
6483
6484   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6485   may_global_wildcard_vcont = 1;
6486
6487   /* And assume every process is individually wildcard-able too.  */
6488   for (inferior *inf : all_non_exited_inferiors ())
6489     {
6490       remote_inferior *priv = get_remote_inferior (inf);
6491
6492       priv->may_wildcard_vcont = true;
6493     }
6494
6495   /* Check for any pending events (not reported or processed yet) and
6496      disable process and global wildcard resumes appropriately.  */
6497   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6498
6499   for (thread_info *tp : all_non_exited_threads ())
6500     {
6501       /* If a thread of a process is not meant to be resumed, then we
6502          can't wildcard that process.  */
6503       if (!tp->executing)
6504         {
6505           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6506
6507           /* And if we can't wildcard a process, we can't wildcard
6508              everything either.  */
6509           may_global_wildcard_vcont = 0;
6510           continue;
6511         }
6512
6513       /* If a thread is the parent of an unfollowed fork, then we
6514          can't do a global wildcard, as that would resume the fork
6515          child.  */
6516       if (is_pending_fork_parent_thread (tp))
6517         may_global_wildcard_vcont = 0;
6518     }
6519
6520   /* Now let's build the vCont packet(s).  Actions must be appended
6521      from narrower to wider scopes (thread -> process -> global).  If
6522      we end up with too many actions for a single packet vcont_builder
6523      flushes the current vCont packet to the remote side and starts a
6524      new one.  */
6525   struct vcont_builder vcont_builder (this);
6526
6527   /* Threads first.  */
6528   for (thread_info *tp : all_non_exited_threads ())
6529     {
6530       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6531
6532       if (!tp->executing || remote_thr->vcont_resumed)
6533         continue;
6534
6535       gdb_assert (!thread_is_in_step_over_chain (tp));
6536
6537       if (!remote_thr->last_resume_step
6538           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6539           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6540         {
6541           /* We'll send a wildcard resume instead.  */
6542           remote_thr->vcont_resumed = 1;
6543           continue;
6544         }
6545
6546       vcont_builder.push_action (tp->ptid,
6547                                  remote_thr->last_resume_step,
6548                                  remote_thr->last_resume_sig);
6549       remote_thr->vcont_resumed = 1;
6550     }
6551
6552   /* Now check whether we can send any process-wide wildcard.  This is
6553      to avoid sending a global wildcard in the case nothing is
6554      supposed to be resumed.  */
6555   any_process_wildcard = 0;
6556
6557   for (inferior *inf : all_non_exited_inferiors ())
6558     {
6559       if (get_remote_inferior (inf)->may_wildcard_vcont)
6560         {
6561           any_process_wildcard = 1;
6562           break;
6563         }
6564     }
6565
6566   if (any_process_wildcard)
6567     {
6568       /* If all processes are wildcard-able, then send a single "c"
6569          action, otherwise, send an "all (-1) threads of process"
6570          continue action for each running process, if any.  */
6571       if (may_global_wildcard_vcont)
6572         {
6573           vcont_builder.push_action (minus_one_ptid,
6574                                      false, GDB_SIGNAL_0);
6575         }
6576       else
6577         {
6578           for (inferior *inf : all_non_exited_inferiors ())
6579             {
6580               if (get_remote_inferior (inf)->may_wildcard_vcont)
6581                 {
6582                   vcont_builder.push_action (ptid_t (inf->pid),
6583                                              false, GDB_SIGNAL_0);
6584                 }
6585             }
6586         }
6587     }
6588
6589   vcont_builder.flush ();
6590 }
6591
6592 \f
6593
6594 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6595    thread, all threads of a remote process, or all threads of all
6596    processes.  */
6597
6598 void
6599 remote_target::remote_stop_ns (ptid_t ptid)
6600 {
6601   struct remote_state *rs = get_remote_state ();
6602   char *p = rs->buf.data ();
6603   char *endp = p + get_remote_packet_size ();
6604
6605   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6606     remote_vcont_probe ();
6607
6608   if (!rs->supports_vCont.t)
6609     error (_("Remote server does not support stopping threads"));
6610
6611   if (ptid == minus_one_ptid
6612       || (!remote_multi_process_p (rs) && ptid.is_pid ()))
6613     p += xsnprintf (p, endp - p, "vCont;t");
6614   else
6615     {
6616       ptid_t nptid;
6617
6618       p += xsnprintf (p, endp - p, "vCont;t:");
6619
6620       if (ptid.is_pid ())
6621           /* All (-1) threads of process.  */
6622         nptid = ptid_t (ptid.pid (), -1, 0);
6623       else
6624         {
6625           /* Small optimization: if we already have a stop reply for
6626              this thread, no use in telling the stub we want this
6627              stopped.  */
6628           if (peek_stop_reply (ptid))
6629             return;
6630
6631           nptid = ptid;
6632         }
6633
6634       write_ptid (p, endp, nptid);
6635     }
6636
6637   /* In non-stop, we get an immediate OK reply.  The stop reply will
6638      come in asynchronously by notification.  */
6639   putpkt (rs->buf);
6640   getpkt (&rs->buf, 0);
6641   if (strcmp (rs->buf.data (), "OK") != 0)
6642     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid).c_str (),
6643            rs->buf.data ());
6644 }
6645
6646 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6647    interrupt the remote target.  It is undefined which thread of which
6648    process reports the interrupt.  */
6649
6650 void
6651 remote_target::remote_interrupt_as ()
6652 {
6653   struct remote_state *rs = get_remote_state ();
6654
6655   rs->ctrlc_pending_p = 1;
6656
6657   /* If the inferior is stopped already, but the core didn't know
6658      about it yet, just ignore the request.  The cached wait status
6659      will be collected in remote_wait.  */
6660   if (rs->cached_wait_status)
6661     return;
6662
6663   /* Send interrupt_sequence to remote target.  */
6664   send_interrupt_sequence ();
6665 }
6666
6667 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6668    the remote target.  It is undefined which thread of which process
6669    reports the interrupt.  Throws an error if the packet is not
6670    supported by the server.  */
6671
6672 void
6673 remote_target::remote_interrupt_ns ()
6674 {
6675   struct remote_state *rs = get_remote_state ();
6676   char *p = rs->buf.data ();
6677   char *endp = p + get_remote_packet_size ();
6678
6679   xsnprintf (p, endp - p, "vCtrlC");
6680
6681   /* In non-stop, we get an immediate OK reply.  The stop reply will
6682      come in asynchronously by notification.  */
6683   putpkt (rs->buf);
6684   getpkt (&rs->buf, 0);
6685
6686   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6687     {
6688     case PACKET_OK:
6689       break;
6690     case PACKET_UNKNOWN:
6691       error (_("No support for interrupting the remote target."));
6692     case PACKET_ERROR:
6693       error (_("Interrupting target failed: %s"), rs->buf.data ());
6694     }
6695 }
6696
6697 /* Implement the to_stop function for the remote targets.  */
6698
6699 void
6700 remote_target::stop (ptid_t ptid)
6701 {
6702   if (remote_debug)
6703     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6704
6705   if (target_is_non_stop_p ())
6706     remote_stop_ns (ptid);
6707   else
6708     {
6709       /* We don't currently have a way to transparently pause the
6710          remote target in all-stop mode.  Interrupt it instead.  */
6711       remote_interrupt_as ();
6712     }
6713 }
6714
6715 /* Implement the to_interrupt function for the remote targets.  */
6716
6717 void
6718 remote_target::interrupt ()
6719 {
6720   if (remote_debug)
6721     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6722
6723   if (target_is_non_stop_p ())
6724     remote_interrupt_ns ();
6725   else
6726     remote_interrupt_as ();
6727 }
6728
6729 /* Implement the to_pass_ctrlc function for the remote targets.  */
6730
6731 void
6732 remote_target::pass_ctrlc ()
6733 {
6734   struct remote_state *rs = get_remote_state ();
6735
6736   if (remote_debug)
6737     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6738
6739   /* If we're starting up, we're not fully synced yet.  Quit
6740      immediately.  */
6741   if (rs->starting_up)
6742     quit ();
6743   /* If ^C has already been sent once, offer to disconnect.  */
6744   else if (rs->ctrlc_pending_p)
6745     interrupt_query ();
6746   else
6747     target_interrupt ();
6748 }
6749
6750 /* Ask the user what to do when an interrupt is received.  */
6751
6752 void
6753 remote_target::interrupt_query ()
6754 {
6755   struct remote_state *rs = get_remote_state ();
6756
6757   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6758     {
6759       if (query (_("The target is not responding to interrupt requests.\n"
6760                    "Stop debugging it? ")))
6761         {
6762           remote_unpush_target ();
6763           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6764         }
6765     }
6766   else
6767     {
6768       if (query (_("Interrupted while waiting for the program.\n"
6769                    "Give up waiting? ")))
6770         quit ();
6771     }
6772 }
6773
6774 /* Enable/disable target terminal ownership.  Most targets can use
6775    terminal groups to control terminal ownership.  Remote targets are
6776    different in that explicit transfer of ownership to/from GDB/target
6777    is required.  */
6778
6779 void
6780 remote_target::terminal_inferior ()
6781 {
6782   /* NOTE: At this point we could also register our selves as the
6783      recipient of all input.  Any characters typed could then be
6784      passed on down to the target.  */
6785 }
6786
6787 void
6788 remote_target::terminal_ours ()
6789 {
6790 }
6791
6792 static void
6793 remote_console_output (const char *msg)
6794 {
6795   const char *p;
6796
6797   for (p = msg; p[0] && p[1]; p += 2)
6798     {
6799       char tb[2];
6800       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6801
6802       tb[0] = c;
6803       tb[1] = 0;
6804       fputs_unfiltered (tb, gdb_stdtarg);
6805     }
6806   gdb_flush (gdb_stdtarg);
6807 }
6808
6809 struct stop_reply : public notif_event
6810 {
6811   ~stop_reply ();
6812
6813   /* The identifier of the thread about this event  */
6814   ptid_t ptid;
6815
6816   /* The remote state this event is associated with.  When the remote
6817      connection, represented by a remote_state object, is closed,
6818      all the associated stop_reply events should be released.  */
6819   struct remote_state *rs;
6820
6821   struct target_waitstatus ws;
6822
6823   /* The architecture associated with the expedited registers.  */
6824   gdbarch *arch;
6825
6826   /* Expedited registers.  This makes remote debugging a bit more
6827      efficient for those targets that provide critical registers as
6828      part of their normal status mechanism (as another roundtrip to
6829      fetch them is avoided).  */
6830   std::vector<cached_reg_t> regcache;
6831
6832   enum target_stop_reason stop_reason;
6833
6834   CORE_ADDR watch_data_address;
6835
6836   int core;
6837 };
6838
6839 /* Return the length of the stop reply queue.  */
6840
6841 int
6842 remote_target::stop_reply_queue_length ()
6843 {
6844   remote_state *rs = get_remote_state ();
6845   return rs->stop_reply_queue.size ();
6846 }
6847
6848 void
6849 remote_notif_stop_parse (remote_target *remote,
6850                          struct notif_client *self, const char *buf,
6851                          struct notif_event *event)
6852 {
6853   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6854 }
6855
6856 static void
6857 remote_notif_stop_ack (remote_target *remote,
6858                        struct notif_client *self, const char *buf,
6859                        struct notif_event *event)
6860 {
6861   struct stop_reply *stop_reply = (struct stop_reply *) event;
6862
6863   /* acknowledge */
6864   putpkt (remote, self->ack_command);
6865
6866   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6867     {
6868       /* We got an unknown stop reply.  */
6869       error (_("Unknown stop reply"));
6870     }
6871
6872   remote->push_stop_reply (stop_reply);
6873 }
6874
6875 static int
6876 remote_notif_stop_can_get_pending_events (remote_target *remote,
6877                                           struct notif_client *self)
6878 {
6879   /* We can't get pending events in remote_notif_process for
6880      notification stop, and we have to do this in remote_wait_ns
6881      instead.  If we fetch all queued events from stub, remote stub
6882      may exit and we have no chance to process them back in
6883      remote_wait_ns.  */
6884   remote_state *rs = remote->get_remote_state ();
6885   mark_async_event_handler (rs->remote_async_inferior_event_token);
6886   return 0;
6887 }
6888
6889 stop_reply::~stop_reply ()
6890 {
6891   for (cached_reg_t &reg : regcache)
6892     xfree (reg.data);
6893 }
6894
6895 static notif_event_up
6896 remote_notif_stop_alloc_reply ()
6897 {
6898   return notif_event_up (new struct stop_reply ());
6899 }
6900
6901 /* A client of notification Stop.  */
6902
6903 struct notif_client notif_client_stop =
6904 {
6905   "Stop",
6906   "vStopped",
6907   remote_notif_stop_parse,
6908   remote_notif_stop_ack,
6909   remote_notif_stop_can_get_pending_events,
6910   remote_notif_stop_alloc_reply,
6911   REMOTE_NOTIF_STOP,
6912 };
6913
6914 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6915    the pid of the process that owns the threads we want to check, or
6916    -1 if we want to check all threads.  */
6917
6918 static int
6919 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6920                         ptid_t thread_ptid)
6921 {
6922   if (ws->kind == TARGET_WAITKIND_FORKED
6923       || ws->kind == TARGET_WAITKIND_VFORKED)
6924     {
6925       if (event_pid == -1 || event_pid == thread_ptid.pid ())
6926         return 1;
6927     }
6928
6929   return 0;
6930 }
6931
6932 /* Return the thread's pending status used to determine whether the
6933    thread is a fork parent stopped at a fork event.  */
6934
6935 static struct target_waitstatus *
6936 thread_pending_fork_status (struct thread_info *thread)
6937 {
6938   if (thread->suspend.waitstatus_pending_p)
6939     return &thread->suspend.waitstatus;
6940   else
6941     return &thread->pending_follow;
6942 }
6943
6944 /* Determine if THREAD is a pending fork parent thread.  */
6945
6946 static int
6947 is_pending_fork_parent_thread (struct thread_info *thread)
6948 {
6949   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6950   int pid = -1;
6951
6952   return is_pending_fork_parent (ws, pid, thread->ptid);
6953 }
6954
6955 /* If CONTEXT contains any fork child threads that have not been
6956    reported yet, remove them from the CONTEXT list.  If such a
6957    thread exists it is because we are stopped at a fork catchpoint
6958    and have not yet called follow_fork, which will set up the
6959    host-side data structures for the new process.  */
6960
6961 void
6962 remote_target::remove_new_fork_children (threads_listing_context *context)
6963 {
6964   int pid = -1;
6965   struct notif_client *notif = &notif_client_stop;
6966
6967   /* For any threads stopped at a fork event, remove the corresponding
6968      fork child threads from the CONTEXT list.  */
6969   for (thread_info *thread : all_non_exited_threads ())
6970     {
6971       struct target_waitstatus *ws = thread_pending_fork_status (thread);
6972
6973       if (is_pending_fork_parent (ws, pid, thread->ptid))
6974         context->remove_thread (ws->value.related_pid);
6975     }
6976
6977   /* Check for any pending fork events (not reported or processed yet)
6978      in process PID and remove those fork child threads from the
6979      CONTEXT list as well.  */
6980   remote_notif_get_pending_events (notif);
6981   for (auto &event : get_remote_state ()->stop_reply_queue)
6982     if (event->ws.kind == TARGET_WAITKIND_FORKED
6983         || event->ws.kind == TARGET_WAITKIND_VFORKED
6984         || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6985       context->remove_thread (event->ws.value.related_pid);
6986 }
6987
6988 /* Check whether any event pending in the vStopped queue would prevent
6989    a global or process wildcard vCont action.  Clear
6990    *may_global_wildcard if we can't do a global wildcard (vCont;c),
6991    and clear the event inferior's may_wildcard_vcont flag if we can't
6992    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
6993
6994 void
6995 remote_target::check_pending_events_prevent_wildcard_vcont
6996   (int *may_global_wildcard)
6997 {
6998   struct notif_client *notif = &notif_client_stop;
6999
7000   remote_notif_get_pending_events (notif);
7001   for (auto &event : get_remote_state ()->stop_reply_queue)
7002     {
7003       if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7004           || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7005         continue;
7006
7007       if (event->ws.kind == TARGET_WAITKIND_FORKED
7008           || event->ws.kind == TARGET_WAITKIND_VFORKED)
7009         *may_global_wildcard = 0;
7010
7011       struct inferior *inf = find_inferior_ptid (event->ptid);
7012
7013       /* This may be the first time we heard about this process.
7014          Regardless, we must not do a global wildcard resume, otherwise
7015          we'd resume this process too.  */
7016       *may_global_wildcard = 0;
7017       if (inf != NULL)
7018         get_remote_inferior (inf)->may_wildcard_vcont = false;
7019     }
7020 }
7021
7022 /* Discard all pending stop replies of inferior INF.  */
7023
7024 void
7025 remote_target::discard_pending_stop_replies (struct inferior *inf)
7026 {
7027   struct stop_reply *reply;
7028   struct remote_state *rs = get_remote_state ();
7029   struct remote_notif_state *rns = rs->notif_state;
7030
7031   /* This function can be notified when an inferior exists.  When the
7032      target is not remote, the notification state is NULL.  */
7033   if (rs->remote_desc == NULL)
7034     return;
7035
7036   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7037
7038   /* Discard the in-flight notification.  */
7039   if (reply != NULL && reply->ptid.pid () == inf->pid)
7040     {
7041       delete reply;
7042       rns->pending_event[notif_client_stop.id] = NULL;
7043     }
7044
7045   /* Discard the stop replies we have already pulled with
7046      vStopped.  */
7047   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7048                               rs->stop_reply_queue.end (),
7049                               [=] (const stop_reply_up &event)
7050                               {
7051                                 return event->ptid.pid () == inf->pid;
7052                               });
7053   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7054 }
7055
7056 /* Discard the stop replies for RS in stop_reply_queue.  */
7057
7058 void
7059 remote_target::discard_pending_stop_replies_in_queue ()
7060 {
7061   remote_state *rs = get_remote_state ();
7062
7063   /* Discard the stop replies we have already pulled with
7064      vStopped.  */
7065   auto iter = std::remove_if (rs->stop_reply_queue.begin (),
7066                               rs->stop_reply_queue.end (),
7067                               [=] (const stop_reply_up &event)
7068                               {
7069                                 return event->rs == rs;
7070                               });
7071   rs->stop_reply_queue.erase (iter, rs->stop_reply_queue.end ());
7072 }
7073
7074 /* Remove the first reply in 'stop_reply_queue' which matches
7075    PTID.  */
7076
7077 struct stop_reply *
7078 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7079 {
7080   remote_state *rs = get_remote_state ();
7081
7082   auto iter = std::find_if (rs->stop_reply_queue.begin (),
7083                             rs->stop_reply_queue.end (),
7084                             [=] (const stop_reply_up &event)
7085                             {
7086                               return event->ptid.matches (ptid);
7087                             });
7088   struct stop_reply *result;
7089   if (iter == rs->stop_reply_queue.end ())
7090     result = nullptr;
7091   else
7092     {
7093       result = iter->release ();
7094       rs->stop_reply_queue.erase (iter);
7095     }
7096
7097   if (notif_debug)
7098     fprintf_unfiltered (gdb_stdlog,
7099                         "notif: discard queued event: 'Stop' in %s\n",
7100                         target_pid_to_str (ptid).c_str ());
7101
7102   return result;
7103 }
7104
7105 /* Look for a queued stop reply belonging to PTID.  If one is found,
7106    remove it from the queue, and return it.  Returns NULL if none is
7107    found.  If there are still queued events left to process, tell the
7108    event loop to get back to target_wait soon.  */
7109
7110 struct stop_reply *
7111 remote_target::queued_stop_reply (ptid_t ptid)
7112 {
7113   remote_state *rs = get_remote_state ();
7114   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7115
7116   if (!rs->stop_reply_queue.empty ())
7117     {
7118       /* There's still at least an event left.  */
7119       mark_async_event_handler (rs->remote_async_inferior_event_token);
7120     }
7121
7122   return r;
7123 }
7124
7125 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7126    know that we now have at least one queued event left to pass to the
7127    core side, tell the event loop to get back to target_wait soon.  */
7128
7129 void
7130 remote_target::push_stop_reply (struct stop_reply *new_event)
7131 {
7132   remote_state *rs = get_remote_state ();
7133   rs->stop_reply_queue.push_back (stop_reply_up (new_event));
7134
7135   if (notif_debug)
7136     fprintf_unfiltered (gdb_stdlog,
7137                         "notif: push 'Stop' %s to queue %d\n",
7138                         target_pid_to_str (new_event->ptid).c_str (),
7139                         int (rs->stop_reply_queue.size ()));
7140
7141   mark_async_event_handler (rs->remote_async_inferior_event_token);
7142 }
7143
7144 /* Returns true if we have a stop reply for PTID.  */
7145
7146 int
7147 remote_target::peek_stop_reply (ptid_t ptid)
7148 {
7149   remote_state *rs = get_remote_state ();
7150   for (auto &event : rs->stop_reply_queue)
7151     if (ptid == event->ptid
7152         && event->ws.kind == TARGET_WAITKIND_STOPPED)
7153       return 1;
7154   return 0;
7155 }
7156
7157 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7158    starting with P and ending with PEND matches PREFIX.  */
7159
7160 static int
7161 strprefix (const char *p, const char *pend, const char *prefix)
7162 {
7163   for ( ; p < pend; p++, prefix++)
7164     if (*p != *prefix)
7165       return 0;
7166   return *prefix == '\0';
7167 }
7168
7169 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7170    result is stored in EVENT, or throws an error.  */
7171
7172 void
7173 remote_target::remote_parse_stop_reply (const char *buf, stop_reply *event)
7174 {
7175   remote_arch_state *rsa = NULL;
7176   ULONGEST addr;
7177   const char *p;
7178   int skipregs = 0;
7179
7180   event->ptid = null_ptid;
7181   event->rs = get_remote_state ();
7182   event->ws.kind = TARGET_WAITKIND_IGNORE;
7183   event->ws.value.integer = 0;
7184   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7185   event->regcache.clear ();
7186   event->core = -1;
7187
7188   switch (buf[0])
7189     {
7190     case 'T':           /* Status with PC, SP, FP, ...  */
7191       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7192       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7193             ss = signal number
7194             n... = register number
7195             r... = register contents
7196       */
7197
7198       p = &buf[3];      /* after Txx */
7199       while (*p)
7200         {
7201           const char *p1;
7202           int fieldsize;
7203
7204           p1 = strchr (p, ':');
7205           if (p1 == NULL)
7206             error (_("Malformed packet(a) (missing colon): %s\n\
7207 Packet: '%s'\n"),
7208                    p, buf);
7209           if (p == p1)
7210             error (_("Malformed packet(a) (missing register number): %s\n\
7211 Packet: '%s'\n"),
7212                    p, buf);
7213
7214           /* Some "registers" are actually extended stop information.
7215              Note if you're adding a new entry here: GDB 7.9 and
7216              earlier assume that all register "numbers" that start
7217              with an hex digit are real register numbers.  Make sure
7218              the server only sends such a packet if it knows the
7219              client understands it.  */
7220
7221           if (strprefix (p, p1, "thread"))
7222             event->ptid = read_ptid (++p1, &p);
7223           else if (strprefix (p, p1, "syscall_entry"))
7224             {
7225               ULONGEST sysno;
7226
7227               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7228               p = unpack_varlen_hex (++p1, &sysno);
7229               event->ws.value.syscall_number = (int) sysno;
7230             }
7231           else if (strprefix (p, p1, "syscall_return"))
7232             {
7233               ULONGEST sysno;
7234
7235               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7236               p = unpack_varlen_hex (++p1, &sysno);
7237               event->ws.value.syscall_number = (int) sysno;
7238             }
7239           else if (strprefix (p, p1, "watch")
7240                    || strprefix (p, p1, "rwatch")
7241                    || strprefix (p, p1, "awatch"))
7242             {
7243               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7244               p = unpack_varlen_hex (++p1, &addr);
7245               event->watch_data_address = (CORE_ADDR) addr;
7246             }
7247           else if (strprefix (p, p1, "swbreak"))
7248             {
7249               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7250
7251               /* Make sure the stub doesn't forget to indicate support
7252                  with qSupported.  */
7253               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7254                 error (_("Unexpected swbreak stop reason"));
7255
7256               /* The value part is documented as "must be empty",
7257                  though we ignore it, in case we ever decide to make
7258                  use of it in a backward compatible way.  */
7259               p = strchrnul (p1 + 1, ';');
7260             }
7261           else if (strprefix (p, p1, "hwbreak"))
7262             {
7263               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7264
7265               /* Make sure the stub doesn't forget to indicate support
7266                  with qSupported.  */
7267               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7268                 error (_("Unexpected hwbreak stop reason"));
7269
7270               /* See above.  */
7271               p = strchrnul (p1 + 1, ';');
7272             }
7273           else if (strprefix (p, p1, "library"))
7274             {
7275               event->ws.kind = TARGET_WAITKIND_LOADED;
7276               p = strchrnul (p1 + 1, ';');
7277             }
7278           else if (strprefix (p, p1, "replaylog"))
7279             {
7280               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7281               /* p1 will indicate "begin" or "end", but it makes
7282                  no difference for now, so ignore it.  */
7283               p = strchrnul (p1 + 1, ';');
7284             }
7285           else if (strprefix (p, p1, "core"))
7286             {
7287               ULONGEST c;
7288
7289               p = unpack_varlen_hex (++p1, &c);
7290               event->core = c;
7291             }
7292           else if (strprefix (p, p1, "fork"))
7293             {
7294               event->ws.value.related_pid = read_ptid (++p1, &p);
7295               event->ws.kind = TARGET_WAITKIND_FORKED;
7296             }
7297           else if (strprefix (p, p1, "vfork"))
7298             {
7299               event->ws.value.related_pid = read_ptid (++p1, &p);
7300               event->ws.kind = TARGET_WAITKIND_VFORKED;
7301             }
7302           else if (strprefix (p, p1, "vforkdone"))
7303             {
7304               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7305               p = strchrnul (p1 + 1, ';');
7306             }
7307           else if (strprefix (p, p1, "exec"))
7308             {
7309               ULONGEST ignored;
7310               int pathlen;
7311
7312               /* Determine the length of the execd pathname.  */
7313               p = unpack_varlen_hex (++p1, &ignored);
7314               pathlen = (p - p1) / 2;
7315
7316               /* Save the pathname for event reporting and for
7317                  the next run command.  */
7318               gdb::unique_xmalloc_ptr<char[]> pathname
7319                 ((char *) xmalloc (pathlen + 1));
7320               hex2bin (p1, (gdb_byte *) pathname.get (), pathlen);
7321               pathname[pathlen] = '\0';
7322
7323               /* This is freed during event handling.  */
7324               event->ws.value.execd_pathname = pathname.release ();
7325               event->ws.kind = TARGET_WAITKIND_EXECD;
7326
7327               /* Skip the registers included in this packet, since
7328                  they may be for an architecture different from the
7329                  one used by the original program.  */
7330               skipregs = 1;
7331             }
7332           else if (strprefix (p, p1, "create"))
7333             {
7334               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7335               p = strchrnul (p1 + 1, ';');
7336             }
7337           else
7338             {
7339               ULONGEST pnum;
7340               const char *p_temp;
7341
7342               if (skipregs)
7343                 {
7344                   p = strchrnul (p1 + 1, ';');
7345                   p++;
7346                   continue;
7347                 }
7348
7349               /* Maybe a real ``P'' register number.  */
7350               p_temp = unpack_varlen_hex (p, &pnum);
7351               /* If the first invalid character is the colon, we got a
7352                  register number.  Otherwise, it's an unknown stop
7353                  reason.  */
7354               if (p_temp == p1)
7355                 {
7356                   /* If we haven't parsed the event's thread yet, find
7357                      it now, in order to find the architecture of the
7358                      reported expedited registers.  */
7359                   if (event->ptid == null_ptid)
7360                     {
7361                       const char *thr = strstr (p1 + 1, ";thread:");
7362                       if (thr != NULL)
7363                         event->ptid = read_ptid (thr + strlen (";thread:"),
7364                                                  NULL);
7365                       else
7366                         {
7367                           /* Either the current thread hasn't changed,
7368                              or the inferior is not multi-threaded.
7369                              The event must be for the thread we last
7370                              set as (or learned as being) current.  */
7371                           event->ptid = event->rs->general_thread;
7372                         }
7373                     }
7374
7375                   if (rsa == NULL)
7376                     {
7377                       inferior *inf = (event->ptid == null_ptid
7378                                        ? NULL
7379                                        : find_inferior_ptid (event->ptid));
7380                       /* If this is the first time we learn anything
7381                          about this process, skip the registers
7382                          included in this packet, since we don't yet
7383                          know which architecture to use to parse them.
7384                          We'll determine the architecture later when
7385                          we process the stop reply and retrieve the
7386                          target description, via
7387                          remote_notice_new_inferior ->
7388                          post_create_inferior.  */
7389                       if (inf == NULL)
7390                         {
7391                           p = strchrnul (p1 + 1, ';');
7392                           p++;
7393                           continue;
7394                         }
7395
7396                       event->arch = inf->gdbarch;
7397                       rsa = event->rs->get_remote_arch_state (event->arch);
7398                     }
7399
7400                   packet_reg *reg
7401                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7402                   cached_reg_t cached_reg;
7403
7404                   if (reg == NULL)
7405                     error (_("Remote sent bad register number %s: %s\n\
7406 Packet: '%s'\n"),
7407                            hex_string (pnum), p, buf);
7408
7409                   cached_reg.num = reg->regnum;
7410                   cached_reg.data = (gdb_byte *)
7411                     xmalloc (register_size (event->arch, reg->regnum));
7412
7413                   p = p1 + 1;
7414                   fieldsize = hex2bin (p, cached_reg.data,
7415                                        register_size (event->arch, reg->regnum));
7416                   p += 2 * fieldsize;
7417                   if (fieldsize < register_size (event->arch, reg->regnum))
7418                     warning (_("Remote reply is too short: %s"), buf);
7419
7420                   event->regcache.push_back (cached_reg);
7421                 }
7422               else
7423                 {
7424                   /* Not a number.  Silently skip unknown optional
7425                      info.  */
7426                   p = strchrnul (p1 + 1, ';');
7427                 }
7428             }
7429
7430           if (*p != ';')
7431             error (_("Remote register badly formatted: %s\nhere: %s"),
7432                    buf, p);
7433           ++p;
7434         }
7435
7436       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7437         break;
7438
7439       /* fall through */
7440     case 'S':           /* Old style status, just signal only.  */
7441       {
7442         int sig;
7443
7444         event->ws.kind = TARGET_WAITKIND_STOPPED;
7445         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7446         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7447           event->ws.value.sig = (enum gdb_signal) sig;
7448         else
7449           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7450       }
7451       break;
7452     case 'w':           /* Thread exited.  */
7453       {
7454         ULONGEST value;
7455
7456         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7457         p = unpack_varlen_hex (&buf[1], &value);
7458         event->ws.value.integer = value;
7459         if (*p != ';')
7460           error (_("stop reply packet badly formatted: %s"), buf);
7461         event->ptid = read_ptid (++p, NULL);
7462         break;
7463       }
7464     case 'W':           /* Target exited.  */
7465     case 'X':
7466       {
7467         int pid;
7468         ULONGEST value;
7469
7470         /* GDB used to accept only 2 hex chars here.  Stubs should
7471            only send more if they detect GDB supports multi-process
7472            support.  */
7473         p = unpack_varlen_hex (&buf[1], &value);
7474
7475         if (buf[0] == 'W')
7476           {
7477             /* The remote process exited.  */
7478             event->ws.kind = TARGET_WAITKIND_EXITED;
7479             event->ws.value.integer = value;
7480           }
7481         else
7482           {
7483             /* The remote process exited with a signal.  */
7484             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7485             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7486               event->ws.value.sig = (enum gdb_signal) value;
7487             else
7488               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7489           }
7490
7491         /* If no process is specified, assume inferior_ptid.  */
7492         pid = inferior_ptid.pid ();
7493         if (*p == '\0')
7494           ;
7495         else if (*p == ';')
7496           {
7497             p++;
7498
7499             if (*p == '\0')
7500               ;
7501             else if (startswith (p, "process:"))
7502               {
7503                 ULONGEST upid;
7504
7505                 p += sizeof ("process:") - 1;
7506                 unpack_varlen_hex (p, &upid);
7507                 pid = upid;
7508               }
7509             else
7510               error (_("unknown stop reply packet: %s"), buf);
7511           }
7512         else
7513           error (_("unknown stop reply packet: %s"), buf);
7514         event->ptid = ptid_t (pid);
7515       }
7516       break;
7517     case 'N':
7518       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7519       event->ptid = minus_one_ptid;
7520       break;
7521     }
7522
7523   if (target_is_non_stop_p () && event->ptid == null_ptid)
7524     error (_("No process or thread specified in stop reply: %s"), buf);
7525 }
7526
7527 /* When the stub wants to tell GDB about a new notification reply, it
7528    sends a notification (%Stop, for example).  Those can come it at
7529    any time, hence, we have to make sure that any pending
7530    putpkt/getpkt sequence we're making is finished, before querying
7531    the stub for more events with the corresponding ack command
7532    (vStopped, for example).  E.g., if we started a vStopped sequence
7533    immediately upon receiving the notification, something like this
7534    could happen:
7535
7536     1.1) --> Hg 1
7537     1.2) <-- OK
7538     1.3) --> g
7539     1.4) <-- %Stop
7540     1.5) --> vStopped
7541     1.6) <-- (registers reply to step #1.3)
7542
7543    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7544    query.
7545
7546    To solve this, whenever we parse a %Stop notification successfully,
7547    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7548    doing whatever we were doing:
7549
7550     2.1) --> Hg 1
7551     2.2) <-- OK
7552     2.3) --> g
7553     2.4) <-- %Stop
7554       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7555     2.5) <-- (registers reply to step #2.3)
7556
7557    Eventualy after step #2.5, we return to the event loop, which
7558    notices there's an event on the
7559    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7560    associated callback --- the function below.  At this point, we're
7561    always safe to start a vStopped sequence. :
7562
7563     2.6) --> vStopped
7564     2.7) <-- T05 thread:2
7565     2.8) --> vStopped
7566     2.9) --> OK
7567 */
7568
7569 void
7570 remote_target::remote_notif_get_pending_events (notif_client *nc)
7571 {
7572   struct remote_state *rs = get_remote_state ();
7573
7574   if (rs->notif_state->pending_event[nc->id] != NULL)
7575     {
7576       if (notif_debug)
7577         fprintf_unfiltered (gdb_stdlog,
7578                             "notif: process: '%s' ack pending event\n",
7579                             nc->name);
7580
7581       /* acknowledge */
7582       nc->ack (this, nc, rs->buf.data (),
7583                rs->notif_state->pending_event[nc->id]);
7584       rs->notif_state->pending_event[nc->id] = NULL;
7585
7586       while (1)
7587         {
7588           getpkt (&rs->buf, 0);
7589           if (strcmp (rs->buf.data (), "OK") == 0)
7590             break;
7591           else
7592             remote_notif_ack (this, nc, rs->buf.data ());
7593         }
7594     }
7595   else
7596     {
7597       if (notif_debug)
7598         fprintf_unfiltered (gdb_stdlog,
7599                             "notif: process: '%s' no pending reply\n",
7600                             nc->name);
7601     }
7602 }
7603
7604 /* Wrapper around remote_target::remote_notif_get_pending_events to
7605    avoid having to export the whole remote_target class.  */
7606
7607 void
7608 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7609 {
7610   remote->remote_notif_get_pending_events (nc);
7611 }
7612
7613 /* Called when it is decided that STOP_REPLY holds the info of the
7614    event that is to be returned to the core.  This function always
7615    destroys STOP_REPLY.  */
7616
7617 ptid_t
7618 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7619                                    struct target_waitstatus *status)
7620 {
7621   ptid_t ptid;
7622
7623   *status = stop_reply->ws;
7624   ptid = stop_reply->ptid;
7625
7626   /* If no thread/process was reported by the stub, assume the current
7627      inferior.  */
7628   if (ptid == null_ptid)
7629     ptid = inferior_ptid;
7630
7631   if (status->kind != TARGET_WAITKIND_EXITED
7632       && status->kind != TARGET_WAITKIND_SIGNALLED
7633       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7634     {
7635       /* Expedited registers.  */
7636       if (!stop_reply->regcache.empty ())
7637         {
7638           struct regcache *regcache
7639             = get_thread_arch_regcache (ptid, stop_reply->arch);
7640
7641           for (cached_reg_t &reg : stop_reply->regcache)
7642             {
7643               regcache->raw_supply (reg.num, reg.data);
7644               xfree (reg.data);
7645             }
7646
7647           stop_reply->regcache.clear ();
7648         }
7649
7650       remote_notice_new_inferior (ptid, 0);
7651       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7652       remote_thr->core = stop_reply->core;
7653       remote_thr->stop_reason = stop_reply->stop_reason;
7654       remote_thr->watch_data_address = stop_reply->watch_data_address;
7655       remote_thr->vcont_resumed = 0;
7656     }
7657
7658   delete stop_reply;
7659   return ptid;
7660 }
7661
7662 /* The non-stop mode version of target_wait.  */
7663
7664 ptid_t
7665 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7666 {
7667   struct remote_state *rs = get_remote_state ();
7668   struct stop_reply *stop_reply;
7669   int ret;
7670   int is_notif = 0;
7671
7672   /* If in non-stop mode, get out of getpkt even if a
7673      notification is received.  */
7674
7675   ret = getpkt_or_notif_sane (&rs->buf, 0 /* forever */, &is_notif);
7676   while (1)
7677     {
7678       if (ret != -1 && !is_notif)
7679         switch (rs->buf[0])
7680           {
7681           case 'E':             /* Error of some sort.  */
7682             /* We're out of sync with the target now.  Did it continue
7683                or not?  We can't tell which thread it was in non-stop,
7684                so just ignore this.  */
7685             warning (_("Remote failure reply: %s"), rs->buf.data ());
7686             break;
7687           case 'O':             /* Console output.  */
7688             remote_console_output (&rs->buf[1]);
7689             break;
7690           default:
7691             warning (_("Invalid remote reply: %s"), rs->buf.data ());
7692             break;
7693           }
7694
7695       /* Acknowledge a pending stop reply that may have arrived in the
7696          mean time.  */
7697       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7698         remote_notif_get_pending_events (&notif_client_stop);
7699
7700       /* If indeed we noticed a stop reply, we're done.  */
7701       stop_reply = queued_stop_reply (ptid);
7702       if (stop_reply != NULL)
7703         return process_stop_reply (stop_reply, status);
7704
7705       /* Still no event.  If we're just polling for an event, then
7706          return to the event loop.  */
7707       if (options & TARGET_WNOHANG)
7708         {
7709           status->kind = TARGET_WAITKIND_IGNORE;
7710           return minus_one_ptid;
7711         }
7712
7713       /* Otherwise do a blocking wait.  */
7714       ret = getpkt_or_notif_sane (&rs->buf, 1 /* forever */, &is_notif);
7715     }
7716 }
7717
7718 /* Wait until the remote machine stops, then return, storing status in
7719    STATUS just as `wait' would.  */
7720
7721 ptid_t
7722 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7723 {
7724   struct remote_state *rs = get_remote_state ();
7725   ptid_t event_ptid = null_ptid;
7726   char *buf;
7727   struct stop_reply *stop_reply;
7728
7729  again:
7730
7731   status->kind = TARGET_WAITKIND_IGNORE;
7732   status->value.integer = 0;
7733
7734   stop_reply = queued_stop_reply (ptid);
7735   if (stop_reply != NULL)
7736     return process_stop_reply (stop_reply, status);
7737
7738   if (rs->cached_wait_status)
7739     /* Use the cached wait status, but only once.  */
7740     rs->cached_wait_status = 0;
7741   else
7742     {
7743       int ret;
7744       int is_notif;
7745       int forever = ((options & TARGET_WNOHANG) == 0
7746                      && rs->wait_forever_enabled_p);
7747
7748       if (!rs->waiting_for_stop_reply)
7749         {
7750           status->kind = TARGET_WAITKIND_NO_RESUMED;
7751           return minus_one_ptid;
7752         }
7753
7754       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7755          _never_ wait for ever -> test on target_is_async_p().
7756          However, before we do that we need to ensure that the caller
7757          knows how to take the target into/out of async mode.  */
7758       ret = getpkt_or_notif_sane (&rs->buf, forever, &is_notif);
7759
7760       /* GDB gets a notification.  Return to core as this event is
7761          not interesting.  */
7762       if (ret != -1 && is_notif)
7763         return minus_one_ptid;
7764
7765       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7766         return minus_one_ptid;
7767     }
7768
7769   buf = rs->buf.data ();
7770
7771   /* Assume that the target has acknowledged Ctrl-C unless we receive
7772      an 'F' or 'O' packet.  */
7773   if (buf[0] != 'F' && buf[0] != 'O')
7774     rs->ctrlc_pending_p = 0;
7775
7776   switch (buf[0])
7777     {
7778     case 'E':           /* Error of some sort.  */
7779       /* We're out of sync with the target now.  Did it continue or
7780          not?  Not is more likely, so report a stop.  */
7781       rs->waiting_for_stop_reply = 0;
7782
7783       warning (_("Remote failure reply: %s"), buf);
7784       status->kind = TARGET_WAITKIND_STOPPED;
7785       status->value.sig = GDB_SIGNAL_0;
7786       break;
7787     case 'F':           /* File-I/O request.  */
7788       /* GDB may access the inferior memory while handling the File-I/O
7789          request, but we don't want GDB accessing memory while waiting
7790          for a stop reply.  See the comments in putpkt_binary.  Set
7791          waiting_for_stop_reply to 0 temporarily.  */
7792       rs->waiting_for_stop_reply = 0;
7793       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7794       rs->ctrlc_pending_p = 0;
7795       /* GDB handled the File-I/O request, and the target is running
7796          again.  Keep waiting for events.  */
7797       rs->waiting_for_stop_reply = 1;
7798       break;
7799     case 'N': case 'T': case 'S': case 'X': case 'W':
7800       {
7801         /* There is a stop reply to handle.  */
7802         rs->waiting_for_stop_reply = 0;
7803
7804         stop_reply
7805           = (struct stop_reply *) remote_notif_parse (this,
7806                                                       &notif_client_stop,
7807                                                       rs->buf.data ());
7808
7809         event_ptid = process_stop_reply (stop_reply, status);
7810         break;
7811       }
7812     case 'O':           /* Console output.  */
7813       remote_console_output (buf + 1);
7814       break;
7815     case '\0':
7816       if (rs->last_sent_signal != GDB_SIGNAL_0)
7817         {
7818           /* Zero length reply means that we tried 'S' or 'C' and the
7819              remote system doesn't support it.  */
7820           target_terminal::ours_for_output ();
7821           printf_filtered
7822             ("Can't send signals to this remote system.  %s not sent.\n",
7823              gdb_signal_to_name (rs->last_sent_signal));
7824           rs->last_sent_signal = GDB_SIGNAL_0;
7825           target_terminal::inferior ();
7826
7827           strcpy (buf, rs->last_sent_step ? "s" : "c");
7828           putpkt (buf);
7829           break;
7830         }
7831       /* fallthrough */
7832     default:
7833       warning (_("Invalid remote reply: %s"), buf);
7834       break;
7835     }
7836
7837   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7838     return minus_one_ptid;
7839   else if (status->kind == TARGET_WAITKIND_IGNORE)
7840     {
7841       /* Nothing interesting happened.  If we're doing a non-blocking
7842          poll, we're done.  Otherwise, go back to waiting.  */
7843       if (options & TARGET_WNOHANG)
7844         return minus_one_ptid;
7845       else
7846         goto again;
7847     }
7848   else if (status->kind != TARGET_WAITKIND_EXITED
7849            && status->kind != TARGET_WAITKIND_SIGNALLED)
7850     {
7851       if (event_ptid != null_ptid)
7852         record_currthread (rs, event_ptid);
7853       else
7854         event_ptid = inferior_ptid;
7855     }
7856   else
7857     /* A process exit.  Invalidate our notion of current thread.  */
7858     record_currthread (rs, minus_one_ptid);
7859
7860   return event_ptid;
7861 }
7862
7863 /* Wait until the remote machine stops, then return, storing status in
7864    STATUS just as `wait' would.  */
7865
7866 ptid_t
7867 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
7868 {
7869   ptid_t event_ptid;
7870
7871   if (target_is_non_stop_p ())
7872     event_ptid = wait_ns (ptid, status, options);
7873   else
7874     event_ptid = wait_as (ptid, status, options);
7875
7876   if (target_is_async_p ())
7877     {
7878       remote_state *rs = get_remote_state ();
7879
7880       /* If there are are events left in the queue tell the event loop
7881          to return here.  */
7882       if (!rs->stop_reply_queue.empty ())
7883         mark_async_event_handler (rs->remote_async_inferior_event_token);
7884     }
7885
7886   return event_ptid;
7887 }
7888
7889 /* Fetch a single register using a 'p' packet.  */
7890
7891 int
7892 remote_target::fetch_register_using_p (struct regcache *regcache,
7893                                        packet_reg *reg)
7894 {
7895   struct gdbarch *gdbarch = regcache->arch ();
7896   struct remote_state *rs = get_remote_state ();
7897   char *buf, *p;
7898   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
7899   int i;
7900
7901   if (packet_support (PACKET_p) == PACKET_DISABLE)
7902     return 0;
7903
7904   if (reg->pnum == -1)
7905     return 0;
7906
7907   p = rs->buf.data ();
7908   *p++ = 'p';
7909   p += hexnumstr (p, reg->pnum);
7910   *p++ = '\0';
7911   putpkt (rs->buf);
7912   getpkt (&rs->buf, 0);
7913
7914   buf = rs->buf.data ();
7915
7916   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_p]))
7917     {
7918     case PACKET_OK:
7919       break;
7920     case PACKET_UNKNOWN:
7921       return 0;
7922     case PACKET_ERROR:
7923       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
7924              gdbarch_register_name (regcache->arch (), 
7925                                     reg->regnum), 
7926              buf);
7927     }
7928
7929   /* If this register is unfetchable, tell the regcache.  */
7930   if (buf[0] == 'x')
7931     {
7932       regcache->raw_supply (reg->regnum, NULL);
7933       return 1;
7934     }
7935
7936   /* Otherwise, parse and supply the value.  */
7937   p = buf;
7938   i = 0;
7939   while (p[0] != 0)
7940     {
7941       if (p[1] == 0)
7942         error (_("fetch_register_using_p: early buf termination"));
7943
7944       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
7945       p += 2;
7946     }
7947   regcache->raw_supply (reg->regnum, regp);
7948   return 1;
7949 }
7950
7951 /* Fetch the registers included in the target's 'g' packet.  */
7952
7953 int
7954 remote_target::send_g_packet ()
7955 {
7956   struct remote_state *rs = get_remote_state ();
7957   int buf_len;
7958
7959   xsnprintf (rs->buf.data (), get_remote_packet_size (), "g");
7960   putpkt (rs->buf);
7961   getpkt (&rs->buf, 0);
7962   if (packet_check_result (rs->buf) == PACKET_ERROR)
7963     error (_("Could not read registers; remote failure reply '%s'"),
7964            rs->buf.data ());
7965
7966   /* We can get out of synch in various cases.  If the first character
7967      in the buffer is not a hex character, assume that has happened
7968      and try to fetch another packet to read.  */
7969   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
7970          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
7971          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
7972          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
7973     {
7974       if (remote_debug)
7975         fprintf_unfiltered (gdb_stdlog,
7976                             "Bad register packet; fetching a new packet\n");
7977       getpkt (&rs->buf, 0);
7978     }
7979
7980   buf_len = strlen (rs->buf.data ());
7981
7982   /* Sanity check the received packet.  */
7983   if (buf_len % 2 != 0)
7984     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf.data ());
7985
7986   return buf_len / 2;
7987 }
7988
7989 void
7990 remote_target::process_g_packet (struct regcache *regcache)
7991 {
7992   struct gdbarch *gdbarch = regcache->arch ();
7993   struct remote_state *rs = get_remote_state ();
7994   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
7995   int i, buf_len;
7996   char *p;
7997   char *regs;
7998
7999   buf_len = strlen (rs->buf.data ());
8000
8001   /* Further sanity checks, with knowledge of the architecture.  */
8002   if (buf_len > 2 * rsa->sizeof_g_packet)
8003     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8004              "bytes): %s"),
8005            rsa->sizeof_g_packet, buf_len / 2,
8006            rs->buf.data ());
8007
8008   /* Save the size of the packet sent to us by the target.  It is used
8009      as a heuristic when determining the max size of packets that the
8010      target can safely receive.  */
8011   if (rsa->actual_register_packet_size == 0)
8012     rsa->actual_register_packet_size = buf_len;
8013
8014   /* If this is smaller than we guessed the 'g' packet would be,
8015      update our records.  A 'g' reply that doesn't include a register's
8016      value implies either that the register is not available, or that
8017      the 'p' packet must be used.  */
8018   if (buf_len < 2 * rsa->sizeof_g_packet)
8019     {
8020       long sizeof_g_packet = buf_len / 2;
8021
8022       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8023         {
8024           long offset = rsa->regs[i].offset;
8025           long reg_size = register_size (gdbarch, i);
8026
8027           if (rsa->regs[i].pnum == -1)
8028             continue;
8029
8030           if (offset >= sizeof_g_packet)
8031             rsa->regs[i].in_g_packet = 0;
8032           else if (offset + reg_size > sizeof_g_packet)
8033             error (_("Truncated register %d in remote 'g' packet"), i);
8034           else
8035             rsa->regs[i].in_g_packet = 1;
8036         }
8037
8038       /* Looks valid enough, we can assume this is the correct length
8039          for a 'g' packet.  It's important not to adjust
8040          rsa->sizeof_g_packet if we have truncated registers otherwise
8041          this "if" won't be run the next time the method is called
8042          with a packet of the same size and one of the internal errors
8043          below will trigger instead.  */
8044       rsa->sizeof_g_packet = sizeof_g_packet;
8045     }
8046
8047   regs = (char *) alloca (rsa->sizeof_g_packet);
8048
8049   /* Unimplemented registers read as all bits zero.  */
8050   memset (regs, 0, rsa->sizeof_g_packet);
8051
8052   /* Reply describes registers byte by byte, each byte encoded as two
8053      hex characters.  Suck them all up, then supply them to the
8054      register cacheing/storage mechanism.  */
8055
8056   p = rs->buf.data ();
8057   for (i = 0; i < rsa->sizeof_g_packet; i++)
8058     {
8059       if (p[0] == 0 || p[1] == 0)
8060         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
8061         internal_error (__FILE__, __LINE__,
8062                         _("unexpected end of 'g' packet reply"));
8063
8064       if (p[0] == 'x' && p[1] == 'x')
8065         regs[i] = 0;            /* 'x' */
8066       else
8067         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8068       p += 2;
8069     }
8070
8071   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8072     {
8073       struct packet_reg *r = &rsa->regs[i];
8074       long reg_size = register_size (gdbarch, i);
8075
8076       if (r->in_g_packet)
8077         {
8078           if ((r->offset + reg_size) * 2 > strlen (rs->buf.data ()))
8079             /* This shouldn't happen - we adjusted in_g_packet above.  */
8080             internal_error (__FILE__, __LINE__,
8081                             _("unexpected end of 'g' packet reply"));
8082           else if (rs->buf[r->offset * 2] == 'x')
8083             {
8084               gdb_assert (r->offset * 2 < strlen (rs->buf.data ()));
8085               /* The register isn't available, mark it as such (at
8086                  the same time setting the value to zero).  */
8087               regcache->raw_supply (r->regnum, NULL);
8088             }
8089           else
8090             regcache->raw_supply (r->regnum, regs + r->offset);
8091         }
8092     }
8093 }
8094
8095 void
8096 remote_target::fetch_registers_using_g (struct regcache *regcache)
8097 {
8098   send_g_packet ();
8099   process_g_packet (regcache);
8100 }
8101
8102 /* Make the remote selected traceframe match GDB's selected
8103    traceframe.  */
8104
8105 void
8106 remote_target::set_remote_traceframe ()
8107 {
8108   int newnum;
8109   struct remote_state *rs = get_remote_state ();
8110
8111   if (rs->remote_traceframe_number == get_traceframe_number ())
8112     return;
8113
8114   /* Avoid recursion, remote_trace_find calls us again.  */
8115   rs->remote_traceframe_number = get_traceframe_number ();
8116
8117   newnum = target_trace_find (tfind_number,
8118                               get_traceframe_number (), 0, 0, NULL);
8119
8120   /* Should not happen.  If it does, all bets are off.  */
8121   if (newnum != get_traceframe_number ())
8122     warning (_("could not set remote traceframe"));
8123 }
8124
8125 void
8126 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8127 {
8128   struct gdbarch *gdbarch = regcache->arch ();
8129   struct remote_state *rs = get_remote_state ();
8130   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8131   int i;
8132
8133   set_remote_traceframe ();
8134   set_general_thread (regcache->ptid ());
8135
8136   if (regnum >= 0)
8137     {
8138       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8139
8140       gdb_assert (reg != NULL);
8141
8142       /* If this register might be in the 'g' packet, try that first -
8143          we are likely to read more than one register.  If this is the
8144          first 'g' packet, we might be overly optimistic about its
8145          contents, so fall back to 'p'.  */
8146       if (reg->in_g_packet)
8147         {
8148           fetch_registers_using_g (regcache);
8149           if (reg->in_g_packet)
8150             return;
8151         }
8152
8153       if (fetch_register_using_p (regcache, reg))
8154         return;
8155
8156       /* This register is not available.  */
8157       regcache->raw_supply (reg->regnum, NULL);
8158
8159       return;
8160     }
8161
8162   fetch_registers_using_g (regcache);
8163
8164   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8165     if (!rsa->regs[i].in_g_packet)
8166       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8167         {
8168           /* This register is not available.  */
8169           regcache->raw_supply (i, NULL);
8170         }
8171 }
8172
8173 /* Prepare to store registers.  Since we may send them all (using a
8174    'G' request), we have to read out the ones we don't want to change
8175    first.  */
8176
8177 void
8178 remote_target::prepare_to_store (struct regcache *regcache)
8179 {
8180   struct remote_state *rs = get_remote_state ();
8181   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8182   int i;
8183
8184   /* Make sure the entire registers array is valid.  */
8185   switch (packet_support (PACKET_P))
8186     {
8187     case PACKET_DISABLE:
8188     case PACKET_SUPPORT_UNKNOWN:
8189       /* Make sure all the necessary registers are cached.  */
8190       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8191         if (rsa->regs[i].in_g_packet)
8192           regcache->raw_update (rsa->regs[i].regnum);
8193       break;
8194     case PACKET_ENABLE:
8195       break;
8196     }
8197 }
8198
8199 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8200    packet was not recognized.  */
8201
8202 int
8203 remote_target::store_register_using_P (const struct regcache *regcache,
8204                                        packet_reg *reg)
8205 {
8206   struct gdbarch *gdbarch = regcache->arch ();
8207   struct remote_state *rs = get_remote_state ();
8208   /* Try storing a single register.  */
8209   char *buf = rs->buf.data ();
8210   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8211   char *p;
8212
8213   if (packet_support (PACKET_P) == PACKET_DISABLE)
8214     return 0;
8215
8216   if (reg->pnum == -1)
8217     return 0;
8218
8219   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8220   p = buf + strlen (buf);
8221   regcache->raw_collect (reg->regnum, regp);
8222   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8223   putpkt (rs->buf);
8224   getpkt (&rs->buf, 0);
8225
8226   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8227     {
8228     case PACKET_OK:
8229       return 1;
8230     case PACKET_ERROR:
8231       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8232              gdbarch_register_name (gdbarch, reg->regnum), rs->buf.data ());
8233     case PACKET_UNKNOWN:
8234       return 0;
8235     default:
8236       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8237     }
8238 }
8239
8240 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8241    contents of the register cache buffer.  FIXME: ignores errors.  */
8242
8243 void
8244 remote_target::store_registers_using_G (const struct regcache *regcache)
8245 {
8246   struct remote_state *rs = get_remote_state ();
8247   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8248   gdb_byte *regs;
8249   char *p;
8250
8251   /* Extract all the registers in the regcache copying them into a
8252      local buffer.  */
8253   {
8254     int i;
8255
8256     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8257     memset (regs, 0, rsa->sizeof_g_packet);
8258     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8259       {
8260         struct packet_reg *r = &rsa->regs[i];
8261
8262         if (r->in_g_packet)
8263           regcache->raw_collect (r->regnum, regs + r->offset);
8264       }
8265   }
8266
8267   /* Command describes registers byte by byte,
8268      each byte encoded as two hex characters.  */
8269   p = rs->buf.data ();
8270   *p++ = 'G';
8271   bin2hex (regs, p, rsa->sizeof_g_packet);
8272   putpkt (rs->buf);
8273   getpkt (&rs->buf, 0);
8274   if (packet_check_result (rs->buf) == PACKET_ERROR)
8275     error (_("Could not write registers; remote failure reply '%s'"), 
8276            rs->buf.data ());
8277 }
8278
8279 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8280    of the register cache buffer.  FIXME: ignores errors.  */
8281
8282 void
8283 remote_target::store_registers (struct regcache *regcache, int regnum)
8284 {
8285   struct gdbarch *gdbarch = regcache->arch ();
8286   struct remote_state *rs = get_remote_state ();
8287   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8288   int i;
8289
8290   set_remote_traceframe ();
8291   set_general_thread (regcache->ptid ());
8292
8293   if (regnum >= 0)
8294     {
8295       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8296
8297       gdb_assert (reg != NULL);
8298
8299       /* Always prefer to store registers using the 'P' packet if
8300          possible; we often change only a small number of registers.
8301          Sometimes we change a larger number; we'd need help from a
8302          higher layer to know to use 'G'.  */
8303       if (store_register_using_P (regcache, reg))
8304         return;
8305
8306       /* For now, don't complain if we have no way to write the
8307          register.  GDB loses track of unavailable registers too
8308          easily.  Some day, this may be an error.  We don't have
8309          any way to read the register, either...  */
8310       if (!reg->in_g_packet)
8311         return;
8312
8313       store_registers_using_G (regcache);
8314       return;
8315     }
8316
8317   store_registers_using_G (regcache);
8318
8319   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8320     if (!rsa->regs[i].in_g_packet)
8321       if (!store_register_using_P (regcache, &rsa->regs[i]))
8322         /* See above for why we do not issue an error here.  */
8323         continue;
8324 }
8325 \f
8326
8327 /* Return the number of hex digits in num.  */
8328
8329 static int
8330 hexnumlen (ULONGEST num)
8331 {
8332   int i;
8333
8334   for (i = 0; num != 0; i++)
8335     num >>= 4;
8336
8337   return std::max (i, 1);
8338 }
8339
8340 /* Set BUF to the minimum number of hex digits representing NUM.  */
8341
8342 static int
8343 hexnumstr (char *buf, ULONGEST num)
8344 {
8345   int len = hexnumlen (num);
8346
8347   return hexnumnstr (buf, num, len);
8348 }
8349
8350
8351 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8352
8353 static int
8354 hexnumnstr (char *buf, ULONGEST num, int width)
8355 {
8356   int i;
8357
8358   buf[width] = '\0';
8359
8360   for (i = width - 1; i >= 0; i--)
8361     {
8362       buf[i] = "0123456789abcdef"[(num & 0xf)];
8363       num >>= 4;
8364     }
8365
8366   return width;
8367 }
8368
8369 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8370
8371 static CORE_ADDR
8372 remote_address_masked (CORE_ADDR addr)
8373 {
8374   unsigned int address_size = remote_address_size;
8375
8376   /* If "remoteaddresssize" was not set, default to target address size.  */
8377   if (!address_size)
8378     address_size = gdbarch_addr_bit (target_gdbarch ());
8379
8380   if (address_size > 0
8381       && address_size < (sizeof (ULONGEST) * 8))
8382     {
8383       /* Only create a mask when that mask can safely be constructed
8384          in a ULONGEST variable.  */
8385       ULONGEST mask = 1;
8386
8387       mask = (mask << address_size) - 1;
8388       addr &= mask;
8389     }
8390   return addr;
8391 }
8392
8393 /* Determine whether the remote target supports binary downloading.
8394    This is accomplished by sending a no-op memory write of zero length
8395    to the target at the specified address. It does not suffice to send
8396    the whole packet, since many stubs strip the eighth bit and
8397    subsequently compute a wrong checksum, which causes real havoc with
8398    remote_write_bytes.
8399
8400    NOTE: This can still lose if the serial line is not eight-bit
8401    clean.  In cases like this, the user should clear "remote
8402    X-packet".  */
8403
8404 void
8405 remote_target::check_binary_download (CORE_ADDR addr)
8406 {
8407   struct remote_state *rs = get_remote_state ();
8408
8409   switch (packet_support (PACKET_X))
8410     {
8411     case PACKET_DISABLE:
8412       break;
8413     case PACKET_ENABLE:
8414       break;
8415     case PACKET_SUPPORT_UNKNOWN:
8416       {
8417         char *p;
8418
8419         p = rs->buf.data ();
8420         *p++ = 'X';
8421         p += hexnumstr (p, (ULONGEST) addr);
8422         *p++ = ',';
8423         p += hexnumstr (p, (ULONGEST) 0);
8424         *p++ = ':';
8425         *p = '\0';
8426
8427         putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8428         getpkt (&rs->buf, 0);
8429
8430         if (rs->buf[0] == '\0')
8431           {
8432             if (remote_debug)
8433               fprintf_unfiltered (gdb_stdlog,
8434                                   "binary downloading NOT "
8435                                   "supported by target\n");
8436             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8437           }
8438         else
8439           {
8440             if (remote_debug)
8441               fprintf_unfiltered (gdb_stdlog,
8442                                   "binary downloading supported by target\n");
8443             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8444           }
8445         break;
8446       }
8447     }
8448 }
8449
8450 /* Helper function to resize the payload in order to try to get a good
8451    alignment.  We try to write an amount of data such that the next write will
8452    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8453
8454 static int
8455 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8456 {
8457   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8458 }
8459
8460 /* Write memory data directly to the remote machine.
8461    This does not inform the data cache; the data cache uses this.
8462    HEADER is the starting part of the packet.
8463    MEMADDR is the address in the remote memory space.
8464    MYADDR is the address of the buffer in our space.
8465    LEN_UNITS is the number of addressable units to write.
8466    UNIT_SIZE is the length in bytes of an addressable unit.
8467    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8468    should send data as binary ('X'), or hex-encoded ('M').
8469
8470    The function creates packet of the form
8471        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8472
8473    where encoding of <DATA> is terminated by PACKET_FORMAT.
8474
8475    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8476    are omitted.
8477
8478    Return the transferred status, error or OK (an
8479    'enum target_xfer_status' value).  Save the number of addressable units
8480    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8481
8482    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8483    exchange between gdb and the stub could look like (?? in place of the
8484    checksum):
8485
8486    -> $m1000,4#??
8487    <- aaaabbbbccccdddd
8488
8489    -> $M1000,3:eeeeffffeeee#??
8490    <- OK
8491
8492    -> $m1000,4#??
8493    <- eeeeffffeeeedddd  */
8494
8495 target_xfer_status
8496 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8497                                        const gdb_byte *myaddr,
8498                                        ULONGEST len_units,
8499                                        int unit_size,
8500                                        ULONGEST *xfered_len_units,
8501                                        char packet_format, int use_length)
8502 {
8503   struct remote_state *rs = get_remote_state ();
8504   char *p;
8505   char *plen = NULL;
8506   int plenlen = 0;
8507   int todo_units;
8508   int units_written;
8509   int payload_capacity_bytes;
8510   int payload_length_bytes;
8511
8512   if (packet_format != 'X' && packet_format != 'M')
8513     internal_error (__FILE__, __LINE__,
8514                     _("remote_write_bytes_aux: bad packet format"));
8515
8516   if (len_units == 0)
8517     return TARGET_XFER_EOF;
8518
8519   payload_capacity_bytes = get_memory_write_packet_size ();
8520
8521   /* The packet buffer will be large enough for the payload;
8522      get_memory_packet_size ensures this.  */
8523   rs->buf[0] = '\0';
8524
8525   /* Compute the size of the actual payload by subtracting out the
8526      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8527
8528   payload_capacity_bytes -= strlen ("$,:#NN");
8529   if (!use_length)
8530     /* The comma won't be used.  */
8531     payload_capacity_bytes += 1;
8532   payload_capacity_bytes -= strlen (header);
8533   payload_capacity_bytes -= hexnumlen (memaddr);
8534
8535   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8536
8537   strcat (rs->buf.data (), header);
8538   p = rs->buf.data () + strlen (header);
8539
8540   /* Compute a best guess of the number of bytes actually transfered.  */
8541   if (packet_format == 'X')
8542     {
8543       /* Best guess at number of bytes that will fit.  */
8544       todo_units = std::min (len_units,
8545                              (ULONGEST) payload_capacity_bytes / unit_size);
8546       if (use_length)
8547         payload_capacity_bytes -= hexnumlen (todo_units);
8548       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8549     }
8550   else
8551     {
8552       /* Number of bytes that will fit.  */
8553       todo_units
8554         = std::min (len_units,
8555                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8556       if (use_length)
8557         payload_capacity_bytes -= hexnumlen (todo_units);
8558       todo_units = std::min (todo_units,
8559                              (payload_capacity_bytes / unit_size) / 2);
8560     }
8561
8562   if (todo_units <= 0)
8563     internal_error (__FILE__, __LINE__,
8564                     _("minimum packet size too small to write data"));
8565
8566   /* If we already need another packet, then try to align the end
8567      of this packet to a useful boundary.  */
8568   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8569     todo_units = align_for_efficient_write (todo_units, memaddr);
8570
8571   /* Append "<memaddr>".  */
8572   memaddr = remote_address_masked (memaddr);
8573   p += hexnumstr (p, (ULONGEST) memaddr);
8574
8575   if (use_length)
8576     {
8577       /* Append ",".  */
8578       *p++ = ',';
8579
8580       /* Append the length and retain its location and size.  It may need to be
8581          adjusted once the packet body has been created.  */
8582       plen = p;
8583       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8584       p += plenlen;
8585     }
8586
8587   /* Append ":".  */
8588   *p++ = ':';
8589   *p = '\0';
8590
8591   /* Append the packet body.  */
8592   if (packet_format == 'X')
8593     {
8594       /* Binary mode.  Send target system values byte by byte, in
8595          increasing byte addresses.  Only escape certain critical
8596          characters.  */
8597       payload_length_bytes =
8598           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8599                                 &units_written, payload_capacity_bytes);
8600
8601       /* If not all TODO units fit, then we'll need another packet.  Make
8602          a second try to keep the end of the packet aligned.  Don't do
8603          this if the packet is tiny.  */
8604       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8605         {
8606           int new_todo_units;
8607
8608           new_todo_units = align_for_efficient_write (units_written, memaddr);
8609
8610           if (new_todo_units != units_written)
8611             payload_length_bytes =
8612                 remote_escape_output (myaddr, new_todo_units, unit_size,
8613                                       (gdb_byte *) p, &units_written,
8614                                       payload_capacity_bytes);
8615         }
8616
8617       p += payload_length_bytes;
8618       if (use_length && units_written < todo_units)
8619         {
8620           /* Escape chars have filled up the buffer prematurely,
8621              and we have actually sent fewer units than planned.
8622              Fix-up the length field of the packet.  Use the same
8623              number of characters as before.  */
8624           plen += hexnumnstr (plen, (ULONGEST) units_written,
8625                               plenlen);
8626           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8627         }
8628     }
8629   else
8630     {
8631       /* Normal mode: Send target system values byte by byte, in
8632          increasing byte addresses.  Each byte is encoded as a two hex
8633          value.  */
8634       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8635       units_written = todo_units;
8636     }
8637
8638   putpkt_binary (rs->buf.data (), (int) (p - rs->buf.data ()));
8639   getpkt (&rs->buf, 0);
8640
8641   if (rs->buf[0] == 'E')
8642     return TARGET_XFER_E_IO;
8643
8644   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8645      send fewer units than we'd planned.  */
8646   *xfered_len_units = (ULONGEST) units_written;
8647   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8648 }
8649
8650 /* Write memory data directly to the remote machine.
8651    This does not inform the data cache; the data cache uses this.
8652    MEMADDR is the address in the remote memory space.
8653    MYADDR is the address of the buffer in our space.
8654    LEN is the number of bytes.
8655
8656    Return the transferred status, error or OK (an
8657    'enum target_xfer_status' value).  Save the number of bytes
8658    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8659
8660 target_xfer_status
8661 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8662                                    ULONGEST len, int unit_size,
8663                                    ULONGEST *xfered_len)
8664 {
8665   const char *packet_format = NULL;
8666
8667   /* Check whether the target supports binary download.  */
8668   check_binary_download (memaddr);
8669
8670   switch (packet_support (PACKET_X))
8671     {
8672     case PACKET_ENABLE:
8673       packet_format = "X";
8674       break;
8675     case PACKET_DISABLE:
8676       packet_format = "M";
8677       break;
8678     case PACKET_SUPPORT_UNKNOWN:
8679       internal_error (__FILE__, __LINE__,
8680                       _("remote_write_bytes: bad internal state"));
8681     default:
8682       internal_error (__FILE__, __LINE__, _("bad switch"));
8683     }
8684
8685   return remote_write_bytes_aux (packet_format,
8686                                  memaddr, myaddr, len, unit_size, xfered_len,
8687                                  packet_format[0], 1);
8688 }
8689
8690 /* Read memory data directly from the remote machine.
8691    This does not use the data cache; the data cache uses this.
8692    MEMADDR is the address in the remote memory space.
8693    MYADDR is the address of the buffer in our space.
8694    LEN_UNITS is the number of addressable memory units to read..
8695    UNIT_SIZE is the length in bytes of an addressable unit.
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_UNITS.
8700
8701    See the comment of remote_write_bytes_aux for an example of
8702    memory read/write exchange between gdb and the stub.  */
8703
8704 target_xfer_status
8705 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8706                                     ULONGEST len_units,
8707                                     int unit_size, ULONGEST *xfered_len_units)
8708 {
8709   struct remote_state *rs = get_remote_state ();
8710   int buf_size_bytes;           /* Max size of packet output buffer.  */
8711   char *p;
8712   int todo_units;
8713   int decoded_bytes;
8714
8715   buf_size_bytes = get_memory_read_packet_size ();
8716   /* The packet buffer will be large enough for the payload;
8717      get_memory_packet_size ensures this.  */
8718
8719   /* Number of units that will fit.  */
8720   todo_units = std::min (len_units,
8721                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8722
8723   /* Construct "m"<memaddr>","<len>".  */
8724   memaddr = remote_address_masked (memaddr);
8725   p = rs->buf.data ();
8726   *p++ = 'm';
8727   p += hexnumstr (p, (ULONGEST) memaddr);
8728   *p++ = ',';
8729   p += hexnumstr (p, (ULONGEST) todo_units);
8730   *p = '\0';
8731   putpkt (rs->buf);
8732   getpkt (&rs->buf, 0);
8733   if (rs->buf[0] == 'E'
8734       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8735       && rs->buf[3] == '\0')
8736     return TARGET_XFER_E_IO;
8737   /* Reply describes memory byte by byte, each byte encoded as two hex
8738      characters.  */
8739   p = rs->buf.data ();
8740   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8741   /* Return what we have.  Let higher layers handle partial reads.  */
8742   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8743   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8744 }
8745
8746 /* Using the set of read-only target sections of remote, read live
8747    read-only memory.
8748
8749    For interface/parameters/return description see target.h,
8750    to_xfer_partial.  */
8751
8752 target_xfer_status
8753 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8754                                                   ULONGEST memaddr,
8755                                                   ULONGEST len,
8756                                                   int unit_size,
8757                                                   ULONGEST *xfered_len)
8758 {
8759   struct target_section *secp;
8760   struct target_section_table *table;
8761
8762   secp = target_section_by_addr (this, memaddr);
8763   if (secp != NULL
8764       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8765                                  secp->the_bfd_section)
8766           & SEC_READONLY))
8767     {
8768       struct target_section *p;
8769       ULONGEST memend = memaddr + len;
8770
8771       table = target_get_section_table (this);
8772
8773       for (p = table->sections; p < table->sections_end; p++)
8774         {
8775           if (memaddr >= p->addr)
8776             {
8777               if (memend <= p->endaddr)
8778                 {
8779                   /* Entire transfer is within this section.  */
8780                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8781                                               xfered_len);
8782                 }
8783               else if (memaddr >= p->endaddr)
8784                 {
8785                   /* This section ends before the transfer starts.  */
8786                   continue;
8787                 }
8788               else
8789                 {
8790                   /* This section overlaps the transfer.  Just do half.  */
8791                   len = p->endaddr - memaddr;
8792                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8793                                               xfered_len);
8794                 }
8795             }
8796         }
8797     }
8798
8799   return TARGET_XFER_EOF;
8800 }
8801
8802 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8803    first if the requested memory is unavailable in traceframe.
8804    Otherwise, fall back to remote_read_bytes_1.  */
8805
8806 target_xfer_status
8807 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8808                                   gdb_byte *myaddr, ULONGEST len, int unit_size,
8809                                   ULONGEST *xfered_len)
8810 {
8811   if (len == 0)
8812     return TARGET_XFER_EOF;
8813
8814   if (get_traceframe_number () != -1)
8815     {
8816       std::vector<mem_range> available;
8817
8818       /* If we fail to get the set of available memory, then the
8819          target does not support querying traceframe info, and so we
8820          attempt reading from the traceframe anyway (assuming the
8821          target implements the old QTro packet then).  */
8822       if (traceframe_available_memory (&available, memaddr, len))
8823         {
8824           if (available.empty () || available[0].start != memaddr)
8825             {
8826               enum target_xfer_status res;
8827
8828               /* Don't read into the traceframe's available
8829                  memory.  */
8830               if (!available.empty ())
8831                 {
8832                   LONGEST oldlen = len;
8833
8834                   len = available[0].start - memaddr;
8835                   gdb_assert (len <= oldlen);
8836                 }
8837
8838               /* This goes through the topmost target again.  */
8839               res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8840                                                        len, unit_size, xfered_len);
8841               if (res == TARGET_XFER_OK)
8842                 return TARGET_XFER_OK;
8843               else
8844                 {
8845                   /* No use trying further, we know some memory starting
8846                      at MEMADDR isn't available.  */
8847                   *xfered_len = len;
8848                   return (*xfered_len != 0) ?
8849                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8850                 }
8851             }
8852
8853           /* Don't try to read more than how much is available, in
8854              case the target implements the deprecated QTro packet to
8855              cater for older GDBs (the target's knowledge of read-only
8856              sections may be outdated by now).  */
8857           len = available[0].length;
8858         }
8859     }
8860
8861   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
8862 }
8863
8864 \f
8865
8866 /* Sends a packet with content determined by the printf format string
8867    FORMAT and the remaining arguments, then gets the reply.  Returns
8868    whether the packet was a success, a failure, or unknown.  */
8869
8870 packet_result
8871 remote_target::remote_send_printf (const char *format, ...)
8872 {
8873   struct remote_state *rs = get_remote_state ();
8874   int max_size = get_remote_packet_size ();
8875   va_list ap;
8876
8877   va_start (ap, format);
8878
8879   rs->buf[0] = '\0';
8880   int size = vsnprintf (rs->buf.data (), max_size, format, ap);
8881
8882   va_end (ap);
8883
8884   if (size >= max_size)
8885     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
8886
8887   if (putpkt (rs->buf) < 0)
8888     error (_("Communication problem with target."));
8889
8890   rs->buf[0] = '\0';
8891   getpkt (&rs->buf, 0);
8892
8893   return packet_check_result (rs->buf);
8894 }
8895
8896 /* Flash writing can take quite some time.  We'll set
8897    effectively infinite timeout for flash operations.
8898    In future, we'll need to decide on a better approach.  */
8899 static const int remote_flash_timeout = 1000;
8900
8901 void
8902 remote_target::flash_erase (ULONGEST address, LONGEST length)
8903 {
8904   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
8905   enum packet_result ret;
8906   scoped_restore restore_timeout
8907     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8908
8909   ret = remote_send_printf ("vFlashErase:%s,%s",
8910                             phex (address, addr_size),
8911                             phex (length, 4));
8912   switch (ret)
8913     {
8914     case PACKET_UNKNOWN:
8915       error (_("Remote target does not support flash erase"));
8916     case PACKET_ERROR:
8917       error (_("Error erasing flash with vFlashErase packet"));
8918     default:
8919       break;
8920     }
8921 }
8922
8923 target_xfer_status
8924 remote_target::remote_flash_write (ULONGEST address,
8925                                    ULONGEST length, ULONGEST *xfered_len,
8926                                    const gdb_byte *data)
8927 {
8928   scoped_restore restore_timeout
8929     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8930   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
8931                                  xfered_len,'X', 0);
8932 }
8933
8934 void
8935 remote_target::flash_done ()
8936 {
8937   int ret;
8938
8939   scoped_restore restore_timeout
8940     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
8941
8942   ret = remote_send_printf ("vFlashDone");
8943
8944   switch (ret)
8945     {
8946     case PACKET_UNKNOWN:
8947       error (_("Remote target does not support vFlashDone"));
8948     case PACKET_ERROR:
8949       error (_("Error finishing flash operation"));
8950     default:
8951       break;
8952     }
8953 }
8954
8955 void
8956 remote_target::files_info ()
8957 {
8958   puts_filtered ("Debugging a target over a serial line.\n");
8959 }
8960 \f
8961 /* Stuff for dealing with the packets which are part of this protocol.
8962    See comment at top of file for details.  */
8963
8964 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
8965    error to higher layers.  Called when a serial error is detected.
8966    The exception message is STRING, followed by a colon and a blank,
8967    the system error message for errno at function entry and final dot
8968    for output compatibility with throw_perror_with_name.  */
8969
8970 static void
8971 unpush_and_perror (const char *string)
8972 {
8973   int saved_errno = errno;
8974
8975   remote_unpush_target ();
8976   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
8977                safe_strerror (saved_errno));
8978 }
8979
8980 /* Read a single character from the remote end.  The current quit
8981    handler is overridden to avoid quitting in the middle of packet
8982    sequence, as that would break communication with the remote server.
8983    See remote_serial_quit_handler for more detail.  */
8984
8985 int
8986 remote_target::readchar (int timeout)
8987 {
8988   int ch;
8989   struct remote_state *rs = get_remote_state ();
8990
8991   {
8992     scoped_restore restore_quit_target
8993       = make_scoped_restore (&curr_quit_handler_target, this);
8994     scoped_restore restore_quit
8995       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
8996
8997     rs->got_ctrlc_during_io = 0;
8998
8999     ch = serial_readchar (rs->remote_desc, timeout);
9000
9001     if (rs->got_ctrlc_during_io)
9002       set_quit_flag ();
9003   }
9004
9005   if (ch >= 0)
9006     return ch;
9007
9008   switch ((enum serial_rc) ch)
9009     {
9010     case SERIAL_EOF:
9011       remote_unpush_target ();
9012       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9013       /* no return */
9014     case SERIAL_ERROR:
9015       unpush_and_perror (_("Remote communication error.  "
9016                            "Target disconnected."));
9017       /* no return */
9018     case SERIAL_TIMEOUT:
9019       break;
9020     }
9021   return ch;
9022 }
9023
9024 /* Wrapper for serial_write that closes the target and throws if
9025    writing fails.  The current quit handler is overridden to avoid
9026    quitting in the middle of packet sequence, as that would break
9027    communication with the remote server.  See
9028    remote_serial_quit_handler for more detail.  */
9029
9030 void
9031 remote_target::remote_serial_write (const char *str, int len)
9032 {
9033   struct remote_state *rs = get_remote_state ();
9034
9035   scoped_restore restore_quit_target
9036     = make_scoped_restore (&curr_quit_handler_target, this);
9037   scoped_restore restore_quit
9038     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9039
9040   rs->got_ctrlc_during_io = 0;
9041
9042   if (serial_write (rs->remote_desc, str, len))
9043     {
9044       unpush_and_perror (_("Remote communication error.  "
9045                            "Target disconnected."));
9046     }
9047
9048   if (rs->got_ctrlc_during_io)
9049     set_quit_flag ();
9050 }
9051
9052 /* Return a string representing an escaped version of BUF, of len N.
9053    E.g. \n is converted to \\n, \t to \\t, etc.  */
9054
9055 static std::string
9056 escape_buffer (const char *buf, int n)
9057 {
9058   string_file stb;
9059
9060   stb.putstrn (buf, n, '\\');
9061   return std::move (stb.string ());
9062 }
9063
9064 /* Display a null-terminated packet on stdout, for debugging, using C
9065    string notation.  */
9066
9067 static void
9068 print_packet (const char *buf)
9069 {
9070   puts_filtered ("\"");
9071   fputstr_filtered (buf, '"', gdb_stdout);
9072   puts_filtered ("\"");
9073 }
9074
9075 int
9076 remote_target::putpkt (const char *buf)
9077 {
9078   return putpkt_binary (buf, strlen (buf));
9079 }
9080
9081 /* Wrapper around remote_target::putpkt to avoid exporting
9082    remote_target.  */
9083
9084 int
9085 putpkt (remote_target *remote, const char *buf)
9086 {
9087   return remote->putpkt (buf);
9088 }
9089
9090 /* Send a packet to the remote machine, with error checking.  The data
9091    of the packet is in BUF.  The string in BUF can be at most
9092    get_remote_packet_size () - 5 to account for the $, # and checksum,
9093    and for a possible /0 if we are debugging (remote_debug) and want
9094    to print the sent packet as a string.  */
9095
9096 int
9097 remote_target::putpkt_binary (const char *buf, int cnt)
9098 {
9099   struct remote_state *rs = get_remote_state ();
9100   int i;
9101   unsigned char csum = 0;
9102   gdb::def_vector<char> data (cnt + 6);
9103   char *buf2 = data.data ();
9104
9105   int ch;
9106   int tcount = 0;
9107   char *p;
9108
9109   /* Catch cases like trying to read memory or listing threads while
9110      we're waiting for a stop reply.  The remote server wouldn't be
9111      ready to handle this request, so we'd hang and timeout.  We don't
9112      have to worry about this in synchronous mode, because in that
9113      case it's not possible to issue a command while the target is
9114      running.  This is not a problem in non-stop mode, because in that
9115      case, the stub is always ready to process serial input.  */
9116   if (!target_is_non_stop_p ()
9117       && target_is_async_p ()
9118       && rs->waiting_for_stop_reply)
9119     {
9120       error (_("Cannot execute this command while the target is running.\n"
9121                "Use the \"interrupt\" command to stop the target\n"
9122                "and then try again."));
9123     }
9124
9125   /* We're sending out a new packet.  Make sure we don't look at a
9126      stale cached response.  */
9127   rs->cached_wait_status = 0;
9128
9129   /* Copy the packet into buffer BUF2, encapsulating it
9130      and giving it a checksum.  */
9131
9132   p = buf2;
9133   *p++ = '$';
9134
9135   for (i = 0; i < cnt; i++)
9136     {
9137       csum += buf[i];
9138       *p++ = buf[i];
9139     }
9140   *p++ = '#';
9141   *p++ = tohex ((csum >> 4) & 0xf);
9142   *p++ = tohex (csum & 0xf);
9143
9144   /* Send it over and over until we get a positive ack.  */
9145
9146   while (1)
9147     {
9148       int started_error_output = 0;
9149
9150       if (remote_debug)
9151         {
9152           *p = '\0';
9153
9154           int len = (int) (p - buf2);
9155
9156           std::string str
9157             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9158
9159           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9160
9161           if (len > REMOTE_DEBUG_MAX_CHAR)
9162             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9163                                 len - REMOTE_DEBUG_MAX_CHAR);
9164
9165           fprintf_unfiltered (gdb_stdlog, "...");
9166
9167           gdb_flush (gdb_stdlog);
9168         }
9169       remote_serial_write (buf2, p - buf2);
9170
9171       /* If this is a no acks version of the remote protocol, send the
9172          packet and move on.  */
9173       if (rs->noack_mode)
9174         break;
9175
9176       /* Read until either a timeout occurs (-2) or '+' is read.
9177          Handle any notification that arrives in the mean time.  */
9178       while (1)
9179         {
9180           ch = readchar (remote_timeout);
9181
9182           if (remote_debug)
9183             {
9184               switch (ch)
9185                 {
9186                 case '+':
9187                 case '-':
9188                 case SERIAL_TIMEOUT:
9189                 case '$':
9190                 case '%':
9191                   if (started_error_output)
9192                     {
9193                       putchar_unfiltered ('\n');
9194                       started_error_output = 0;
9195                     }
9196                 }
9197             }
9198
9199           switch (ch)
9200             {
9201             case '+':
9202               if (remote_debug)
9203                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9204               return 1;
9205             case '-':
9206               if (remote_debug)
9207                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9208               /* FALLTHROUGH */
9209             case SERIAL_TIMEOUT:
9210               tcount++;
9211               if (tcount > 3)
9212                 return 0;
9213               break;            /* Retransmit buffer.  */
9214             case '$':
9215               {
9216                 if (remote_debug)
9217                   fprintf_unfiltered (gdb_stdlog,
9218                                       "Packet instead of Ack, ignoring it\n");
9219                 /* It's probably an old response sent because an ACK
9220                    was lost.  Gobble up the packet and ack it so it
9221                    doesn't get retransmitted when we resend this
9222                    packet.  */
9223                 skip_frame ();
9224                 remote_serial_write ("+", 1);
9225                 continue;       /* Now, go look for +.  */
9226               }
9227
9228             case '%':
9229               {
9230                 int val;
9231
9232                 /* If we got a notification, handle it, and go back to looking
9233                    for an ack.  */
9234                 /* We've found the start of a notification.  Now
9235                    collect the data.  */
9236                 val = read_frame (&rs->buf);
9237                 if (val >= 0)
9238                   {
9239                     if (remote_debug)
9240                       {
9241                         std::string str = escape_buffer (rs->buf.data (), val);
9242
9243                         fprintf_unfiltered (gdb_stdlog,
9244                                             "  Notification received: %s\n",
9245                                             str.c_str ());
9246                       }
9247                     handle_notification (rs->notif_state, rs->buf.data ());
9248                     /* We're in sync now, rewait for the ack.  */
9249                     tcount = 0;
9250                   }
9251                 else
9252                   {
9253                     if (remote_debug)
9254                       {
9255                         if (!started_error_output)
9256                           {
9257                             started_error_output = 1;
9258                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9259                           }
9260                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9261                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf.data ());
9262                       }
9263                   }
9264                 continue;
9265               }
9266               /* fall-through */
9267             default:
9268               if (remote_debug)
9269                 {
9270                   if (!started_error_output)
9271                     {
9272                       started_error_output = 1;
9273                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9274                     }
9275                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9276                 }
9277               continue;
9278             }
9279           break;                /* Here to retransmit.  */
9280         }
9281
9282 #if 0
9283       /* This is wrong.  If doing a long backtrace, the user should be
9284          able to get out next time we call QUIT, without anything as
9285          violent as interrupt_query.  If we want to provide a way out of
9286          here without getting to the next QUIT, it should be based on
9287          hitting ^C twice as in remote_wait.  */
9288       if (quit_flag)
9289         {
9290           quit_flag = 0;
9291           interrupt_query ();
9292         }
9293 #endif
9294     }
9295
9296   return 0;
9297 }
9298
9299 /* Come here after finding the start of a frame when we expected an
9300    ack.  Do our best to discard the rest of this packet.  */
9301
9302 void
9303 remote_target::skip_frame ()
9304 {
9305   int c;
9306
9307   while (1)
9308     {
9309       c = readchar (remote_timeout);
9310       switch (c)
9311         {
9312         case SERIAL_TIMEOUT:
9313           /* Nothing we can do.  */
9314           return;
9315         case '#':
9316           /* Discard the two bytes of checksum and stop.  */
9317           c = readchar (remote_timeout);
9318           if (c >= 0)
9319             c = readchar (remote_timeout);
9320
9321           return;
9322         case '*':               /* Run length encoding.  */
9323           /* Discard the repeat count.  */
9324           c = readchar (remote_timeout);
9325           if (c < 0)
9326             return;
9327           break;
9328         default:
9329           /* A regular character.  */
9330           break;
9331         }
9332     }
9333 }
9334
9335 /* Come here after finding the start of the frame.  Collect the rest
9336    into *BUF, verifying the checksum, length, and handling run-length
9337    compression.  NUL terminate the buffer.  If there is not enough room,
9338    expand *BUF.
9339
9340    Returns -1 on error, number of characters in buffer (ignoring the
9341    trailing NULL) on success. (could be extended to return one of the
9342    SERIAL status indications).  */
9343
9344 long
9345 remote_target::read_frame (gdb::char_vector *buf_p)
9346 {
9347   unsigned char csum;
9348   long bc;
9349   int c;
9350   char *buf = buf_p->data ();
9351   struct remote_state *rs = get_remote_state ();
9352
9353   csum = 0;
9354   bc = 0;
9355
9356   while (1)
9357     {
9358       c = readchar (remote_timeout);
9359       switch (c)
9360         {
9361         case SERIAL_TIMEOUT:
9362           if (remote_debug)
9363             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9364           return -1;
9365         case '$':
9366           if (remote_debug)
9367             fputs_filtered ("Saw new packet start in middle of old one\n",
9368                             gdb_stdlog);
9369           return -1;            /* Start a new packet, count retries.  */
9370         case '#':
9371           {
9372             unsigned char pktcsum;
9373             int check_0 = 0;
9374             int check_1 = 0;
9375
9376             buf[bc] = '\0';
9377
9378             check_0 = readchar (remote_timeout);
9379             if (check_0 >= 0)
9380               check_1 = readchar (remote_timeout);
9381
9382             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9383               {
9384                 if (remote_debug)
9385                   fputs_filtered ("Timeout in checksum, retrying\n",
9386                                   gdb_stdlog);
9387                 return -1;
9388               }
9389             else if (check_0 < 0 || check_1 < 0)
9390               {
9391                 if (remote_debug)
9392                   fputs_filtered ("Communication error in checksum\n",
9393                                   gdb_stdlog);
9394                 return -1;
9395               }
9396
9397             /* Don't recompute the checksum; with no ack packets we
9398                don't have any way to indicate a packet retransmission
9399                is necessary.  */
9400             if (rs->noack_mode)
9401               return bc;
9402
9403             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9404             if (csum == pktcsum)
9405               return bc;
9406
9407             if (remote_debug)
9408               {
9409                 std::string str = escape_buffer (buf, bc);
9410
9411                 fprintf_unfiltered (gdb_stdlog,
9412                                     "Bad checksum, sentsum=0x%x, "
9413                                     "csum=0x%x, buf=%s\n",
9414                                     pktcsum, csum, str.c_str ());
9415               }
9416             /* Number of characters in buffer ignoring trailing
9417                NULL.  */
9418             return -1;
9419           }
9420         case '*':               /* Run length encoding.  */
9421           {
9422             int repeat;
9423
9424             csum += c;
9425             c = readchar (remote_timeout);
9426             csum += c;
9427             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9428
9429             /* The character before ``*'' is repeated.  */
9430
9431             if (repeat > 0 && repeat <= 255 && bc > 0)
9432               {
9433                 if (bc + repeat - 1 >= buf_p->size () - 1)
9434                   {
9435                     /* Make some more room in the buffer.  */
9436                     buf_p->resize (buf_p->size () + repeat);
9437                     buf = buf_p->data ();
9438                   }
9439
9440                 memset (&buf[bc], buf[bc - 1], repeat);
9441                 bc += repeat;
9442                 continue;
9443               }
9444
9445             buf[bc] = '\0';
9446             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9447             return -1;
9448           }
9449         default:
9450           if (bc >= buf_p->size () - 1)
9451             {
9452               /* Make some more room in the buffer.  */
9453               buf_p->resize (buf_p->size () * 2);
9454               buf = buf_p->data ();
9455             }
9456
9457           buf[bc++] = c;
9458           csum += c;
9459           continue;
9460         }
9461     }
9462 }
9463
9464 /* Set this to the maximum number of seconds to wait instead of waiting forever
9465    in target_wait().  If this timer times out, then it generates an error and
9466    the command is aborted.  This replaces most of the need for timeouts in the
9467    GDB test suite, and makes it possible to distinguish between a hung target
9468    and one with slow communications.  */
9469
9470 static int watchdog = 0;
9471 static void
9472 show_watchdog (struct ui_file *file, int from_tty,
9473                struct cmd_list_element *c, const char *value)
9474 {
9475   fprintf_filtered (file, _("Watchdog timer is %s.\n"), value);
9476 }
9477
9478 /* Read a packet from the remote machine, with error checking, and
9479    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
9480    FOREVER, wait forever rather than timing out; this is used (in
9481    synchronous mode) to wait for a target that is is executing user
9482    code to stop.  */
9483 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9484    don't have to change all the calls to getpkt to deal with the
9485    return value, because at the moment I don't know what the right
9486    thing to do it for those.  */
9487
9488 void
9489 remote_target::getpkt (gdb::char_vector *buf, int forever)
9490 {
9491   getpkt_sane (buf, forever);
9492 }
9493
9494
9495 /* Read a packet from the remote machine, with error checking, and
9496    store it in *BUF.  Resize *BUF if necessary to hold the result.  If
9497    FOREVER, wait forever rather than timing out; this is used (in
9498    synchronous mode) to wait for a target that is is executing user
9499    code to stop.  If FOREVER == 0, this function is allowed to time
9500    out gracefully and return an indication of this to the caller.
9501    Otherwise return the number of bytes read.  If EXPECTING_NOTIF,
9502    consider receiving a notification enough reason to return to the
9503    caller.  *IS_NOTIF is an output boolean that indicates whether *BUF
9504    holds a notification or not (a regular packet).  */
9505
9506 int
9507 remote_target::getpkt_or_notif_sane_1 (gdb::char_vector *buf,
9508                                        int forever, int expecting_notif,
9509                                        int *is_notif)
9510 {
9511   struct remote_state *rs = get_remote_state ();
9512   int c;
9513   int tries;
9514   int timeout;
9515   int val = -1;
9516
9517   /* We're reading a new response.  Make sure we don't look at a
9518      previously cached response.  */
9519   rs->cached_wait_status = 0;
9520
9521   strcpy (buf->data (), "timeout");
9522
9523   if (forever)
9524     timeout = watchdog > 0 ? watchdog : -1;
9525   else if (expecting_notif)
9526     timeout = 0; /* There should already be a char in the buffer.  If
9527                     not, bail out.  */
9528   else
9529     timeout = remote_timeout;
9530
9531 #define MAX_TRIES 3
9532
9533   /* Process any number of notifications, and then return when
9534      we get a packet.  */
9535   for (;;)
9536     {
9537       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9538          times.  */
9539       for (tries = 1; tries <= MAX_TRIES; tries++)
9540         {
9541           /* This can loop forever if the remote side sends us
9542              characters continuously, but if it pauses, we'll get
9543              SERIAL_TIMEOUT from readchar because of timeout.  Then
9544              we'll count that as a retry.
9545
9546              Note that even when forever is set, we will only wait
9547              forever prior to the start of a packet.  After that, we
9548              expect characters to arrive at a brisk pace.  They should
9549              show up within remote_timeout intervals.  */
9550           do
9551             c = readchar (timeout);
9552           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9553
9554           if (c == SERIAL_TIMEOUT)
9555             {
9556               if (expecting_notif)
9557                 return -1; /* Don't complain, it's normal to not get
9558                               anything in this case.  */
9559
9560               if (forever)      /* Watchdog went off?  Kill the target.  */
9561                 {
9562                   remote_unpush_target ();
9563                   throw_error (TARGET_CLOSE_ERROR,
9564                                _("Watchdog timeout has expired.  "
9565                                  "Target detached."));
9566                 }
9567               if (remote_debug)
9568                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9569             }
9570           else
9571             {
9572               /* We've found the start of a packet or notification.
9573                  Now collect the data.  */
9574               val = read_frame (buf);
9575               if (val >= 0)
9576                 break;
9577             }
9578
9579           remote_serial_write ("-", 1);
9580         }
9581
9582       if (tries > MAX_TRIES)
9583         {
9584           /* We have tried hard enough, and just can't receive the
9585              packet/notification.  Give up.  */
9586           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9587
9588           /* Skip the ack char if we're in no-ack mode.  */
9589           if (!rs->noack_mode)
9590             remote_serial_write ("+", 1);
9591           return -1;
9592         }
9593
9594       /* If we got an ordinary packet, return that to our caller.  */
9595       if (c == '$')
9596         {
9597           if (remote_debug)
9598             {
9599               std::string str
9600                 = escape_buffer (buf->data (),
9601                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9602
9603               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9604                                   str.c_str ());
9605
9606               if (val > REMOTE_DEBUG_MAX_CHAR)
9607                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9608                                     val - REMOTE_DEBUG_MAX_CHAR);
9609
9610               fprintf_unfiltered (gdb_stdlog, "\n");
9611             }
9612
9613           /* Skip the ack char if we're in no-ack mode.  */
9614           if (!rs->noack_mode)
9615             remote_serial_write ("+", 1);
9616           if (is_notif != NULL)
9617             *is_notif = 0;
9618           return val;
9619         }
9620
9621        /* If we got a notification, handle it, and go back to looking
9622          for a packet.  */
9623       else
9624         {
9625           gdb_assert (c == '%');
9626
9627           if (remote_debug)
9628             {
9629               std::string str = escape_buffer (buf->data (), val);
9630
9631               fprintf_unfiltered (gdb_stdlog,
9632                                   "  Notification received: %s\n",
9633                                   str.c_str ());
9634             }
9635           if (is_notif != NULL)
9636             *is_notif = 1;
9637
9638           handle_notification (rs->notif_state, buf->data ());
9639
9640           /* Notifications require no acknowledgement.  */
9641
9642           if (expecting_notif)
9643             return val;
9644         }
9645     }
9646 }
9647
9648 int
9649 remote_target::getpkt_sane (gdb::char_vector *buf, int forever)
9650 {
9651   return getpkt_or_notif_sane_1 (buf, forever, 0, NULL);
9652 }
9653
9654 int
9655 remote_target::getpkt_or_notif_sane (gdb::char_vector *buf, int forever,
9656                                      int *is_notif)
9657 {
9658   return getpkt_or_notif_sane_1 (buf, forever, 1, is_notif);
9659 }
9660
9661 /* Kill any new fork children of process PID that haven't been
9662    processed by follow_fork.  */
9663
9664 void
9665 remote_target::kill_new_fork_children (int pid)
9666 {
9667   remote_state *rs = get_remote_state ();
9668   struct notif_client *notif = &notif_client_stop;
9669
9670   /* Kill the fork child threads of any threads in process PID
9671      that are stopped at a fork event.  */
9672   for (thread_info *thread : all_non_exited_threads ())
9673     {
9674       struct target_waitstatus *ws = &thread->pending_follow;
9675
9676       if (is_pending_fork_parent (ws, pid, thread->ptid))
9677         {
9678           int child_pid = ws->value.related_pid.pid ();
9679           int res;
9680
9681           res = remote_vkill (child_pid);
9682           if (res != 0)
9683             error (_("Can't kill fork child process %d"), child_pid);
9684         }
9685     }
9686
9687   /* Check for any pending fork events (not reported or processed yet)
9688      in process PID and kill those fork child threads as well.  */
9689   remote_notif_get_pending_events (notif);
9690   for (auto &event : rs->stop_reply_queue)
9691     if (is_pending_fork_parent (&event->ws, pid, event->ptid))
9692       {
9693         int child_pid = event->ws.value.related_pid.pid ();
9694         int res;
9695
9696         res = remote_vkill (child_pid);
9697         if (res != 0)
9698           error (_("Can't kill fork child process %d"), child_pid);
9699       }
9700 }
9701
9702 \f
9703 /* Target hook to kill the current inferior.  */
9704
9705 void
9706 remote_target::kill ()
9707 {
9708   int res = -1;
9709   int pid = inferior_ptid.pid ();
9710   struct remote_state *rs = get_remote_state ();
9711
9712   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9713     {
9714       /* If we're stopped while forking and we haven't followed yet,
9715          kill the child task.  We need to do this before killing the
9716          parent task because if this is a vfork then the parent will
9717          be sleeping.  */
9718       kill_new_fork_children (pid);
9719
9720       res = remote_vkill (pid);
9721       if (res == 0)
9722         {
9723           target_mourn_inferior (inferior_ptid);
9724           return;
9725         }
9726     }
9727
9728   /* If we are in 'target remote' mode and we are killing the only
9729      inferior, then we will tell gdbserver to exit and unpush the
9730      target.  */
9731   if (res == -1 && !remote_multi_process_p (rs)
9732       && number_of_live_inferiors () == 1)
9733     {
9734       remote_kill_k ();
9735
9736       /* We've killed the remote end, we get to mourn it.  If we are
9737          not in extended mode, mourning the inferior also unpushes
9738          remote_ops from the target stack, which closes the remote
9739          connection.  */
9740       target_mourn_inferior (inferior_ptid);
9741
9742       return;
9743     }
9744
9745   error (_("Can't kill process"));
9746 }
9747
9748 /* Send a kill request to the target using the 'vKill' packet.  */
9749
9750 int
9751 remote_target::remote_vkill (int pid)
9752 {
9753   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9754     return -1;
9755
9756   remote_state *rs = get_remote_state ();
9757
9758   /* Tell the remote target to detach.  */
9759   xsnprintf (rs->buf.data (), get_remote_packet_size (), "vKill;%x", pid);
9760   putpkt (rs->buf);
9761   getpkt (&rs->buf, 0);
9762
9763   switch (packet_ok (rs->buf,
9764                      &remote_protocol_packets[PACKET_vKill]))
9765     {
9766     case PACKET_OK:
9767       return 0;
9768     case PACKET_ERROR:
9769       return 1;
9770     case PACKET_UNKNOWN:
9771       return -1;
9772     default:
9773       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9774     }
9775 }
9776
9777 /* Send a kill request to the target using the 'k' packet.  */
9778
9779 void
9780 remote_target::remote_kill_k ()
9781 {
9782   /* Catch errors so the user can quit from gdb even when we
9783      aren't on speaking terms with the remote system.  */
9784   try
9785     {
9786       putpkt ("k");
9787     }
9788   catch (const gdb_exception_error &ex)
9789     {
9790       if (ex.error == TARGET_CLOSE_ERROR)
9791         {
9792           /* If we got an (EOF) error that caused the target
9793              to go away, then we're done, that's what we wanted.
9794              "k" is susceptible to cause a premature EOF, given
9795              that the remote server isn't actually required to
9796              reply to "k", and it can happen that it doesn't
9797              even get to reply ACK to the "k".  */
9798           return;
9799         }
9800
9801       /* Otherwise, something went wrong.  We didn't actually kill
9802          the target.  Just propagate the exception, and let the
9803          user or higher layers decide what to do.  */
9804       throw;
9805     }
9806 }
9807
9808 void
9809 remote_target::mourn_inferior ()
9810 {
9811   struct remote_state *rs = get_remote_state ();
9812
9813   /* We're no longer interested in notification events of an inferior
9814      that exited or was killed/detached.  */
9815   discard_pending_stop_replies (current_inferior ());
9816
9817   /* In 'target remote' mode with one inferior, we close the connection.  */
9818   if (!rs->extended && number_of_live_inferiors () <= 1)
9819     {
9820       unpush_target (this);
9821
9822       /* remote_close takes care of doing most of the clean up.  */
9823       generic_mourn_inferior ();
9824       return;
9825     }
9826
9827   /* In case we got here due to an error, but we're going to stay
9828      connected.  */
9829   rs->waiting_for_stop_reply = 0;
9830
9831   /* If the current general thread belonged to the process we just
9832      detached from or has exited, the remote side current general
9833      thread becomes undefined.  Considering a case like this:
9834
9835      - We just got here due to a detach.
9836      - The process that we're detaching from happens to immediately
9837        report a global breakpoint being hit in non-stop mode, in the
9838        same thread we had selected before.
9839      - GDB attaches to this process again.
9840      - This event happens to be the next event we handle.
9841
9842      GDB would consider that the current general thread didn't need to
9843      be set on the stub side (with Hg), since for all it knew,
9844      GENERAL_THREAD hadn't changed.
9845
9846      Notice that although in all-stop mode, the remote server always
9847      sets the current thread to the thread reporting the stop event,
9848      that doesn't happen in non-stop mode; in non-stop, the stub *must
9849      not* change the current thread when reporting a breakpoint hit,
9850      due to the decoupling of event reporting and event handling.
9851
9852      To keep things simple, we always invalidate our notion of the
9853      current thread.  */
9854   record_currthread (rs, minus_one_ptid);
9855
9856   /* Call common code to mark the inferior as not running.  */
9857   generic_mourn_inferior ();
9858
9859   if (!have_inferiors ())
9860     {
9861       if (!remote_multi_process_p (rs))
9862         {
9863           /* Check whether the target is running now - some remote stubs
9864              automatically restart after kill.  */
9865           putpkt ("?");
9866           getpkt (&rs->buf, 0);
9867
9868           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
9869             {
9870               /* Assume that the target has been restarted.  Set
9871                  inferior_ptid so that bits of core GDB realizes
9872                  there's something here, e.g., so that the user can
9873                  say "kill" again.  */
9874               inferior_ptid = magic_null_ptid;
9875             }
9876         }
9877     }
9878 }
9879
9880 bool
9881 extended_remote_target::supports_disable_randomization ()
9882 {
9883   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
9884 }
9885
9886 void
9887 remote_target::extended_remote_disable_randomization (int val)
9888 {
9889   struct remote_state *rs = get_remote_state ();
9890   char *reply;
9891
9892   xsnprintf (rs->buf.data (), get_remote_packet_size (),
9893              "QDisableRandomization:%x", val);
9894   putpkt (rs->buf);
9895   reply = remote_get_noisy_reply ();
9896   if (*reply == '\0')
9897     error (_("Target does not support QDisableRandomization."));
9898   if (strcmp (reply, "OK") != 0)
9899     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
9900 }
9901
9902 int
9903 remote_target::extended_remote_run (const std::string &args)
9904 {
9905   struct remote_state *rs = get_remote_state ();
9906   int len;
9907   const char *remote_exec_file = get_remote_exec_file ();
9908
9909   /* If the user has disabled vRun support, or we have detected that
9910      support is not available, do not try it.  */
9911   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
9912     return -1;
9913
9914   strcpy (rs->buf.data (), "vRun;");
9915   len = strlen (rs->buf.data ());
9916
9917   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
9918     error (_("Remote file name too long for run packet"));
9919   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf.data () + len,
9920                       strlen (remote_exec_file));
9921
9922   if (!args.empty ())
9923     {
9924       int i;
9925
9926       gdb_argv argv (args.c_str ());
9927       for (i = 0; argv[i] != NULL; i++)
9928         {
9929           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
9930             error (_("Argument list too long for run packet"));
9931           rs->buf[len++] = ';';
9932           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf.data () + len,
9933                               strlen (argv[i]));
9934         }
9935     }
9936
9937   rs->buf[len++] = '\0';
9938
9939   putpkt (rs->buf);
9940   getpkt (&rs->buf, 0);
9941
9942   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
9943     {
9944     case PACKET_OK:
9945       /* We have a wait response.  All is well.  */
9946       return 0;
9947     case PACKET_UNKNOWN:
9948       return -1;
9949     case PACKET_ERROR:
9950       if (remote_exec_file[0] == '\0')
9951         error (_("Running the default executable on the remote target failed; "
9952                  "try \"set remote exec-file\"?"));
9953       else
9954         error (_("Running \"%s\" on the remote target failed"),
9955                remote_exec_file);
9956     default:
9957       gdb_assert_not_reached (_("bad switch"));
9958     }
9959 }
9960
9961 /* Helper function to send set/unset environment packets.  ACTION is
9962    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
9963    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
9964    sent.  */
9965
9966 void
9967 remote_target::send_environment_packet (const char *action,
9968                                         const char *packet,
9969                                         const char *value)
9970 {
9971   remote_state *rs = get_remote_state ();
9972
9973   /* Convert the environment variable to an hex string, which
9974      is the best format to be transmitted over the wire.  */
9975   std::string encoded_value = bin2hex ((const gdb_byte *) value,
9976                                          strlen (value));
9977
9978   xsnprintf (rs->buf.data (), get_remote_packet_size (),
9979              "%s:%s", packet, encoded_value.c_str ());
9980
9981   putpkt (rs->buf);
9982   getpkt (&rs->buf, 0);
9983   if (strcmp (rs->buf.data (), "OK") != 0)
9984     warning (_("Unable to %s environment variable '%s' on remote."),
9985              action, value);
9986 }
9987
9988 /* Helper function to handle the QEnvironment* packets.  */
9989
9990 void
9991 remote_target::extended_remote_environment_support ()
9992 {
9993   remote_state *rs = get_remote_state ();
9994
9995   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
9996     {
9997       putpkt ("QEnvironmentReset");
9998       getpkt (&rs->buf, 0);
9999       if (strcmp (rs->buf.data (), "OK") != 0)
10000         warning (_("Unable to reset environment on remote."));
10001     }
10002
10003   gdb_environ *e = &current_inferior ()->environment;
10004
10005   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10006     for (const std::string &el : e->user_set_env ())
10007       send_environment_packet ("set", "QEnvironmentHexEncoded",
10008                                el.c_str ());
10009
10010   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10011     for (const std::string &el : e->user_unset_env ())
10012       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10013 }
10014
10015 /* Helper function to set the current working directory for the
10016    inferior in the remote target.  */
10017
10018 void
10019 remote_target::extended_remote_set_inferior_cwd ()
10020 {
10021   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10022     {
10023       const char *inferior_cwd = get_inferior_cwd ();
10024       remote_state *rs = get_remote_state ();
10025
10026       if (inferior_cwd != NULL)
10027         {
10028           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10029                                          strlen (inferior_cwd));
10030
10031           xsnprintf (rs->buf.data (), get_remote_packet_size (),
10032                      "QSetWorkingDir:%s", hexpath.c_str ());
10033         }
10034       else
10035         {
10036           /* An empty inferior_cwd means that the user wants us to
10037              reset the remote server's inferior's cwd.  */
10038           xsnprintf (rs->buf.data (), get_remote_packet_size (),
10039                      "QSetWorkingDir:");
10040         }
10041
10042       putpkt (rs->buf);
10043       getpkt (&rs->buf, 0);
10044       if (packet_ok (rs->buf,
10045                      &remote_protocol_packets[PACKET_QSetWorkingDir])
10046           != PACKET_OK)
10047         error (_("\
10048 Remote replied unexpectedly while setting the inferior's working\n\
10049 directory: %s"),
10050                rs->buf.data ());
10051
10052     }
10053 }
10054
10055 /* In the extended protocol we want to be able to do things like
10056    "run" and have them basically work as expected.  So we need
10057    a special create_inferior function.  We support changing the
10058    executable file and the command line arguments, but not the
10059    environment.  */
10060
10061 void
10062 extended_remote_target::create_inferior (const char *exec_file,
10063                                          const std::string &args,
10064                                          char **env, int from_tty)
10065 {
10066   int run_worked;
10067   char *stop_reply;
10068   struct remote_state *rs = get_remote_state ();
10069   const char *remote_exec_file = get_remote_exec_file ();
10070
10071   /* If running asynchronously, register the target file descriptor
10072      with the event loop.  */
10073   if (target_can_async_p ())
10074     target_async (1);
10075
10076   /* Disable address space randomization if requested (and supported).  */
10077   if (supports_disable_randomization ())
10078     extended_remote_disable_randomization (disable_randomization);
10079
10080   /* If startup-with-shell is on, we inform gdbserver to start the
10081      remote inferior using a shell.  */
10082   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10083     {
10084       xsnprintf (rs->buf.data (), get_remote_packet_size (),
10085                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10086       putpkt (rs->buf);
10087       getpkt (&rs->buf, 0);
10088       if (strcmp (rs->buf.data (), "OK") != 0)
10089         error (_("\
10090 Remote replied unexpectedly while setting startup-with-shell: %s"),
10091                rs->buf.data ());
10092     }
10093
10094   extended_remote_environment_support ();
10095
10096   extended_remote_set_inferior_cwd ();
10097
10098   /* Now restart the remote server.  */
10099   run_worked = extended_remote_run (args) != -1;
10100   if (!run_worked)
10101     {
10102       /* vRun was not supported.  Fail if we need it to do what the
10103          user requested.  */
10104       if (remote_exec_file[0])
10105         error (_("Remote target does not support \"set remote exec-file\""));
10106       if (!args.empty ())
10107         error (_("Remote target does not support \"set args\" or run ARGS"));
10108
10109       /* Fall back to "R".  */
10110       extended_remote_restart ();
10111     }
10112
10113   /* vRun's success return is a stop reply.  */
10114   stop_reply = run_worked ? rs->buf.data () : NULL;
10115   add_current_inferior_and_thread (stop_reply);
10116
10117   /* Get updated offsets, if the stub uses qOffsets.  */
10118   get_offsets ();
10119 }
10120 \f
10121
10122 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10123    the list of conditions (in agent expression bytecode format), if any, the
10124    target needs to evaluate.  The output is placed into the packet buffer
10125    started from BUF and ended at BUF_END.  */
10126
10127 static int
10128 remote_add_target_side_condition (struct gdbarch *gdbarch,
10129                                   struct bp_target_info *bp_tgt, char *buf,
10130                                   char *buf_end)
10131 {
10132   if (bp_tgt->conditions.empty ())
10133     return 0;
10134
10135   buf += strlen (buf);
10136   xsnprintf (buf, buf_end - buf, "%s", ";");
10137   buf++;
10138
10139   /* Send conditions to the target.  */
10140   for (agent_expr *aexpr : bp_tgt->conditions)
10141     {
10142       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10143       buf += strlen (buf);
10144       for (int i = 0; i < aexpr->len; ++i)
10145         buf = pack_hex_byte (buf, aexpr->buf[i]);
10146       *buf = '\0';
10147     }
10148   return 0;
10149 }
10150
10151 static void
10152 remote_add_target_side_commands (struct gdbarch *gdbarch,
10153                                  struct bp_target_info *bp_tgt, char *buf)
10154 {
10155   if (bp_tgt->tcommands.empty ())
10156     return;
10157
10158   buf += strlen (buf);
10159
10160   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10161   buf += strlen (buf);
10162
10163   /* Concatenate all the agent expressions that are commands into the
10164      cmds parameter.  */
10165   for (agent_expr *aexpr : bp_tgt->tcommands)
10166     {
10167       sprintf (buf, "X%x,", aexpr->len);
10168       buf += strlen (buf);
10169       for (int i = 0; i < aexpr->len; ++i)
10170         buf = pack_hex_byte (buf, aexpr->buf[i]);
10171       *buf = '\0';
10172     }
10173 }
10174
10175 /* Insert a breakpoint.  On targets that have software breakpoint
10176    support, we ask the remote target to do the work; on targets
10177    which don't, we insert a traditional memory breakpoint.  */
10178
10179 int
10180 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10181                                   struct bp_target_info *bp_tgt)
10182 {
10183   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10184      If it succeeds, then set the support to PACKET_ENABLE.  If it
10185      fails, and the user has explicitly requested the Z support then
10186      report an error, otherwise, mark it disabled and go on.  */
10187
10188   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10189     {
10190       CORE_ADDR addr = bp_tgt->reqstd_address;
10191       struct remote_state *rs;
10192       char *p, *endbuf;
10193
10194       /* Make sure the remote is pointing at the right process, if
10195          necessary.  */
10196       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10197         set_general_process ();
10198
10199       rs = get_remote_state ();
10200       p = rs->buf.data ();
10201       endbuf = p + get_remote_packet_size ();
10202
10203       *(p++) = 'Z';
10204       *(p++) = '0';
10205       *(p++) = ',';
10206       addr = (ULONGEST) remote_address_masked (addr);
10207       p += hexnumstr (p, addr);
10208       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10209
10210       if (supports_evaluation_of_breakpoint_conditions ())
10211         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10212
10213       if (can_run_breakpoint_commands ())
10214         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10215
10216       putpkt (rs->buf);
10217       getpkt (&rs->buf, 0);
10218
10219       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10220         {
10221         case PACKET_ERROR:
10222           return -1;
10223         case PACKET_OK:
10224           return 0;
10225         case PACKET_UNKNOWN:
10226           break;
10227         }
10228     }
10229
10230   /* If this breakpoint has target-side commands but this stub doesn't
10231      support Z0 packets, throw error.  */
10232   if (!bp_tgt->tcommands.empty ())
10233     throw_error (NOT_SUPPORTED_ERROR, _("\
10234 Target doesn't support breakpoints that have target side commands."));
10235
10236   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10237 }
10238
10239 int
10240 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10241                                   struct bp_target_info *bp_tgt,
10242                                   enum remove_bp_reason reason)
10243 {
10244   CORE_ADDR addr = bp_tgt->placed_address;
10245   struct remote_state *rs = get_remote_state ();
10246
10247   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10248     {
10249       char *p = rs->buf.data ();
10250       char *endbuf = p + get_remote_packet_size ();
10251
10252       /* Make sure the remote is pointing at the right process, if
10253          necessary.  */
10254       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10255         set_general_process ();
10256
10257       *(p++) = 'z';
10258       *(p++) = '0';
10259       *(p++) = ',';
10260
10261       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10262       p += hexnumstr (p, addr);
10263       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10264
10265       putpkt (rs->buf);
10266       getpkt (&rs->buf, 0);
10267
10268       return (rs->buf[0] == 'E');
10269     }
10270
10271   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10272 }
10273
10274 static enum Z_packet_type
10275 watchpoint_to_Z_packet (int type)
10276 {
10277   switch (type)
10278     {
10279     case hw_write:
10280       return Z_PACKET_WRITE_WP;
10281       break;
10282     case hw_read:
10283       return Z_PACKET_READ_WP;
10284       break;
10285     case hw_access:
10286       return Z_PACKET_ACCESS_WP;
10287       break;
10288     default:
10289       internal_error (__FILE__, __LINE__,
10290                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10291     }
10292 }
10293
10294 int
10295 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10296                                   enum target_hw_bp_type type, struct expression *cond)
10297 {
10298   struct remote_state *rs = get_remote_state ();
10299   char *endbuf = rs->buf.data () + get_remote_packet_size ();
10300   char *p;
10301   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10302
10303   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10304     return 1;
10305
10306   /* Make sure the remote is pointing at the right process, if
10307      necessary.  */
10308   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10309     set_general_process ();
10310
10311   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "Z%x,", packet);
10312   p = strchr (rs->buf.data (), '\0');
10313   addr = remote_address_masked (addr);
10314   p += hexnumstr (p, (ULONGEST) addr);
10315   xsnprintf (p, endbuf - p, ",%x", len);
10316
10317   putpkt (rs->buf);
10318   getpkt (&rs->buf, 0);
10319
10320   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10321     {
10322     case PACKET_ERROR:
10323       return -1;
10324     case PACKET_UNKNOWN:
10325       return 1;
10326     case PACKET_OK:
10327       return 0;
10328     }
10329   internal_error (__FILE__, __LINE__,
10330                   _("remote_insert_watchpoint: reached end of function"));
10331 }
10332
10333 bool
10334 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10335                                              CORE_ADDR start, int length)
10336 {
10337   CORE_ADDR diff = remote_address_masked (addr - start);
10338
10339   return diff < length;
10340 }
10341
10342
10343 int
10344 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10345                                   enum target_hw_bp_type type, struct expression *cond)
10346 {
10347   struct remote_state *rs = get_remote_state ();
10348   char *endbuf = rs->buf.data () + get_remote_packet_size ();
10349   char *p;
10350   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10351
10352   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10353     return -1;
10354
10355   /* Make sure the remote is pointing at the right process, if
10356      necessary.  */
10357   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10358     set_general_process ();
10359
10360   xsnprintf (rs->buf.data (), endbuf - rs->buf.data (), "z%x,", packet);
10361   p = strchr (rs->buf.data (), '\0');
10362   addr = remote_address_masked (addr);
10363   p += hexnumstr (p, (ULONGEST) addr);
10364   xsnprintf (p, endbuf - p, ",%x", len);
10365   putpkt (rs->buf);
10366   getpkt (&rs->buf, 0);
10367
10368   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10369     {
10370     case PACKET_ERROR:
10371     case PACKET_UNKNOWN:
10372       return -1;
10373     case PACKET_OK:
10374       return 0;
10375     }
10376   internal_error (__FILE__, __LINE__,
10377                   _("remote_remove_watchpoint: reached end of function"));
10378 }
10379
10380
10381 static int remote_hw_watchpoint_limit = -1;
10382 static int remote_hw_watchpoint_length_limit = -1;
10383 static int remote_hw_breakpoint_limit = -1;
10384
10385 int
10386 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10387 {
10388   if (remote_hw_watchpoint_length_limit == 0)
10389     return 0;
10390   else if (remote_hw_watchpoint_length_limit < 0)
10391     return 1;
10392   else if (len <= remote_hw_watchpoint_length_limit)
10393     return 1;
10394   else
10395     return 0;
10396 }
10397
10398 int
10399 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10400 {
10401   if (type == bp_hardware_breakpoint)
10402     {
10403       if (remote_hw_breakpoint_limit == 0)
10404         return 0;
10405       else if (remote_hw_breakpoint_limit < 0)
10406         return 1;
10407       else if (cnt <= remote_hw_breakpoint_limit)
10408         return 1;
10409     }
10410   else
10411     {
10412       if (remote_hw_watchpoint_limit == 0)
10413         return 0;
10414       else if (remote_hw_watchpoint_limit < 0)
10415         return 1;
10416       else if (ot)
10417         return -1;
10418       else if (cnt <= remote_hw_watchpoint_limit)
10419         return 1;
10420     }
10421   return -1;
10422 }
10423
10424 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10425
10426 bool
10427 remote_target::stopped_by_sw_breakpoint ()
10428 {
10429   struct thread_info *thread = inferior_thread ();
10430
10431   return (thread->priv != NULL
10432           && (get_remote_thread_info (thread)->stop_reason
10433               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10434 }
10435
10436 /* The to_supports_stopped_by_sw_breakpoint method of target
10437    remote.  */
10438
10439 bool
10440 remote_target::supports_stopped_by_sw_breakpoint ()
10441 {
10442   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10443 }
10444
10445 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10446
10447 bool
10448 remote_target::stopped_by_hw_breakpoint ()
10449 {
10450   struct thread_info *thread = inferior_thread ();
10451
10452   return (thread->priv != NULL
10453           && (get_remote_thread_info (thread)->stop_reason
10454               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10455 }
10456
10457 /* The to_supports_stopped_by_hw_breakpoint method of target
10458    remote.  */
10459
10460 bool
10461 remote_target::supports_stopped_by_hw_breakpoint ()
10462 {
10463   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10464 }
10465
10466 bool
10467 remote_target::stopped_by_watchpoint ()
10468 {
10469   struct thread_info *thread = inferior_thread ();
10470
10471   return (thread->priv != NULL
10472           && (get_remote_thread_info (thread)->stop_reason
10473               == TARGET_STOPPED_BY_WATCHPOINT));
10474 }
10475
10476 bool
10477 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10478 {
10479   struct thread_info *thread = inferior_thread ();
10480
10481   if (thread->priv != NULL
10482       && (get_remote_thread_info (thread)->stop_reason
10483           == TARGET_STOPPED_BY_WATCHPOINT))
10484     {
10485       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10486       return true;
10487     }
10488
10489   return false;
10490 }
10491
10492
10493 int
10494 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10495                                      struct bp_target_info *bp_tgt)
10496 {
10497   CORE_ADDR addr = bp_tgt->reqstd_address;
10498   struct remote_state *rs;
10499   char *p, *endbuf;
10500   char *message;
10501
10502   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10503     return -1;
10504
10505   /* Make sure the remote is pointing at the right process, if
10506      necessary.  */
10507   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10508     set_general_process ();
10509
10510   rs = get_remote_state ();
10511   p = rs->buf.data ();
10512   endbuf = p + get_remote_packet_size ();
10513
10514   *(p++) = 'Z';
10515   *(p++) = '1';
10516   *(p++) = ',';
10517
10518   addr = remote_address_masked (addr);
10519   p += hexnumstr (p, (ULONGEST) addr);
10520   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10521
10522   if (supports_evaluation_of_breakpoint_conditions ())
10523     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10524
10525   if (can_run_breakpoint_commands ())
10526     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10527
10528   putpkt (rs->buf);
10529   getpkt (&rs->buf, 0);
10530
10531   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10532     {
10533     case PACKET_ERROR:
10534       if (rs->buf[1] == '.')
10535         {
10536           message = strchr (&rs->buf[2], '.');
10537           if (message)
10538             error (_("Remote failure reply: %s"), message + 1);
10539         }
10540       return -1;
10541     case PACKET_UNKNOWN:
10542       return -1;
10543     case PACKET_OK:
10544       return 0;
10545     }
10546   internal_error (__FILE__, __LINE__,
10547                   _("remote_insert_hw_breakpoint: reached end of function"));
10548 }
10549
10550
10551 int
10552 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10553                                      struct bp_target_info *bp_tgt)
10554 {
10555   CORE_ADDR addr;
10556   struct remote_state *rs = get_remote_state ();
10557   char *p = rs->buf.data ();
10558   char *endbuf = p + get_remote_packet_size ();
10559
10560   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10561     return -1;
10562
10563   /* Make sure the remote is pointing at the right process, if
10564      necessary.  */
10565   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10566     set_general_process ();
10567
10568   *(p++) = 'z';
10569   *(p++) = '1';
10570   *(p++) = ',';
10571
10572   addr = remote_address_masked (bp_tgt->placed_address);
10573   p += hexnumstr (p, (ULONGEST) addr);
10574   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10575
10576   putpkt (rs->buf);
10577   getpkt (&rs->buf, 0);
10578
10579   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10580     {
10581     case PACKET_ERROR:
10582     case PACKET_UNKNOWN:
10583       return -1;
10584     case PACKET_OK:
10585       return 0;
10586     }
10587   internal_error (__FILE__, __LINE__,
10588                   _("remote_remove_hw_breakpoint: reached end of function"));
10589 }
10590
10591 /* Verify memory using the "qCRC:" request.  */
10592
10593 int
10594 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10595 {
10596   struct remote_state *rs = get_remote_state ();
10597   unsigned long host_crc, target_crc;
10598   char *tmp;
10599
10600   /* It doesn't make sense to use qCRC if the remote target is
10601      connected but not running.  */
10602   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10603     {
10604       enum packet_result result;
10605
10606       /* Make sure the remote is pointing at the right process.  */
10607       set_general_process ();
10608
10609       /* FIXME: assumes lma can fit into long.  */
10610       xsnprintf (rs->buf.data (), get_remote_packet_size (), "qCRC:%lx,%lx",
10611                  (long) lma, (long) size);
10612       putpkt (rs->buf);
10613
10614       /* Be clever; compute the host_crc before waiting for target
10615          reply.  */
10616       host_crc = xcrc32 (data, size, 0xffffffff);
10617
10618       getpkt (&rs->buf, 0);
10619
10620       result = packet_ok (rs->buf,
10621                           &remote_protocol_packets[PACKET_qCRC]);
10622       if (result == PACKET_ERROR)
10623         return -1;
10624       else if (result == PACKET_OK)
10625         {
10626           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10627             target_crc = target_crc * 16 + fromhex (*tmp);
10628
10629           return (host_crc == target_crc);
10630         }
10631     }
10632
10633   return simple_verify_memory (this, data, lma, size);
10634 }
10635
10636 /* compare-sections command
10637
10638    With no arguments, compares each loadable section in the exec bfd
10639    with the same memory range on the target, and reports mismatches.
10640    Useful for verifying the image on the target against the exec file.  */
10641
10642 static void
10643 compare_sections_command (const char *args, int from_tty)
10644 {
10645   asection *s;
10646   const char *sectname;
10647   bfd_size_type size;
10648   bfd_vma lma;
10649   int matched = 0;
10650   int mismatched = 0;
10651   int res;
10652   int read_only = 0;
10653
10654   if (!exec_bfd)
10655     error (_("command cannot be used without an exec file"));
10656
10657   if (args != NULL && strcmp (args, "-r") == 0)
10658     {
10659       read_only = 1;
10660       args = NULL;
10661     }
10662
10663   for (s = exec_bfd->sections; s; s = s->next)
10664     {
10665       if (!(s->flags & SEC_LOAD))
10666         continue;               /* Skip non-loadable section.  */
10667
10668       if (read_only && (s->flags & SEC_READONLY) == 0)
10669         continue;               /* Skip writeable sections */
10670
10671       size = bfd_get_section_size (s);
10672       if (size == 0)
10673         continue;               /* Skip zero-length section.  */
10674
10675       sectname = bfd_get_section_name (exec_bfd, s);
10676       if (args && strcmp (args, sectname) != 0)
10677         continue;               /* Not the section selected by user.  */
10678
10679       matched = 1;              /* Do this section.  */
10680       lma = s->lma;
10681
10682       gdb::byte_vector sectdata (size);
10683       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10684
10685       res = target_verify_memory (sectdata.data (), lma, size);
10686
10687       if (res == -1)
10688         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10689                paddress (target_gdbarch (), lma),
10690                paddress (target_gdbarch (), lma + size));
10691
10692       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10693                        paddress (target_gdbarch (), lma),
10694                        paddress (target_gdbarch (), lma + size));
10695       if (res)
10696         printf_filtered ("matched.\n");
10697       else
10698         {
10699           printf_filtered ("MIS-MATCHED!\n");
10700           mismatched++;
10701         }
10702     }
10703   if (mismatched > 0)
10704     warning (_("One or more sections of the target image does not match\n\
10705 the loaded file\n"));
10706   if (args && !matched)
10707     printf_filtered (_("No loaded section named '%s'.\n"), args);
10708 }
10709
10710 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10711    into remote target.  The number of bytes written to the remote
10712    target is returned, or -1 for error.  */
10713
10714 target_xfer_status
10715 remote_target::remote_write_qxfer (const char *object_name,
10716                                    const char *annex, const gdb_byte *writebuf,
10717                                    ULONGEST offset, LONGEST len,
10718                                    ULONGEST *xfered_len,
10719                                    struct packet_config *packet)
10720 {
10721   int i, buf_len;
10722   ULONGEST n;
10723   struct remote_state *rs = get_remote_state ();
10724   int max_size = get_memory_write_packet_size (); 
10725
10726   if (packet_config_support (packet) == PACKET_DISABLE)
10727     return TARGET_XFER_E_IO;
10728
10729   /* Insert header.  */
10730   i = snprintf (rs->buf.data (), max_size, 
10731                 "qXfer:%s:write:%s:%s:",
10732                 object_name, annex ? annex : "",
10733                 phex_nz (offset, sizeof offset));
10734   max_size -= (i + 1);
10735
10736   /* Escape as much data as fits into rs->buf.  */
10737   buf_len = remote_escape_output 
10738     (writebuf, len, 1, (gdb_byte *) rs->buf.data () + i, &max_size, max_size);
10739
10740   if (putpkt_binary (rs->buf.data (), i + buf_len) < 0
10741       || getpkt_sane (&rs->buf, 0) < 0
10742       || packet_ok (rs->buf, packet) != PACKET_OK)
10743     return TARGET_XFER_E_IO;
10744
10745   unpack_varlen_hex (rs->buf.data (), &n);
10746
10747   *xfered_len = n;
10748   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10749 }
10750
10751 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10752    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10753    number of bytes read is returned, or 0 for EOF, or -1 for error.
10754    The number of bytes read may be less than LEN without indicating an
10755    EOF.  PACKET is checked and updated to indicate whether the remote
10756    target supports this object.  */
10757
10758 target_xfer_status
10759 remote_target::remote_read_qxfer (const char *object_name,
10760                                   const char *annex,
10761                                   gdb_byte *readbuf, ULONGEST offset,
10762                                   LONGEST len,
10763                                   ULONGEST *xfered_len,
10764                                   struct packet_config *packet)
10765 {
10766   struct remote_state *rs = get_remote_state ();
10767   LONGEST i, n, packet_len;
10768
10769   if (packet_config_support (packet) == PACKET_DISABLE)
10770     return TARGET_XFER_E_IO;
10771
10772   /* Check whether we've cached an end-of-object packet that matches
10773      this request.  */
10774   if (rs->finished_object)
10775     {
10776       if (strcmp (object_name, rs->finished_object) == 0
10777           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10778           && offset == rs->finished_offset)
10779         return TARGET_XFER_EOF;
10780
10781
10782       /* Otherwise, we're now reading something different.  Discard
10783          the cache.  */
10784       xfree (rs->finished_object);
10785       xfree (rs->finished_annex);
10786       rs->finished_object = NULL;
10787       rs->finished_annex = NULL;
10788     }
10789
10790   /* Request only enough to fit in a single packet.  The actual data
10791      may not, since we don't know how much of it will need to be escaped;
10792      the target is free to respond with slightly less data.  We subtract
10793      five to account for the response type and the protocol frame.  */
10794   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10795   snprintf (rs->buf.data (), get_remote_packet_size () - 4,
10796             "qXfer:%s:read:%s:%s,%s",
10797             object_name, annex ? annex : "",
10798             phex_nz (offset, sizeof offset),
10799             phex_nz (n, sizeof n));
10800   i = putpkt (rs->buf);
10801   if (i < 0)
10802     return TARGET_XFER_E_IO;
10803
10804   rs->buf[0] = '\0';
10805   packet_len = getpkt_sane (&rs->buf, 0);
10806   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10807     return TARGET_XFER_E_IO;
10808
10809   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10810     error (_("Unknown remote qXfer reply: %s"), rs->buf.data ());
10811
10812   /* 'm' means there is (or at least might be) more data after this
10813      batch.  That does not make sense unless there's at least one byte
10814      of data in this reply.  */
10815   if (rs->buf[0] == 'm' && packet_len == 1)
10816     error (_("Remote qXfer reply contained no data."));
10817
10818   /* Got some data.  */
10819   i = remote_unescape_input ((gdb_byte *) rs->buf.data () + 1,
10820                              packet_len - 1, readbuf, n);
10821
10822   /* 'l' is an EOF marker, possibly including a final block of data,
10823      or possibly empty.  If we have the final block of a non-empty
10824      object, record this fact to bypass a subsequent partial read.  */
10825   if (rs->buf[0] == 'l' && offset + i > 0)
10826     {
10827       rs->finished_object = xstrdup (object_name);
10828       rs->finished_annex = xstrdup (annex ? annex : "");
10829       rs->finished_offset = offset + i;
10830     }
10831
10832   if (i == 0)
10833     return TARGET_XFER_EOF;
10834   else
10835     {
10836       *xfered_len = i;
10837       return TARGET_XFER_OK;
10838     }
10839 }
10840
10841 enum target_xfer_status
10842 remote_target::xfer_partial (enum target_object object,
10843                              const char *annex, gdb_byte *readbuf,
10844                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
10845                              ULONGEST *xfered_len)
10846 {
10847   struct remote_state *rs;
10848   int i;
10849   char *p2;
10850   char query_type;
10851   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
10852
10853   set_remote_traceframe ();
10854   set_general_thread (inferior_ptid);
10855
10856   rs = get_remote_state ();
10857
10858   /* Handle memory using the standard memory routines.  */
10859   if (object == TARGET_OBJECT_MEMORY)
10860     {
10861       /* If the remote target is connected but not running, we should
10862          pass this request down to a lower stratum (e.g. the executable
10863          file).  */
10864       if (!target_has_execution)
10865         return TARGET_XFER_EOF;
10866
10867       if (writebuf != NULL)
10868         return remote_write_bytes (offset, writebuf, len, unit_size,
10869                                    xfered_len);
10870       else
10871         return remote_read_bytes (offset, readbuf, len, unit_size,
10872                                   xfered_len);
10873     }
10874
10875   /* Handle SPU memory using qxfer packets.  */
10876   if (object == TARGET_OBJECT_SPU)
10877     {
10878       if (readbuf)
10879         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
10880                                   xfered_len, &remote_protocol_packets
10881                                   [PACKET_qXfer_spu_read]);
10882       else
10883         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
10884                                    xfered_len, &remote_protocol_packets
10885                                    [PACKET_qXfer_spu_write]);
10886     }
10887
10888   /* Handle extra signal info using qxfer packets.  */
10889   if (object == TARGET_OBJECT_SIGNAL_INFO)
10890     {
10891       if (readbuf)
10892         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
10893                                   xfered_len, &remote_protocol_packets
10894                                   [PACKET_qXfer_siginfo_read]);
10895       else
10896         return remote_write_qxfer ("siginfo", annex,
10897                                    writebuf, offset, len, xfered_len,
10898                                    &remote_protocol_packets
10899                                    [PACKET_qXfer_siginfo_write]);
10900     }
10901
10902   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
10903     {
10904       if (readbuf)
10905         return remote_read_qxfer ("statictrace", annex,
10906                                   readbuf, offset, len, xfered_len,
10907                                   &remote_protocol_packets
10908                                   [PACKET_qXfer_statictrace_read]);
10909       else
10910         return TARGET_XFER_E_IO;
10911     }
10912
10913   /* Only handle flash writes.  */
10914   if (writebuf != NULL)
10915     {
10916       switch (object)
10917         {
10918         case TARGET_OBJECT_FLASH:
10919           return remote_flash_write (offset, len, xfered_len,
10920                                      writebuf);
10921
10922         default:
10923           return TARGET_XFER_E_IO;
10924         }
10925     }
10926
10927   /* Map pre-existing objects onto letters.  DO NOT do this for new
10928      objects!!!  Instead specify new query packets.  */
10929   switch (object)
10930     {
10931     case TARGET_OBJECT_AVR:
10932       query_type = 'R';
10933       break;
10934
10935     case TARGET_OBJECT_AUXV:
10936       gdb_assert (annex == NULL);
10937       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
10938                                 xfered_len,
10939                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
10940
10941     case TARGET_OBJECT_AVAILABLE_FEATURES:
10942       return remote_read_qxfer
10943         ("features", annex, readbuf, offset, len, xfered_len,
10944          &remote_protocol_packets[PACKET_qXfer_features]);
10945
10946     case TARGET_OBJECT_LIBRARIES:
10947       return remote_read_qxfer
10948         ("libraries", annex, readbuf, offset, len, xfered_len,
10949          &remote_protocol_packets[PACKET_qXfer_libraries]);
10950
10951     case TARGET_OBJECT_LIBRARIES_SVR4:
10952       return remote_read_qxfer
10953         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
10954          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
10955
10956     case TARGET_OBJECT_MEMORY_MAP:
10957       gdb_assert (annex == NULL);
10958       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
10959                                  xfered_len,
10960                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
10961
10962     case TARGET_OBJECT_OSDATA:
10963       /* Should only get here if we're connected.  */
10964       gdb_assert (rs->remote_desc);
10965       return remote_read_qxfer
10966         ("osdata", annex, readbuf, offset, len, xfered_len,
10967         &remote_protocol_packets[PACKET_qXfer_osdata]);
10968
10969     case TARGET_OBJECT_THREADS:
10970       gdb_assert (annex == NULL);
10971       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
10972                                 xfered_len,
10973                                 &remote_protocol_packets[PACKET_qXfer_threads]);
10974
10975     case TARGET_OBJECT_TRACEFRAME_INFO:
10976       gdb_assert (annex == NULL);
10977       return remote_read_qxfer
10978         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
10979          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
10980
10981     case TARGET_OBJECT_FDPIC:
10982       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
10983                                 xfered_len,
10984                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
10985
10986     case TARGET_OBJECT_OPENVMS_UIB:
10987       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
10988                                 xfered_len,
10989                                 &remote_protocol_packets[PACKET_qXfer_uib]);
10990
10991     case TARGET_OBJECT_BTRACE:
10992       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
10993                                 xfered_len,
10994         &remote_protocol_packets[PACKET_qXfer_btrace]);
10995
10996     case TARGET_OBJECT_BTRACE_CONF:
10997       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
10998                                 len, xfered_len,
10999         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11000
11001     case TARGET_OBJECT_EXEC_FILE:
11002       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11003                                 len, xfered_len,
11004         &remote_protocol_packets[PACKET_qXfer_exec_file]);
11005
11006     default:
11007       return TARGET_XFER_E_IO;
11008     }
11009
11010   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
11011      large enough let the caller deal with it.  */
11012   if (len < get_remote_packet_size ())
11013     return TARGET_XFER_E_IO;
11014   len = get_remote_packet_size ();
11015
11016   /* Except for querying the minimum buffer size, target must be open.  */
11017   if (!rs->remote_desc)
11018     error (_("remote query is only available after target open"));
11019
11020   gdb_assert (annex != NULL);
11021   gdb_assert (readbuf != NULL);
11022
11023   p2 = rs->buf.data ();
11024   *p2++ = 'q';
11025   *p2++ = query_type;
11026
11027   /* We used one buffer char for the remote protocol q command and
11028      another for the query type.  As the remote protocol encapsulation
11029      uses 4 chars plus one extra in case we are debugging
11030      (remote_debug), we have PBUFZIZ - 7 left to pack the query
11031      string.  */
11032   i = 0;
11033   while (annex[i] && (i < (get_remote_packet_size () - 8)))
11034     {
11035       /* Bad caller may have sent forbidden characters.  */
11036       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11037       *p2++ = annex[i];
11038       i++;
11039     }
11040   *p2 = '\0';
11041   gdb_assert (annex[i] == '\0');
11042
11043   i = putpkt (rs->buf);
11044   if (i < 0)
11045     return TARGET_XFER_E_IO;
11046
11047   getpkt (&rs->buf, 0);
11048   strcpy ((char *) readbuf, rs->buf.data ());
11049
11050   *xfered_len = strlen ((char *) readbuf);
11051   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11052 }
11053
11054 /* Implementation of to_get_memory_xfer_limit.  */
11055
11056 ULONGEST
11057 remote_target::get_memory_xfer_limit ()
11058 {
11059   return get_memory_write_packet_size ();
11060 }
11061
11062 int
11063 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11064                               const gdb_byte *pattern, ULONGEST pattern_len,
11065                               CORE_ADDR *found_addrp)
11066 {
11067   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11068   struct remote_state *rs = get_remote_state ();
11069   int max_size = get_memory_write_packet_size ();
11070   struct packet_config *packet =
11071     &remote_protocol_packets[PACKET_qSearch_memory];
11072   /* Number of packet bytes used to encode the pattern;
11073      this could be more than PATTERN_LEN due to escape characters.  */
11074   int escaped_pattern_len;
11075   /* Amount of pattern that was encodable in the packet.  */
11076   int used_pattern_len;
11077   int i;
11078   int found;
11079   ULONGEST found_addr;
11080
11081   /* Don't go to the target if we don't have to.  This is done before
11082      checking packet_config_support to avoid the possibility that a
11083      success for this edge case means the facility works in
11084      general.  */
11085   if (pattern_len > search_space_len)
11086     return 0;
11087   if (pattern_len == 0)
11088     {
11089       *found_addrp = start_addr;
11090       return 1;
11091     }
11092
11093   /* If we already know the packet isn't supported, fall back to the simple
11094      way of searching memory.  */
11095
11096   if (packet_config_support (packet) == PACKET_DISABLE)
11097     {
11098       /* Target doesn't provided special support, fall back and use the
11099          standard support (copy memory and do the search here).  */
11100       return simple_search_memory (this, start_addr, search_space_len,
11101                                    pattern, pattern_len, found_addrp);
11102     }
11103
11104   /* Make sure the remote is pointing at the right process.  */
11105   set_general_process ();
11106
11107   /* Insert header.  */
11108   i = snprintf (rs->buf.data (), max_size, 
11109                 "qSearch:memory:%s;%s;",
11110                 phex_nz (start_addr, addr_size),
11111                 phex_nz (search_space_len, sizeof (search_space_len)));
11112   max_size -= (i + 1);
11113
11114   /* Escape as much data as fits into rs->buf.  */
11115   escaped_pattern_len =
11116     remote_escape_output (pattern, pattern_len, 1,
11117                           (gdb_byte *) rs->buf.data () + i,
11118                           &used_pattern_len, max_size);
11119
11120   /* Bail if the pattern is too large.  */
11121   if (used_pattern_len != pattern_len)
11122     error (_("Pattern is too large to transmit to remote target."));
11123
11124   if (putpkt_binary (rs->buf.data (), i + escaped_pattern_len) < 0
11125       || getpkt_sane (&rs->buf, 0) < 0
11126       || packet_ok (rs->buf, packet) != PACKET_OK)
11127     {
11128       /* The request may not have worked because the command is not
11129          supported.  If so, fall back to the simple way.  */
11130       if (packet_config_support (packet) == PACKET_DISABLE)
11131         {
11132           return simple_search_memory (this, start_addr, search_space_len,
11133                                        pattern, pattern_len, found_addrp);
11134         }
11135       return -1;
11136     }
11137
11138   if (rs->buf[0] == '0')
11139     found = 0;
11140   else if (rs->buf[0] == '1')
11141     {
11142       found = 1;
11143       if (rs->buf[1] != ',')
11144         error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11145       unpack_varlen_hex (&rs->buf[2], &found_addr);
11146       *found_addrp = found_addr;
11147     }
11148   else
11149     error (_("Unknown qSearch:memory reply: %s"), rs->buf.data ());
11150
11151   return found;
11152 }
11153
11154 void
11155 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11156 {
11157   struct remote_state *rs = get_remote_state ();
11158   char *p = rs->buf.data ();
11159
11160   if (!rs->remote_desc)
11161     error (_("remote rcmd is only available after target open"));
11162
11163   /* Send a NULL command across as an empty command.  */
11164   if (command == NULL)
11165     command = "";
11166
11167   /* The query prefix.  */
11168   strcpy (rs->buf.data (), "qRcmd,");
11169   p = strchr (rs->buf.data (), '\0');
11170
11171   if ((strlen (rs->buf.data ()) + strlen (command) * 2 + 8/*misc*/)
11172       > get_remote_packet_size ())
11173     error (_("\"monitor\" command ``%s'' is too long."), command);
11174
11175   /* Encode the actual command.  */
11176   bin2hex ((const gdb_byte *) command, p, strlen (command));
11177
11178   if (putpkt (rs->buf) < 0)
11179     error (_("Communication problem with target."));
11180
11181   /* get/display the response */
11182   while (1)
11183     {
11184       char *buf;
11185
11186       /* XXX - see also remote_get_noisy_reply().  */
11187       QUIT;                     /* Allow user to bail out with ^C.  */
11188       rs->buf[0] = '\0';
11189       if (getpkt_sane (&rs->buf, 0) == -1)
11190         { 
11191           /* Timeout.  Continue to (try to) read responses.
11192              This is better than stopping with an error, assuming the stub
11193              is still executing the (long) monitor command.
11194              If needed, the user can interrupt gdb using C-c, obtaining
11195              an effect similar to stop on timeout.  */
11196           continue;
11197         }
11198       buf = rs->buf.data ();
11199       if (buf[0] == '\0')
11200         error (_("Target does not support this command."));
11201       if (buf[0] == 'O' && buf[1] != 'K')
11202         {
11203           remote_console_output (buf + 1); /* 'O' message from stub.  */
11204           continue;
11205         }
11206       if (strcmp (buf, "OK") == 0)
11207         break;
11208       if (strlen (buf) == 3 && buf[0] == 'E'
11209           && isdigit (buf[1]) && isdigit (buf[2]))
11210         {
11211           error (_("Protocol error with Rcmd"));
11212         }
11213       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11214         {
11215           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11216
11217           fputc_unfiltered (c, outbuf);
11218         }
11219       break;
11220     }
11221 }
11222
11223 std::vector<mem_region>
11224 remote_target::memory_map ()
11225 {
11226   std::vector<mem_region> result;
11227   gdb::optional<gdb::char_vector> text
11228     = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11229
11230   if (text)
11231     result = parse_memory_map (text->data ());
11232
11233   return result;
11234 }
11235
11236 static void
11237 packet_command (const char *args, int from_tty)
11238 {
11239   remote_target *remote = get_current_remote_target ();
11240
11241   if (remote == nullptr)
11242     error (_("command can only be used with remote target"));
11243
11244   remote->packet_command (args, from_tty);
11245 }
11246
11247 void
11248 remote_target::packet_command (const char *args, int from_tty)
11249 {
11250   if (!args)
11251     error (_("remote-packet command requires packet text as argument"));
11252
11253   puts_filtered ("sending: ");
11254   print_packet (args);
11255   puts_filtered ("\n");
11256   putpkt (args);
11257
11258   remote_state *rs = get_remote_state ();
11259
11260   getpkt (&rs->buf, 0);
11261   puts_filtered ("received: ");
11262   print_packet (rs->buf.data ());
11263   puts_filtered ("\n");
11264 }
11265
11266 #if 0
11267 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11268
11269 static void display_thread_info (struct gdb_ext_thread_info *info);
11270
11271 static void threadset_test_cmd (char *cmd, int tty);
11272
11273 static void threadalive_test (char *cmd, int tty);
11274
11275 static void threadlist_test_cmd (char *cmd, int tty);
11276
11277 int get_and_display_threadinfo (threadref *ref);
11278
11279 static void threadinfo_test_cmd (char *cmd, int tty);
11280
11281 static int thread_display_step (threadref *ref, void *context);
11282
11283 static void threadlist_update_test_cmd (char *cmd, int tty);
11284
11285 static void init_remote_threadtests (void);
11286
11287 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11288
11289 static void
11290 threadset_test_cmd (const char *cmd, int tty)
11291 {
11292   int sample_thread = SAMPLE_THREAD;
11293
11294   printf_filtered (_("Remote threadset test\n"));
11295   set_general_thread (sample_thread);
11296 }
11297
11298
11299 static void
11300 threadalive_test (const char *cmd, int tty)
11301 {
11302   int sample_thread = SAMPLE_THREAD;
11303   int pid = inferior_ptid.pid ();
11304   ptid_t ptid = ptid_t (pid, sample_thread, 0);
11305
11306   if (remote_thread_alive (ptid))
11307     printf_filtered ("PASS: Thread alive test\n");
11308   else
11309     printf_filtered ("FAIL: Thread alive test\n");
11310 }
11311
11312 void output_threadid (char *title, threadref *ref);
11313
11314 void
11315 output_threadid (char *title, threadref *ref)
11316 {
11317   char hexid[20];
11318
11319   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11320   hexid[16] = 0;
11321   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11322 }
11323
11324 static void
11325 threadlist_test_cmd (const char *cmd, int tty)
11326 {
11327   int startflag = 1;
11328   threadref nextthread;
11329   int done, result_count;
11330   threadref threadlist[3];
11331
11332   printf_filtered ("Remote Threadlist test\n");
11333   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11334                               &result_count, &threadlist[0]))
11335     printf_filtered ("FAIL: threadlist test\n");
11336   else
11337     {
11338       threadref *scan = threadlist;
11339       threadref *limit = scan + result_count;
11340
11341       while (scan < limit)
11342         output_threadid (" thread ", scan++);
11343     }
11344 }
11345
11346 void
11347 display_thread_info (struct gdb_ext_thread_info *info)
11348 {
11349   output_threadid ("Threadid: ", &info->threadid);
11350   printf_filtered ("Name: %s\n ", info->shortname);
11351   printf_filtered ("State: %s\n", info->display);
11352   printf_filtered ("other: %s\n\n", info->more_display);
11353 }
11354
11355 int
11356 get_and_display_threadinfo (threadref *ref)
11357 {
11358   int result;
11359   int set;
11360   struct gdb_ext_thread_info threadinfo;
11361
11362   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11363     | TAG_MOREDISPLAY | TAG_DISPLAY;
11364   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11365     display_thread_info (&threadinfo);
11366   return result;
11367 }
11368
11369 static void
11370 threadinfo_test_cmd (const char *cmd, int tty)
11371 {
11372   int athread = SAMPLE_THREAD;
11373   threadref thread;
11374   int set;
11375
11376   int_to_threadref (&thread, athread);
11377   printf_filtered ("Remote Threadinfo test\n");
11378   if (!get_and_display_threadinfo (&thread))
11379     printf_filtered ("FAIL cannot get thread info\n");
11380 }
11381
11382 static int
11383 thread_display_step (threadref *ref, void *context)
11384 {
11385   /* output_threadid(" threadstep ",ref); *//* simple test */
11386   return get_and_display_threadinfo (ref);
11387 }
11388
11389 static void
11390 threadlist_update_test_cmd (const char *cmd, int tty)
11391 {
11392   printf_filtered ("Remote Threadlist update test\n");
11393   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11394 }
11395
11396 static void
11397 init_remote_threadtests (void)
11398 {
11399   add_com ("tlist", class_obscure, threadlist_test_cmd,
11400            _("Fetch and print the remote list of "
11401              "thread identifiers, one pkt only"));
11402   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11403            _("Fetch and display info about one thread"));
11404   add_com ("tset", class_obscure, threadset_test_cmd,
11405            _("Test setting to a different thread"));
11406   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11407            _("Iterate through updating all remote thread info"));
11408   add_com ("talive", class_obscure, threadalive_test,
11409            _(" Remote thread alive test "));
11410 }
11411
11412 #endif /* 0 */
11413
11414 /* Convert a thread ID to a string.  */
11415
11416 std::string
11417 remote_target::pid_to_str (ptid_t ptid)
11418 {
11419   struct remote_state *rs = get_remote_state ();
11420
11421   if (ptid == null_ptid)
11422     return normal_pid_to_str (ptid);
11423   else if (ptid.is_pid ())
11424     {
11425       /* Printing an inferior target id.  */
11426
11427       /* When multi-process extensions are off, there's no way in the
11428          remote protocol to know the remote process id, if there's any
11429          at all.  There's one exception --- when we're connected with
11430          target extended-remote, and we manually attached to a process
11431          with "attach PID".  We don't record anywhere a flag that
11432          allows us to distinguish that case from the case of
11433          connecting with extended-remote and the stub already being
11434          attached to a process, and reporting yes to qAttached, hence
11435          no smart special casing here.  */
11436       if (!remote_multi_process_p (rs))
11437         return "Remote target";
11438
11439       return normal_pid_to_str (ptid);
11440     }
11441   else
11442     {
11443       if (magic_null_ptid == ptid)
11444         return "Thread <main>";
11445       else if (remote_multi_process_p (rs))
11446         if (ptid.lwp () == 0)
11447           return normal_pid_to_str (ptid);
11448         else
11449           return string_printf ("Thread %d.%ld",
11450                                 ptid.pid (), ptid.lwp ());
11451       else
11452         return string_printf ("Thread %ld", ptid.lwp ());
11453     }
11454 }
11455
11456 /* Get the address of the thread local variable in OBJFILE which is
11457    stored at OFFSET within the thread local storage for thread PTID.  */
11458
11459 CORE_ADDR
11460 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11461                                          CORE_ADDR offset)
11462 {
11463   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11464     {
11465       struct remote_state *rs = get_remote_state ();
11466       char *p = rs->buf.data ();
11467       char *endp = p + get_remote_packet_size ();
11468       enum packet_result result;
11469
11470       strcpy (p, "qGetTLSAddr:");
11471       p += strlen (p);
11472       p = write_ptid (p, endp, ptid);
11473       *p++ = ',';
11474       p += hexnumstr (p, offset);
11475       *p++ = ',';
11476       p += hexnumstr (p, lm);
11477       *p++ = '\0';
11478
11479       putpkt (rs->buf);
11480       getpkt (&rs->buf, 0);
11481       result = packet_ok (rs->buf,
11482                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11483       if (result == PACKET_OK)
11484         {
11485           ULONGEST addr;
11486
11487           unpack_varlen_hex (rs->buf.data (), &addr);
11488           return addr;
11489         }
11490       else if (result == PACKET_UNKNOWN)
11491         throw_error (TLS_GENERIC_ERROR,
11492                      _("Remote target doesn't support qGetTLSAddr packet"));
11493       else
11494         throw_error (TLS_GENERIC_ERROR,
11495                      _("Remote target failed to process qGetTLSAddr request"));
11496     }
11497   else
11498     throw_error (TLS_GENERIC_ERROR,
11499                  _("TLS not supported or disabled on this target"));
11500   /* Not reached.  */
11501   return 0;
11502 }
11503
11504 /* Provide thread local base, i.e. Thread Information Block address.
11505    Returns 1 if ptid is found and thread_local_base is non zero.  */
11506
11507 bool
11508 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11509 {
11510   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11511     {
11512       struct remote_state *rs = get_remote_state ();
11513       char *p = rs->buf.data ();
11514       char *endp = p + get_remote_packet_size ();
11515       enum packet_result result;
11516
11517       strcpy (p, "qGetTIBAddr:");
11518       p += strlen (p);
11519       p = write_ptid (p, endp, ptid);
11520       *p++ = '\0';
11521
11522       putpkt (rs->buf);
11523       getpkt (&rs->buf, 0);
11524       result = packet_ok (rs->buf,
11525                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11526       if (result == PACKET_OK)
11527         {
11528           ULONGEST val;
11529           unpack_varlen_hex (rs->buf.data (), &val);
11530           if (addr)
11531             *addr = (CORE_ADDR) val;
11532           return true;
11533         }
11534       else if (result == PACKET_UNKNOWN)
11535         error (_("Remote target doesn't support qGetTIBAddr packet"));
11536       else
11537         error (_("Remote target failed to process qGetTIBAddr request"));
11538     }
11539   else
11540     error (_("qGetTIBAddr not supported or disabled on this target"));
11541   /* Not reached.  */
11542   return false;
11543 }
11544
11545 /* Support for inferring a target description based on the current
11546    architecture and the size of a 'g' packet.  While the 'g' packet
11547    can have any size (since optional registers can be left off the
11548    end), some sizes are easily recognizable given knowledge of the
11549    approximate architecture.  */
11550
11551 struct remote_g_packet_guess
11552 {
11553   remote_g_packet_guess (int bytes_, const struct target_desc *tdesc_)
11554     : bytes (bytes_),
11555       tdesc (tdesc_)
11556   {
11557   }
11558
11559   int bytes;
11560   const struct target_desc *tdesc;
11561 };
11562
11563 struct remote_g_packet_data : public allocate_on_obstack
11564 {
11565   std::vector<remote_g_packet_guess> guesses;
11566 };
11567
11568 static struct gdbarch_data *remote_g_packet_data_handle;
11569
11570 static void *
11571 remote_g_packet_data_init (struct obstack *obstack)
11572 {
11573   return new (obstack) remote_g_packet_data;
11574 }
11575
11576 void
11577 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11578                                 const struct target_desc *tdesc)
11579 {
11580   struct remote_g_packet_data *data
11581     = ((struct remote_g_packet_data *)
11582        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11583
11584   gdb_assert (tdesc != NULL);
11585
11586   for (const remote_g_packet_guess &guess : data->guesses)
11587     if (guess.bytes == bytes)
11588       internal_error (__FILE__, __LINE__,
11589                       _("Duplicate g packet description added for size %d"),
11590                       bytes);
11591
11592   data->guesses.emplace_back (bytes, tdesc);
11593 }
11594
11595 /* Return true if remote_read_description would do anything on this target
11596    and architecture, false otherwise.  */
11597
11598 static bool
11599 remote_read_description_p (struct target_ops *target)
11600 {
11601   struct remote_g_packet_data *data
11602     = ((struct remote_g_packet_data *)
11603        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11604
11605   return !data->guesses.empty ();
11606 }
11607
11608 const struct target_desc *
11609 remote_target::read_description ()
11610 {
11611   struct remote_g_packet_data *data
11612     = ((struct remote_g_packet_data *)
11613        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11614
11615   /* Do not try this during initial connection, when we do not know
11616      whether there is a running but stopped thread.  */
11617   if (!target_has_execution || inferior_ptid == null_ptid)
11618     return beneath ()->read_description ();
11619
11620   if (!data->guesses.empty ())
11621     {
11622       int bytes = send_g_packet ();
11623
11624       for (const remote_g_packet_guess &guess : data->guesses)
11625         if (guess.bytes == bytes)
11626           return guess.tdesc;
11627
11628       /* We discard the g packet.  A minor optimization would be to
11629          hold on to it, and fill the register cache once we have selected
11630          an architecture, but it's too tricky to do safely.  */
11631     }
11632
11633   return beneath ()->read_description ();
11634 }
11635
11636 /* Remote file transfer support.  This is host-initiated I/O, not
11637    target-initiated; for target-initiated, see remote-fileio.c.  */
11638
11639 /* If *LEFT is at least the length of STRING, copy STRING to
11640    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11641    decrease *LEFT.  Otherwise raise an error.  */
11642
11643 static void
11644 remote_buffer_add_string (char **buffer, int *left, const char *string)
11645 {
11646   int len = strlen (string);
11647
11648   if (len > *left)
11649     error (_("Packet too long for target."));
11650
11651   memcpy (*buffer, string, len);
11652   *buffer += len;
11653   *left -= len;
11654
11655   /* NUL-terminate the buffer as a convenience, if there is
11656      room.  */
11657   if (*left)
11658     **buffer = '\0';
11659 }
11660
11661 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11662    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11663    decrease *LEFT.  Otherwise raise an error.  */
11664
11665 static void
11666 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11667                          int len)
11668 {
11669   if (2 * len > *left)
11670     error (_("Packet too long for target."));
11671
11672   bin2hex (bytes, *buffer, len);
11673   *buffer += 2 * len;
11674   *left -= 2 * len;
11675
11676   /* NUL-terminate the buffer as a convenience, if there is
11677      room.  */
11678   if (*left)
11679     **buffer = '\0';
11680 }
11681
11682 /* If *LEFT is large enough, convert VALUE to hex and add it to
11683    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11684    decrease *LEFT.  Otherwise raise an error.  */
11685
11686 static void
11687 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11688 {
11689   int len = hexnumlen (value);
11690
11691   if (len > *left)
11692     error (_("Packet too long for target."));
11693
11694   hexnumstr (*buffer, value);
11695   *buffer += len;
11696   *left -= len;
11697
11698   /* NUL-terminate the buffer as a convenience, if there is
11699      room.  */
11700   if (*left)
11701     **buffer = '\0';
11702 }
11703
11704 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11705    value, *REMOTE_ERRNO to the remote error number or zero if none
11706    was included, and *ATTACHMENT to point to the start of the annex
11707    if any.  The length of the packet isn't needed here; there may
11708    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11709
11710    Return 0 if the packet could be parsed, -1 if it could not.  If
11711    -1 is returned, the other variables may not be initialized.  */
11712
11713 static int
11714 remote_hostio_parse_result (char *buffer, int *retcode,
11715                             int *remote_errno, char **attachment)
11716 {
11717   char *p, *p2;
11718
11719   *remote_errno = 0;
11720   *attachment = NULL;
11721
11722   if (buffer[0] != 'F')
11723     return -1;
11724
11725   errno = 0;
11726   *retcode = strtol (&buffer[1], &p, 16);
11727   if (errno != 0 || p == &buffer[1])
11728     return -1;
11729
11730   /* Check for ",errno".  */
11731   if (*p == ',')
11732     {
11733       errno = 0;
11734       *remote_errno = strtol (p + 1, &p2, 16);
11735       if (errno != 0 || p + 1 == p2)
11736         return -1;
11737       p = p2;
11738     }
11739
11740   /* Check for ";attachment".  If there is no attachment, the
11741      packet should end here.  */
11742   if (*p == ';')
11743     {
11744       *attachment = p + 1;
11745       return 0;
11746     }
11747   else if (*p == '\0')
11748     return 0;
11749   else
11750     return -1;
11751 }
11752
11753 /* Send a prepared I/O packet to the target and read its response.
11754    The prepared packet is in the global RS->BUF before this function
11755    is called, and the answer is there when we return.
11756
11757    COMMAND_BYTES is the length of the request to send, which may include
11758    binary data.  WHICH_PACKET is the packet configuration to check
11759    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11760    is set to the error number and -1 is returned.  Otherwise the value
11761    returned by the function is returned.
11762
11763    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11764    attachment is expected; an error will be reported if there's a
11765    mismatch.  If one is found, *ATTACHMENT will be set to point into
11766    the packet buffer and *ATTACHMENT_LEN will be set to the
11767    attachment's length.  */
11768
11769 int
11770 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11771                                            int *remote_errno, char **attachment,
11772                                            int *attachment_len)
11773 {
11774   struct remote_state *rs = get_remote_state ();
11775   int ret, bytes_read;
11776   char *attachment_tmp;
11777
11778   if (packet_support (which_packet) == PACKET_DISABLE)
11779     {
11780       *remote_errno = FILEIO_ENOSYS;
11781       return -1;
11782     }
11783
11784   putpkt_binary (rs->buf.data (), command_bytes);
11785   bytes_read = getpkt_sane (&rs->buf, 0);
11786
11787   /* If it timed out, something is wrong.  Don't try to parse the
11788      buffer.  */
11789   if (bytes_read < 0)
11790     {
11791       *remote_errno = FILEIO_EINVAL;
11792       return -1;
11793     }
11794
11795   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11796     {
11797     case PACKET_ERROR:
11798       *remote_errno = FILEIO_EINVAL;
11799       return -1;
11800     case PACKET_UNKNOWN:
11801       *remote_errno = FILEIO_ENOSYS;
11802       return -1;
11803     case PACKET_OK:
11804       break;
11805     }
11806
11807   if (remote_hostio_parse_result (rs->buf.data (), &ret, remote_errno,
11808                                   &attachment_tmp))
11809     {
11810       *remote_errno = FILEIO_EINVAL;
11811       return -1;
11812     }
11813
11814   /* Make sure we saw an attachment if and only if we expected one.  */
11815   if ((attachment_tmp == NULL && attachment != NULL)
11816       || (attachment_tmp != NULL && attachment == NULL))
11817     {
11818       *remote_errno = FILEIO_EINVAL;
11819       return -1;
11820     }
11821
11822   /* If an attachment was found, it must point into the packet buffer;
11823      work out how many bytes there were.  */
11824   if (attachment_tmp != NULL)
11825     {
11826       *attachment = attachment_tmp;
11827       *attachment_len = bytes_read - (*attachment - rs->buf.data ());
11828     }
11829
11830   return ret;
11831 }
11832
11833 /* See declaration.h.  */
11834
11835 void
11836 readahead_cache::invalidate ()
11837 {
11838   this->fd = -1;
11839 }
11840
11841 /* See declaration.h.  */
11842
11843 void
11844 readahead_cache::invalidate_fd (int fd)
11845 {
11846   if (this->fd == fd)
11847     this->fd = -1;
11848 }
11849
11850 /* Set the filesystem remote_hostio functions that take FILENAME
11851    arguments will use.  Return 0 on success, or -1 if an error
11852    occurs (and set *REMOTE_ERRNO).  */
11853
11854 int
11855 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
11856                                              int *remote_errno)
11857 {
11858   struct remote_state *rs = get_remote_state ();
11859   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
11860   char *p = rs->buf.data ();
11861   int left = get_remote_packet_size () - 1;
11862   char arg[9];
11863   int ret;
11864
11865   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11866     return 0;
11867
11868   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
11869     return 0;
11870
11871   remote_buffer_add_string (&p, &left, "vFile:setfs:");
11872
11873   xsnprintf (arg, sizeof (arg), "%x", required_pid);
11874   remote_buffer_add_string (&p, &left, arg);
11875
11876   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_setfs,
11877                                     remote_errno, NULL, NULL);
11878
11879   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
11880     return 0;
11881
11882   if (ret == 0)
11883     rs->fs_pid = required_pid;
11884
11885   return ret;
11886 }
11887
11888 /* Implementation of to_fileio_open.  */
11889
11890 int
11891 remote_target::remote_hostio_open (inferior *inf, const char *filename,
11892                                    int flags, int mode, int warn_if_slow,
11893                                    int *remote_errno)
11894 {
11895   struct remote_state *rs = get_remote_state ();
11896   char *p = rs->buf.data ();
11897   int left = get_remote_packet_size () - 1;
11898
11899   if (warn_if_slow)
11900     {
11901       static int warning_issued = 0;
11902
11903       printf_unfiltered (_("Reading %s from remote target...\n"),
11904                          filename);
11905
11906       if (!warning_issued)
11907         {
11908           warning (_("File transfers from remote targets can be slow."
11909                      " Use \"set sysroot\" to access files locally"
11910                      " instead."));
11911           warning_issued = 1;
11912         }
11913     }
11914
11915   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
11916     return -1;
11917
11918   remote_buffer_add_string (&p, &left, "vFile:open:");
11919
11920   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
11921                            strlen (filename));
11922   remote_buffer_add_string (&p, &left, ",");
11923
11924   remote_buffer_add_int (&p, &left, flags);
11925   remote_buffer_add_string (&p, &left, ",");
11926
11927   remote_buffer_add_int (&p, &left, mode);
11928
11929   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_open,
11930                                      remote_errno, NULL, NULL);
11931 }
11932
11933 int
11934 remote_target::fileio_open (struct inferior *inf, const char *filename,
11935                             int flags, int mode, int warn_if_slow,
11936                             int *remote_errno)
11937 {
11938   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
11939                              remote_errno);
11940 }
11941
11942 /* Implementation of to_fileio_pwrite.  */
11943
11944 int
11945 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
11946                                      ULONGEST offset, int *remote_errno)
11947 {
11948   struct remote_state *rs = get_remote_state ();
11949   char *p = rs->buf.data ();
11950   int left = get_remote_packet_size ();
11951   int out_len;
11952
11953   rs->readahead_cache.invalidate_fd (fd);
11954
11955   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
11956
11957   remote_buffer_add_int (&p, &left, fd);
11958   remote_buffer_add_string (&p, &left, ",");
11959
11960   remote_buffer_add_int (&p, &left, offset);
11961   remote_buffer_add_string (&p, &left, ",");
11962
11963   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
11964                              (get_remote_packet_size ()
11965                               - (p - rs->buf.data ())));
11966
11967   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pwrite,
11968                                      remote_errno, NULL, NULL);
11969 }
11970
11971 int
11972 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
11973                               ULONGEST offset, int *remote_errno)
11974 {
11975   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
11976 }
11977
11978 /* Helper for the implementation of to_fileio_pread.  Read the file
11979    from the remote side with vFile:pread.  */
11980
11981 int
11982 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
11983                                           ULONGEST offset, int *remote_errno)
11984 {
11985   struct remote_state *rs = get_remote_state ();
11986   char *p = rs->buf.data ();
11987   char *attachment;
11988   int left = get_remote_packet_size ();
11989   int ret, attachment_len;
11990   int read_len;
11991
11992   remote_buffer_add_string (&p, &left, "vFile:pread:");
11993
11994   remote_buffer_add_int (&p, &left, fd);
11995   remote_buffer_add_string (&p, &left, ",");
11996
11997   remote_buffer_add_int (&p, &left, len);
11998   remote_buffer_add_string (&p, &left, ",");
11999
12000   remote_buffer_add_int (&p, &left, offset);
12001
12002   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_pread,
12003                                     remote_errno, &attachment,
12004                                     &attachment_len);
12005
12006   if (ret < 0)
12007     return ret;
12008
12009   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12010                                     read_buf, len);
12011   if (read_len != ret)
12012     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12013
12014   return ret;
12015 }
12016
12017 /* See declaration.h.  */
12018
12019 int
12020 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12021                         ULONGEST offset)
12022 {
12023   if (this->fd == fd
12024       && this->offset <= offset
12025       && offset < this->offset + this->bufsize)
12026     {
12027       ULONGEST max = this->offset + this->bufsize;
12028
12029       if (offset + len > max)
12030         len = max - offset;
12031
12032       memcpy (read_buf, this->buf + offset - this->offset, len);
12033       return len;
12034     }
12035
12036   return 0;
12037 }
12038
12039 /* Implementation of to_fileio_pread.  */
12040
12041 int
12042 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12043                                     ULONGEST offset, int *remote_errno)
12044 {
12045   int ret;
12046   struct remote_state *rs = get_remote_state ();
12047   readahead_cache *cache = &rs->readahead_cache;
12048
12049   ret = cache->pread (fd, read_buf, len, offset);
12050   if (ret > 0)
12051     {
12052       cache->hit_count++;
12053
12054       if (remote_debug)
12055         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12056                             pulongest (cache->hit_count));
12057       return ret;
12058     }
12059
12060   cache->miss_count++;
12061   if (remote_debug)
12062     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12063                         pulongest (cache->miss_count));
12064
12065   cache->fd = fd;
12066   cache->offset = offset;
12067   cache->bufsize = get_remote_packet_size ();
12068   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12069
12070   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12071                                    cache->offset, remote_errno);
12072   if (ret <= 0)
12073     {
12074       cache->invalidate_fd (fd);
12075       return ret;
12076     }
12077
12078   cache->bufsize = ret;
12079   return cache->pread (fd, read_buf, len, offset);
12080 }
12081
12082 int
12083 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12084                              ULONGEST offset, int *remote_errno)
12085 {
12086   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12087 }
12088
12089 /* Implementation of to_fileio_close.  */
12090
12091 int
12092 remote_target::remote_hostio_close (int fd, int *remote_errno)
12093 {
12094   struct remote_state *rs = get_remote_state ();
12095   char *p = rs->buf.data ();
12096   int left = get_remote_packet_size () - 1;
12097
12098   rs->readahead_cache.invalidate_fd (fd);
12099
12100   remote_buffer_add_string (&p, &left, "vFile:close:");
12101
12102   remote_buffer_add_int (&p, &left, fd);
12103
12104   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_close,
12105                                      remote_errno, NULL, NULL);
12106 }
12107
12108 int
12109 remote_target::fileio_close (int fd, int *remote_errno)
12110 {
12111   return remote_hostio_close (fd, remote_errno);
12112 }
12113
12114 /* Implementation of to_fileio_unlink.  */
12115
12116 int
12117 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12118                                      int *remote_errno)
12119 {
12120   struct remote_state *rs = get_remote_state ();
12121   char *p = rs->buf.data ();
12122   int left = get_remote_packet_size () - 1;
12123
12124   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12125     return -1;
12126
12127   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12128
12129   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12130                            strlen (filename));
12131
12132   return remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_unlink,
12133                                      remote_errno, NULL, NULL);
12134 }
12135
12136 int
12137 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12138                               int *remote_errno)
12139 {
12140   return remote_hostio_unlink (inf, filename, remote_errno);
12141 }
12142
12143 /* Implementation of to_fileio_readlink.  */
12144
12145 gdb::optional<std::string>
12146 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12147                                 int *remote_errno)
12148 {
12149   struct remote_state *rs = get_remote_state ();
12150   char *p = rs->buf.data ();
12151   char *attachment;
12152   int left = get_remote_packet_size ();
12153   int len, attachment_len;
12154   int read_len;
12155
12156   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12157     return {};
12158
12159   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12160
12161   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12162                            strlen (filename));
12163
12164   len = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_readlink,
12165                                     remote_errno, &attachment,
12166                                     &attachment_len);
12167
12168   if (len < 0)
12169     return {};
12170
12171   std::string ret (len, '\0');
12172
12173   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12174                                     (gdb_byte *) &ret[0], len);
12175   if (read_len != len)
12176     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12177
12178   return ret;
12179 }
12180
12181 /* Implementation of to_fileio_fstat.  */
12182
12183 int
12184 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12185 {
12186   struct remote_state *rs = get_remote_state ();
12187   char *p = rs->buf.data ();
12188   int left = get_remote_packet_size ();
12189   int attachment_len, ret;
12190   char *attachment;
12191   struct fio_stat fst;
12192   int read_len;
12193
12194   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12195
12196   remote_buffer_add_int (&p, &left, fd);
12197
12198   ret = remote_hostio_send_command (p - rs->buf.data (), PACKET_vFile_fstat,
12199                                     remote_errno, &attachment,
12200                                     &attachment_len);
12201   if (ret < 0)
12202     {
12203       if (*remote_errno != FILEIO_ENOSYS)
12204         return ret;
12205
12206       /* Strictly we should return -1, ENOSYS here, but when
12207          "set sysroot remote:" was implemented in August 2008
12208          BFD's need for a stat function was sidestepped with
12209          this hack.  This was not remedied until March 2015
12210          so we retain the previous behavior to avoid breaking
12211          compatibility.
12212
12213          Note that the memset is a March 2015 addition; older
12214          GDBs set st_size *and nothing else* so the structure
12215          would have garbage in all other fields.  This might
12216          break something but retaining the previous behavior
12217          here would be just too wrong.  */
12218
12219       memset (st, 0, sizeof (struct stat));
12220       st->st_size = INT_MAX;
12221       return 0;
12222     }
12223
12224   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12225                                     (gdb_byte *) &fst, sizeof (fst));
12226
12227   if (read_len != ret)
12228     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12229
12230   if (read_len != sizeof (fst))
12231     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12232            read_len, (int) sizeof (fst));
12233
12234   remote_fileio_to_host_stat (&fst, st);
12235
12236   return 0;
12237 }
12238
12239 /* Implementation of to_filesystem_is_local.  */
12240
12241 bool
12242 remote_target::filesystem_is_local ()
12243 {
12244   /* Valgrind GDB presents itself as a remote target but works
12245      on the local filesystem: it does not implement remote get
12246      and users are not expected to set a sysroot.  To handle
12247      this case we treat the remote filesystem as local if the
12248      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12249      does not support vFile:open.  */
12250   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12251     {
12252       enum packet_support ps = packet_support (PACKET_vFile_open);
12253
12254       if (ps == PACKET_SUPPORT_UNKNOWN)
12255         {
12256           int fd, remote_errno;
12257
12258           /* Try opening a file to probe support.  The supplied
12259              filename is irrelevant, we only care about whether
12260              the stub recognizes the packet or not.  */
12261           fd = remote_hostio_open (NULL, "just probing",
12262                                    FILEIO_O_RDONLY, 0700, 0,
12263                                    &remote_errno);
12264
12265           if (fd >= 0)
12266             remote_hostio_close (fd, &remote_errno);
12267
12268           ps = packet_support (PACKET_vFile_open);
12269         }
12270
12271       if (ps == PACKET_DISABLE)
12272         {
12273           static int warning_issued = 0;
12274
12275           if (!warning_issued)
12276             {
12277               warning (_("remote target does not support file"
12278                          " transfer, attempting to access files"
12279                          " from local filesystem."));
12280               warning_issued = 1;
12281             }
12282
12283           return true;
12284         }
12285     }
12286
12287   return false;
12288 }
12289
12290 static int
12291 remote_fileio_errno_to_host (int errnum)
12292 {
12293   switch (errnum)
12294     {
12295       case FILEIO_EPERM:
12296         return EPERM;
12297       case FILEIO_ENOENT:
12298         return ENOENT;
12299       case FILEIO_EINTR:
12300         return EINTR;
12301       case FILEIO_EIO:
12302         return EIO;
12303       case FILEIO_EBADF:
12304         return EBADF;
12305       case FILEIO_EACCES:
12306         return EACCES;
12307       case FILEIO_EFAULT:
12308         return EFAULT;
12309       case FILEIO_EBUSY:
12310         return EBUSY;
12311       case FILEIO_EEXIST:
12312         return EEXIST;
12313       case FILEIO_ENODEV:
12314         return ENODEV;
12315       case FILEIO_ENOTDIR:
12316         return ENOTDIR;
12317       case FILEIO_EISDIR:
12318         return EISDIR;
12319       case FILEIO_EINVAL:
12320         return EINVAL;
12321       case FILEIO_ENFILE:
12322         return ENFILE;
12323       case FILEIO_EMFILE:
12324         return EMFILE;
12325       case FILEIO_EFBIG:
12326         return EFBIG;
12327       case FILEIO_ENOSPC:
12328         return ENOSPC;
12329       case FILEIO_ESPIPE:
12330         return ESPIPE;
12331       case FILEIO_EROFS:
12332         return EROFS;
12333       case FILEIO_ENOSYS:
12334         return ENOSYS;
12335       case FILEIO_ENAMETOOLONG:
12336         return ENAMETOOLONG;
12337     }
12338   return -1;
12339 }
12340
12341 static char *
12342 remote_hostio_error (int errnum)
12343 {
12344   int host_error = remote_fileio_errno_to_host (errnum);
12345
12346   if (host_error == -1)
12347     error (_("Unknown remote I/O error %d"), errnum);
12348   else
12349     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12350 }
12351
12352 /* A RAII wrapper around a remote file descriptor.  */
12353
12354 class scoped_remote_fd
12355 {
12356 public:
12357   scoped_remote_fd (remote_target *remote, int fd)
12358     : m_remote (remote), m_fd (fd)
12359   {
12360   }
12361
12362   ~scoped_remote_fd ()
12363   {
12364     if (m_fd != -1)
12365       {
12366         try
12367           {
12368             int remote_errno;
12369             m_remote->remote_hostio_close (m_fd, &remote_errno);
12370           }
12371         catch (...)
12372           {
12373             /* Swallow exception before it escapes the dtor.  If
12374                something goes wrong, likely the connection is gone,
12375                and there's nothing else that can be done.  */
12376           }
12377       }
12378   }
12379
12380   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12381
12382   /* Release ownership of the file descriptor, and return it.  */
12383   ATTRIBUTE_UNUSED_RESULT int release () noexcept
12384   {
12385     int fd = m_fd;
12386     m_fd = -1;
12387     return fd;
12388   }
12389
12390   /* Return the owned file descriptor.  */
12391   int get () const noexcept
12392   {
12393     return m_fd;
12394   }
12395
12396 private:
12397   /* The remote target.  */
12398   remote_target *m_remote;
12399
12400   /* The owned remote I/O file descriptor.  */
12401   int m_fd;
12402 };
12403
12404 void
12405 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12406 {
12407   remote_target *remote = get_current_remote_target ();
12408
12409   if (remote == nullptr)
12410     error (_("command can only be used with remote target"));
12411
12412   remote->remote_file_put (local_file, remote_file, from_tty);
12413 }
12414
12415 void
12416 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12417                                 int from_tty)
12418 {
12419   int retcode, remote_errno, bytes, io_size;
12420   int bytes_in_buffer;
12421   int saw_eof;
12422   ULONGEST offset;
12423
12424   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12425   if (file == NULL)
12426     perror_with_name (local_file);
12427
12428   scoped_remote_fd fd
12429     (this, remote_hostio_open (NULL,
12430                                remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12431                                              | FILEIO_O_TRUNC),
12432                                0700, 0, &remote_errno));
12433   if (fd.get () == -1)
12434     remote_hostio_error (remote_errno);
12435
12436   /* Send up to this many bytes at once.  They won't all fit in the
12437      remote packet limit, so we'll transfer slightly fewer.  */
12438   io_size = get_remote_packet_size ();
12439   gdb::byte_vector buffer (io_size);
12440
12441   bytes_in_buffer = 0;
12442   saw_eof = 0;
12443   offset = 0;
12444   while (bytes_in_buffer || !saw_eof)
12445     {
12446       if (!saw_eof)
12447         {
12448           bytes = fread (buffer.data () + bytes_in_buffer, 1,
12449                          io_size - bytes_in_buffer,
12450                          file.get ());
12451           if (bytes == 0)
12452             {
12453               if (ferror (file.get ()))
12454                 error (_("Error reading %s."), local_file);
12455               else
12456                 {
12457                   /* EOF.  Unless there is something still in the
12458                      buffer from the last iteration, we are done.  */
12459                   saw_eof = 1;
12460                   if (bytes_in_buffer == 0)
12461                     break;
12462                 }
12463             }
12464         }
12465       else
12466         bytes = 0;
12467
12468       bytes += bytes_in_buffer;
12469       bytes_in_buffer = 0;
12470
12471       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12472                                       offset, &remote_errno);
12473
12474       if (retcode < 0)
12475         remote_hostio_error (remote_errno);
12476       else if (retcode == 0)
12477         error (_("Remote write of %d bytes returned 0!"), bytes);
12478       else if (retcode < bytes)
12479         {
12480           /* Short write.  Save the rest of the read data for the next
12481              write.  */
12482           bytes_in_buffer = bytes - retcode;
12483           memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12484         }
12485
12486       offset += retcode;
12487     }
12488
12489   if (remote_hostio_close (fd.release (), &remote_errno))
12490     remote_hostio_error (remote_errno);
12491
12492   if (from_tty)
12493     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12494 }
12495
12496 void
12497 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12498 {
12499   remote_target *remote = get_current_remote_target ();
12500
12501   if (remote == nullptr)
12502     error (_("command can only be used with remote target"));
12503
12504   remote->remote_file_get (remote_file, local_file, from_tty);
12505 }
12506
12507 void
12508 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12509                                 int from_tty)
12510 {
12511   int remote_errno, bytes, io_size;
12512   ULONGEST offset;
12513
12514   scoped_remote_fd fd
12515     (this, remote_hostio_open (NULL,
12516                                remote_file, FILEIO_O_RDONLY, 0, 0,
12517                                &remote_errno));
12518   if (fd.get () == -1)
12519     remote_hostio_error (remote_errno);
12520
12521   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12522   if (file == NULL)
12523     perror_with_name (local_file);
12524
12525   /* Send up to this many bytes at once.  They won't all fit in the
12526      remote packet limit, so we'll transfer slightly fewer.  */
12527   io_size = get_remote_packet_size ();
12528   gdb::byte_vector buffer (io_size);
12529
12530   offset = 0;
12531   while (1)
12532     {
12533       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12534                                    &remote_errno);
12535       if (bytes == 0)
12536         /* Success, but no bytes, means end-of-file.  */
12537         break;
12538       if (bytes == -1)
12539         remote_hostio_error (remote_errno);
12540
12541       offset += bytes;
12542
12543       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12544       if (bytes == 0)
12545         perror_with_name (local_file);
12546     }
12547
12548   if (remote_hostio_close (fd.release (), &remote_errno))
12549     remote_hostio_error (remote_errno);
12550
12551   if (from_tty)
12552     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12553 }
12554
12555 void
12556 remote_file_delete (const char *remote_file, int from_tty)
12557 {
12558   remote_target *remote = get_current_remote_target ();
12559
12560   if (remote == nullptr)
12561     error (_("command can only be used with remote target"));
12562
12563   remote->remote_file_delete (remote_file, from_tty);
12564 }
12565
12566 void
12567 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12568 {
12569   int retcode, remote_errno;
12570
12571   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12572   if (retcode == -1)
12573     remote_hostio_error (remote_errno);
12574
12575   if (from_tty)
12576     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12577 }
12578
12579 static void
12580 remote_put_command (const char *args, int from_tty)
12581 {
12582   if (args == NULL)
12583     error_no_arg (_("file to put"));
12584
12585   gdb_argv argv (args);
12586   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12587     error (_("Invalid parameters to remote put"));
12588
12589   remote_file_put (argv[0], argv[1], from_tty);
12590 }
12591
12592 static void
12593 remote_get_command (const char *args, int from_tty)
12594 {
12595   if (args == NULL)
12596     error_no_arg (_("file to get"));
12597
12598   gdb_argv argv (args);
12599   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12600     error (_("Invalid parameters to remote get"));
12601
12602   remote_file_get (argv[0], argv[1], from_tty);
12603 }
12604
12605 static void
12606 remote_delete_command (const char *args, int from_tty)
12607 {
12608   if (args == NULL)
12609     error_no_arg (_("file to delete"));
12610
12611   gdb_argv argv (args);
12612   if (argv[0] == NULL || argv[1] != NULL)
12613     error (_("Invalid parameters to remote delete"));
12614
12615   remote_file_delete (argv[0], from_tty);
12616 }
12617
12618 static void
12619 remote_command (const char *args, int from_tty)
12620 {
12621   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12622 }
12623
12624 bool
12625 remote_target::can_execute_reverse ()
12626 {
12627   if (packet_support (PACKET_bs) == PACKET_ENABLE
12628       || packet_support (PACKET_bc) == PACKET_ENABLE)
12629     return true;
12630   else
12631     return false;
12632 }
12633
12634 bool
12635 remote_target::supports_non_stop ()
12636 {
12637   return true;
12638 }
12639
12640 bool
12641 remote_target::supports_disable_randomization ()
12642 {
12643   /* Only supported in extended mode.  */
12644   return false;
12645 }
12646
12647 bool
12648 remote_target::supports_multi_process ()
12649 {
12650   struct remote_state *rs = get_remote_state ();
12651
12652   return remote_multi_process_p (rs);
12653 }
12654
12655 static int
12656 remote_supports_cond_tracepoints ()
12657 {
12658   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12659 }
12660
12661 bool
12662 remote_target::supports_evaluation_of_breakpoint_conditions ()
12663 {
12664   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12665 }
12666
12667 static int
12668 remote_supports_fast_tracepoints ()
12669 {
12670   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12671 }
12672
12673 static int
12674 remote_supports_static_tracepoints ()
12675 {
12676   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12677 }
12678
12679 static int
12680 remote_supports_install_in_trace ()
12681 {
12682   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12683 }
12684
12685 bool
12686 remote_target::supports_enable_disable_tracepoint ()
12687 {
12688   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12689           == PACKET_ENABLE);
12690 }
12691
12692 bool
12693 remote_target::supports_string_tracing ()
12694 {
12695   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12696 }
12697
12698 bool
12699 remote_target::can_run_breakpoint_commands ()
12700 {
12701   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12702 }
12703
12704 void
12705 remote_target::trace_init ()
12706 {
12707   struct remote_state *rs = get_remote_state ();
12708
12709   putpkt ("QTinit");
12710   remote_get_noisy_reply ();
12711   if (strcmp (rs->buf.data (), "OK") != 0)
12712     error (_("Target does not support this command."));
12713 }
12714
12715 /* Recursive routine to walk through command list including loops, and
12716    download packets for each command.  */
12717
12718 void
12719 remote_target::remote_download_command_source (int num, ULONGEST addr,
12720                                                struct command_line *cmds)
12721 {
12722   struct remote_state *rs = get_remote_state ();
12723   struct command_line *cmd;
12724
12725   for (cmd = cmds; cmd; cmd = cmd->next)
12726     {
12727       QUIT;     /* Allow user to bail out with ^C.  */
12728       strcpy (rs->buf.data (), "QTDPsrc:");
12729       encode_source_string (num, addr, "cmd", cmd->line,
12730                             rs->buf.data () + strlen (rs->buf.data ()),
12731                             rs->buf.size () - strlen (rs->buf.data ()));
12732       putpkt (rs->buf);
12733       remote_get_noisy_reply ();
12734       if (strcmp (rs->buf.data (), "OK"))
12735         warning (_("Target does not support source download."));
12736
12737       if (cmd->control_type == while_control
12738           || cmd->control_type == while_stepping_control)
12739         {
12740           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12741
12742           QUIT; /* Allow user to bail out with ^C.  */
12743           strcpy (rs->buf.data (), "QTDPsrc:");
12744           encode_source_string (num, addr, "cmd", "end",
12745                                 rs->buf.data () + strlen (rs->buf.data ()),
12746                                 rs->buf.size () - strlen (rs->buf.data ()));
12747           putpkt (rs->buf);
12748           remote_get_noisy_reply ();
12749           if (strcmp (rs->buf.data (), "OK"))
12750             warning (_("Target does not support source download."));
12751         }
12752     }
12753 }
12754
12755 void
12756 remote_target::download_tracepoint (struct bp_location *loc)
12757 {
12758   CORE_ADDR tpaddr;
12759   char addrbuf[40];
12760   std::vector<std::string> tdp_actions;
12761   std::vector<std::string> stepping_actions;
12762   char *pkt;
12763   struct breakpoint *b = loc->owner;
12764   struct tracepoint *t = (struct tracepoint *) b;
12765   struct remote_state *rs = get_remote_state ();
12766   int ret;
12767   const char *err_msg = _("Tracepoint packet too large for target.");
12768   size_t size_left;
12769
12770   /* We use a buffer other than rs->buf because we'll build strings
12771      across multiple statements, and other statements in between could
12772      modify rs->buf.  */
12773   gdb::char_vector buf (get_remote_packet_size ());
12774
12775   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12776
12777   tpaddr = loc->address;
12778   sprintf_vma (addrbuf, tpaddr);
12779   ret = snprintf (buf.data (), buf.size (), "QTDP:%x:%s:%c:%lx:%x",
12780                   b->number, addrbuf, /* address */
12781                   (b->enable_state == bp_enabled ? 'E' : 'D'),
12782                   t->step_count, t->pass_count);
12783
12784   if (ret < 0 || ret >= buf.size ())
12785     error ("%s", err_msg);
12786
12787   /* Fast tracepoints are mostly handled by the target, but we can
12788      tell the target how big of an instruction block should be moved
12789      around.  */
12790   if (b->type == bp_fast_tracepoint)
12791     {
12792       /* Only test for support at download time; we may not know
12793          target capabilities at definition time.  */
12794       if (remote_supports_fast_tracepoints ())
12795         {
12796           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12797                                                 NULL))
12798             {
12799               size_left = buf.size () - strlen (buf.data ());
12800               ret = snprintf (buf.data () + strlen (buf.data ()),
12801                               size_left, ":F%x",
12802                               gdb_insn_length (loc->gdbarch, tpaddr));
12803
12804               if (ret < 0 || ret >= size_left)
12805                 error ("%s", err_msg);
12806             }
12807           else
12808             /* If it passed validation at definition but fails now,
12809                something is very wrong.  */
12810             internal_error (__FILE__, __LINE__,
12811                             _("Fast tracepoint not "
12812                               "valid during download"));
12813         }
12814       else
12815         /* Fast tracepoints are functionally identical to regular
12816            tracepoints, so don't take lack of support as a reason to
12817            give up on the trace run.  */
12818         warning (_("Target does not support fast tracepoints, "
12819                    "downloading %d as regular tracepoint"), b->number);
12820     }
12821   else if (b->type == bp_static_tracepoint)
12822     {
12823       /* Only test for support at download time; we may not know
12824          target capabilities at definition time.  */
12825       if (remote_supports_static_tracepoints ())
12826         {
12827           struct static_tracepoint_marker marker;
12828
12829           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12830             {
12831               size_left = buf.size () - strlen (buf.data ());
12832               ret = snprintf (buf.data () + strlen (buf.data ()),
12833                               size_left, ":S");
12834
12835               if (ret < 0 || ret >= size_left)
12836                 error ("%s", err_msg);
12837             }
12838           else
12839             error (_("Static tracepoint not valid during download"));
12840         }
12841       else
12842         /* Fast tracepoints are functionally identical to regular
12843            tracepoints, so don't take lack of support as a reason
12844            to give up on the trace run.  */
12845         error (_("Target does not support static tracepoints"));
12846     }
12847   /* If the tracepoint has a conditional, make it into an agent
12848      expression and append to the definition.  */
12849   if (loc->cond)
12850     {
12851       /* Only test support at download time, we may not know target
12852          capabilities at definition time.  */
12853       if (remote_supports_cond_tracepoints ())
12854         {
12855           agent_expr_up aexpr = gen_eval_for_expr (tpaddr,
12856                                                    loc->cond.get ());
12857
12858           size_left = buf.size () - strlen (buf.data ());
12859
12860           ret = snprintf (buf.data () + strlen (buf.data ()),
12861                           size_left, ":X%x,", aexpr->len);
12862
12863           if (ret < 0 || ret >= size_left)
12864             error ("%s", err_msg);
12865
12866           size_left = buf.size () - strlen (buf.data ());
12867
12868           /* Two bytes to encode each aexpr byte, plus the terminating
12869              null byte.  */
12870           if (aexpr->len * 2 + 1 > size_left)
12871             error ("%s", err_msg);
12872
12873           pkt = buf.data () + strlen (buf.data ());
12874
12875           for (int ndx = 0; ndx < aexpr->len; ++ndx)
12876             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
12877           *pkt = '\0';
12878         }
12879       else
12880         warning (_("Target does not support conditional tracepoints, "
12881                    "ignoring tp %d cond"), b->number);
12882     }
12883
12884   if (b->commands || *default_collect)
12885     {
12886       size_left = buf.size () - strlen (buf.data ());
12887
12888       ret = snprintf (buf.data () + strlen (buf.data ()),
12889                       size_left, "-");
12890
12891       if (ret < 0 || ret >= size_left)
12892         error ("%s", err_msg);
12893     }
12894
12895   putpkt (buf.data ());
12896   remote_get_noisy_reply ();
12897   if (strcmp (rs->buf.data (), "OK"))
12898     error (_("Target does not support tracepoints."));
12899
12900   /* do_single_steps (t); */
12901   for (auto action_it = tdp_actions.begin ();
12902        action_it != tdp_actions.end (); action_it++)
12903     {
12904       QUIT;     /* Allow user to bail out with ^C.  */
12905
12906       bool has_more = ((action_it + 1) != tdp_actions.end ()
12907                        || !stepping_actions.empty ());
12908
12909       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%c",
12910                       b->number, addrbuf, /* address */
12911                       action_it->c_str (),
12912                       has_more ? '-' : 0);
12913
12914       if (ret < 0 || ret >= buf.size ())
12915         error ("%s", err_msg);
12916
12917       putpkt (buf.data ());
12918       remote_get_noisy_reply ();
12919       if (strcmp (rs->buf.data (), "OK"))
12920         error (_("Error on target while setting tracepoints."));
12921     }
12922
12923   for (auto action_it = stepping_actions.begin ();
12924        action_it != stepping_actions.end (); action_it++)
12925     {
12926       QUIT;     /* Allow user to bail out with ^C.  */
12927
12928       bool is_first = action_it == stepping_actions.begin ();
12929       bool has_more = (action_it + 1) != stepping_actions.end ();
12930
12931       ret = snprintf (buf.data (), buf.size (), "QTDP:-%x:%s:%s%s%s",
12932                       b->number, addrbuf, /* address */
12933                       is_first ? "S" : "",
12934                       action_it->c_str (),
12935                       has_more ? "-" : "");
12936
12937       if (ret < 0 || ret >= buf.size ())
12938         error ("%s", err_msg);
12939
12940       putpkt (buf.data ());
12941       remote_get_noisy_reply ();
12942       if (strcmp (rs->buf.data (), "OK"))
12943         error (_("Error on target while setting tracepoints."));
12944     }
12945
12946   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
12947     {
12948       if (b->location != NULL)
12949         {
12950           ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
12951
12952           if (ret < 0 || ret >= buf.size ())
12953             error ("%s", err_msg);
12954
12955           encode_source_string (b->number, loc->address, "at",
12956                                 event_location_to_string (b->location.get ()),
12957                                 buf.data () + strlen (buf.data ()),
12958                                 buf.size () - strlen (buf.data ()));
12959           putpkt (buf.data ());
12960           remote_get_noisy_reply ();
12961           if (strcmp (rs->buf.data (), "OK"))
12962             warning (_("Target does not support source download."));
12963         }
12964       if (b->cond_string)
12965         {
12966           ret = snprintf (buf.data (), buf.size (), "QTDPsrc:");
12967
12968           if (ret < 0 || ret >= buf.size ())
12969             error ("%s", err_msg);
12970
12971           encode_source_string (b->number, loc->address,
12972                                 "cond", b->cond_string,
12973                                 buf.data () + strlen (buf.data ()),
12974                                 buf.size () - strlen (buf.data ()));
12975           putpkt (buf.data ());
12976           remote_get_noisy_reply ();
12977           if (strcmp (rs->buf.data (), "OK"))
12978             warning (_("Target does not support source download."));
12979         }
12980       remote_download_command_source (b->number, loc->address,
12981                                       breakpoint_commands (b));
12982     }
12983 }
12984
12985 bool
12986 remote_target::can_download_tracepoint ()
12987 {
12988   struct remote_state *rs = get_remote_state ();
12989   struct trace_status *ts;
12990   int status;
12991
12992   /* Don't try to install tracepoints until we've relocated our
12993      symbols, and fetched and merged the target's tracepoint list with
12994      ours.  */
12995   if (rs->starting_up)
12996     return false;
12997
12998   ts = current_trace_status ();
12999   status = get_trace_status (ts);
13000
13001   if (status == -1 || !ts->running_known || !ts->running)
13002     return false;
13003
13004   /* If we are in a tracing experiment, but remote stub doesn't support
13005      installing tracepoint in trace, we have to return.  */
13006   if (!remote_supports_install_in_trace ())
13007     return false;
13008
13009   return true;
13010 }
13011
13012
13013 void
13014 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13015 {
13016   struct remote_state *rs = get_remote_state ();
13017   char *p;
13018
13019   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDV:%x:%s:%x:",
13020              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13021              tsv.builtin);
13022   p = rs->buf.data () + strlen (rs->buf.data ());
13023   if ((p - rs->buf.data ()) + tsv.name.length () * 2
13024       >= get_remote_packet_size ())
13025     error (_("Trace state variable name too long for tsv definition packet"));
13026   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13027   *p++ = '\0';
13028   putpkt (rs->buf);
13029   remote_get_noisy_reply ();
13030   if (rs->buf[0] == '\0')
13031     error (_("Target does not support this command."));
13032   if (strcmp (rs->buf.data (), "OK") != 0)
13033     error (_("Error on target while downloading trace state variable."));
13034 }
13035
13036 void
13037 remote_target::enable_tracepoint (struct bp_location *location)
13038 {
13039   struct remote_state *rs = get_remote_state ();
13040   char addr_buf[40];
13041
13042   sprintf_vma (addr_buf, location->address);
13043   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTEnable:%x:%s",
13044              location->owner->number, addr_buf);
13045   putpkt (rs->buf);
13046   remote_get_noisy_reply ();
13047   if (rs->buf[0] == '\0')
13048     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13049   if (strcmp (rs->buf.data (), "OK") != 0)
13050     error (_("Error on target while enabling tracepoint."));
13051 }
13052
13053 void
13054 remote_target::disable_tracepoint (struct bp_location *location)
13055 {
13056   struct remote_state *rs = get_remote_state ();
13057   char addr_buf[40];
13058
13059   sprintf_vma (addr_buf, location->address);
13060   xsnprintf (rs->buf.data (), get_remote_packet_size (), "QTDisable:%x:%s",
13061              location->owner->number, addr_buf);
13062   putpkt (rs->buf);
13063   remote_get_noisy_reply ();
13064   if (rs->buf[0] == '\0')
13065     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13066   if (strcmp (rs->buf.data (), "OK") != 0)
13067     error (_("Error on target while disabling tracepoint."));
13068 }
13069
13070 void
13071 remote_target::trace_set_readonly_regions ()
13072 {
13073   asection *s;
13074   bfd *abfd = NULL;
13075   bfd_size_type size;
13076   bfd_vma vma;
13077   int anysecs = 0;
13078   int offset = 0;
13079
13080   if (!exec_bfd)
13081     return;                     /* No information to give.  */
13082
13083   struct remote_state *rs = get_remote_state ();
13084
13085   strcpy (rs->buf.data (), "QTro");
13086   offset = strlen (rs->buf.data ());
13087   for (s = exec_bfd->sections; s; s = s->next)
13088     {
13089       char tmp1[40], tmp2[40];
13090       int sec_length;
13091
13092       if ((s->flags & SEC_LOAD) == 0 ||
13093       /*  (s->flags & SEC_CODE) == 0 || */
13094           (s->flags & SEC_READONLY) == 0)
13095         continue;
13096
13097       anysecs = 1;
13098       vma = bfd_get_section_vma (abfd, s);
13099       size = bfd_get_section_size (s);
13100       sprintf_vma (tmp1, vma);
13101       sprintf_vma (tmp2, vma + size);
13102       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13103       if (offset + sec_length + 1 > rs->buf.size ())
13104         {
13105           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13106             warning (_("\
13107 Too many sections for read-only sections definition packet."));
13108           break;
13109         }
13110       xsnprintf (rs->buf.data () + offset, rs->buf.size () - offset, ":%s,%s",
13111                  tmp1, tmp2);
13112       offset += sec_length;
13113     }
13114   if (anysecs)
13115     {
13116       putpkt (rs->buf);
13117       getpkt (&rs->buf, 0);
13118     }
13119 }
13120
13121 void
13122 remote_target::trace_start ()
13123 {
13124   struct remote_state *rs = get_remote_state ();
13125
13126   putpkt ("QTStart");
13127   remote_get_noisy_reply ();
13128   if (rs->buf[0] == '\0')
13129     error (_("Target does not support this command."));
13130   if (strcmp (rs->buf.data (), "OK") != 0)
13131     error (_("Bogus reply from target: %s"), rs->buf.data ());
13132 }
13133
13134 int
13135 remote_target::get_trace_status (struct trace_status *ts)
13136 {
13137   /* Initialize it just to avoid a GCC false warning.  */
13138   char *p = NULL;
13139   /* FIXME we need to get register block size some other way.  */
13140   extern int trace_regblock_size;
13141   enum packet_result result;
13142   struct remote_state *rs = get_remote_state ();
13143
13144   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13145     return -1;
13146
13147   trace_regblock_size
13148     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13149
13150   putpkt ("qTStatus");
13151
13152   try
13153     {
13154       p = remote_get_noisy_reply ();
13155     }
13156   catch (const gdb_exception_error &ex)
13157     {
13158       if (ex.error != TARGET_CLOSE_ERROR)
13159         {
13160           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13161           return -1;
13162         }
13163       throw;
13164     }
13165
13166   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13167
13168   /* If the remote target doesn't do tracing, flag it.  */
13169   if (result == PACKET_UNKNOWN)
13170     return -1;
13171
13172   /* We're working with a live target.  */
13173   ts->filename = NULL;
13174
13175   if (*p++ != 'T')
13176     error (_("Bogus trace status reply from target: %s"), rs->buf.data ());
13177
13178   /* Function 'parse_trace_status' sets default value of each field of
13179      'ts' at first, so we don't have to do it here.  */
13180   parse_trace_status (p, ts);
13181
13182   return ts->running;
13183 }
13184
13185 void
13186 remote_target::get_tracepoint_status (struct breakpoint *bp,
13187                                       struct uploaded_tp *utp)
13188 {
13189   struct remote_state *rs = get_remote_state ();
13190   char *reply;
13191   struct bp_location *loc;
13192   struct tracepoint *tp = (struct tracepoint *) bp;
13193   size_t size = get_remote_packet_size ();
13194
13195   if (tp)
13196     {
13197       tp->hit_count = 0;
13198       tp->traceframe_usage = 0;
13199       for (loc = tp->loc; loc; loc = loc->next)
13200         {
13201           /* If the tracepoint was never downloaded, don't go asking for
13202              any status.  */
13203           if (tp->number_on_target == 0)
13204             continue;
13205           xsnprintf (rs->buf.data (), size, "qTP:%x:%s", tp->number_on_target,
13206                      phex_nz (loc->address, 0));
13207           putpkt (rs->buf);
13208           reply = remote_get_noisy_reply ();
13209           if (reply && *reply)
13210             {
13211               if (*reply == 'V')
13212                 parse_tracepoint_status (reply + 1, bp, utp);
13213             }
13214         }
13215     }
13216   else if (utp)
13217     {
13218       utp->hit_count = 0;
13219       utp->traceframe_usage = 0;
13220       xsnprintf (rs->buf.data (), size, "qTP:%x:%s", utp->number,
13221                  phex_nz (utp->addr, 0));
13222       putpkt (rs->buf);
13223       reply = remote_get_noisy_reply ();
13224       if (reply && *reply)
13225         {
13226           if (*reply == 'V')
13227             parse_tracepoint_status (reply + 1, bp, utp);
13228         }
13229     }
13230 }
13231
13232 void
13233 remote_target::trace_stop ()
13234 {
13235   struct remote_state *rs = get_remote_state ();
13236
13237   putpkt ("QTStop");
13238   remote_get_noisy_reply ();
13239   if (rs->buf[0] == '\0')
13240     error (_("Target does not support this command."));
13241   if (strcmp (rs->buf.data (), "OK") != 0)
13242     error (_("Bogus reply from target: %s"), rs->buf.data ());
13243 }
13244
13245 int
13246 remote_target::trace_find (enum trace_find_type type, int num,
13247                            CORE_ADDR addr1, CORE_ADDR addr2,
13248                            int *tpp)
13249 {
13250   struct remote_state *rs = get_remote_state ();
13251   char *endbuf = rs->buf.data () + get_remote_packet_size ();
13252   char *p, *reply;
13253   int target_frameno = -1, target_tracept = -1;
13254
13255   /* Lookups other than by absolute frame number depend on the current
13256      trace selected, so make sure it is correct on the remote end
13257      first.  */
13258   if (type != tfind_number)
13259     set_remote_traceframe ();
13260
13261   p = rs->buf.data ();
13262   strcpy (p, "QTFrame:");
13263   p = strchr (p, '\0');
13264   switch (type)
13265     {
13266     case tfind_number:
13267       xsnprintf (p, endbuf - p, "%x", num);
13268       break;
13269     case tfind_pc:
13270       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13271       break;
13272     case tfind_tp:
13273       xsnprintf (p, endbuf - p, "tdp:%x", num);
13274       break;
13275     case tfind_range:
13276       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13277                  phex_nz (addr2, 0));
13278       break;
13279     case tfind_outside:
13280       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13281                  phex_nz (addr2, 0));
13282       break;
13283     default:
13284       error (_("Unknown trace find type %d"), type);
13285     }
13286
13287   putpkt (rs->buf);
13288   reply = remote_get_noisy_reply ();
13289   if (*reply == '\0')
13290     error (_("Target does not support this command."));
13291
13292   while (reply && *reply)
13293     switch (*reply)
13294       {
13295       case 'F':
13296         p = ++reply;
13297         target_frameno = (int) strtol (p, &reply, 16);
13298         if (reply == p)
13299           error (_("Unable to parse trace frame number"));
13300         /* Don't update our remote traceframe number cache on failure
13301            to select a remote traceframe.  */
13302         if (target_frameno == -1)
13303           return -1;
13304         break;
13305       case 'T':
13306         p = ++reply;
13307         target_tracept = (int) strtol (p, &reply, 16);
13308         if (reply == p)
13309           error (_("Unable to parse tracepoint number"));
13310         break;
13311       case 'O':         /* "OK"? */
13312         if (reply[1] == 'K' && reply[2] == '\0')
13313           reply += 2;
13314         else
13315           error (_("Bogus reply from target: %s"), reply);
13316         break;
13317       default:
13318         error (_("Bogus reply from target: %s"), reply);
13319       }
13320   if (tpp)
13321     *tpp = target_tracept;
13322
13323   rs->remote_traceframe_number = target_frameno;
13324   return target_frameno;
13325 }
13326
13327 bool
13328 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13329 {
13330   struct remote_state *rs = get_remote_state ();
13331   char *reply;
13332   ULONGEST uval;
13333
13334   set_remote_traceframe ();
13335
13336   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTV:%x", tsvnum);
13337   putpkt (rs->buf);
13338   reply = remote_get_noisy_reply ();
13339   if (reply && *reply)
13340     {
13341       if (*reply == 'V')
13342         {
13343           unpack_varlen_hex (reply + 1, &uval);
13344           *val = (LONGEST) uval;
13345           return true;
13346         }
13347     }
13348   return false;
13349 }
13350
13351 int
13352 remote_target::save_trace_data (const char *filename)
13353 {
13354   struct remote_state *rs = get_remote_state ();
13355   char *p, *reply;
13356
13357   p = rs->buf.data ();
13358   strcpy (p, "QTSave:");
13359   p += strlen (p);
13360   if ((p - rs->buf.data ()) + strlen (filename) * 2
13361       >= get_remote_packet_size ())
13362     error (_("Remote file name too long for trace save packet"));
13363   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13364   *p++ = '\0';
13365   putpkt (rs->buf);
13366   reply = remote_get_noisy_reply ();
13367   if (*reply == '\0')
13368     error (_("Target does not support this command."));
13369   if (strcmp (reply, "OK") != 0)
13370     error (_("Bogus reply from target: %s"), reply);
13371   return 0;
13372 }
13373
13374 /* This is basically a memory transfer, but needs to be its own packet
13375    because we don't know how the target actually organizes its trace
13376    memory, plus we want to be able to ask for as much as possible, but
13377    not be unhappy if we don't get as much as we ask for.  */
13378
13379 LONGEST
13380 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13381 {
13382   struct remote_state *rs = get_remote_state ();
13383   char *reply;
13384   char *p;
13385   int rslt;
13386
13387   p = rs->buf.data ();
13388   strcpy (p, "qTBuffer:");
13389   p += strlen (p);
13390   p += hexnumstr (p, offset);
13391   *p++ = ',';
13392   p += hexnumstr (p, len);
13393   *p++ = '\0';
13394
13395   putpkt (rs->buf);
13396   reply = remote_get_noisy_reply ();
13397   if (reply && *reply)
13398     {
13399       /* 'l' by itself means we're at the end of the buffer and
13400          there is nothing more to get.  */
13401       if (*reply == 'l')
13402         return 0;
13403
13404       /* Convert the reply into binary.  Limit the number of bytes to
13405          convert according to our passed-in buffer size, rather than
13406          what was returned in the packet; if the target is
13407          unexpectedly generous and gives us a bigger reply than we
13408          asked for, we don't want to crash.  */
13409       rslt = hex2bin (reply, buf, len);
13410       return rslt;
13411     }
13412
13413   /* Something went wrong, flag as an error.  */
13414   return -1;
13415 }
13416
13417 void
13418 remote_target::set_disconnected_tracing (int val)
13419 {
13420   struct remote_state *rs = get_remote_state ();
13421
13422   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13423     {
13424       char *reply;
13425
13426       xsnprintf (rs->buf.data (), get_remote_packet_size (),
13427                  "QTDisconnected:%x", val);
13428       putpkt (rs->buf);
13429       reply = remote_get_noisy_reply ();
13430       if (*reply == '\0')
13431         error (_("Target does not support this command."));
13432       if (strcmp (reply, "OK") != 0)
13433         error (_("Bogus reply from target: %s"), reply);
13434     }
13435   else if (val)
13436     warning (_("Target does not support disconnected tracing."));
13437 }
13438
13439 int
13440 remote_target::core_of_thread (ptid_t ptid)
13441 {
13442   struct thread_info *info = find_thread_ptid (ptid);
13443
13444   if (info != NULL && info->priv != NULL)
13445     return get_remote_thread_info (info)->core;
13446
13447   return -1;
13448 }
13449
13450 void
13451 remote_target::set_circular_trace_buffer (int val)
13452 {
13453   struct remote_state *rs = get_remote_state ();
13454   char *reply;
13455
13456   xsnprintf (rs->buf.data (), get_remote_packet_size (),
13457              "QTBuffer:circular:%x", val);
13458   putpkt (rs->buf);
13459   reply = remote_get_noisy_reply ();
13460   if (*reply == '\0')
13461     error (_("Target does not support this command."));
13462   if (strcmp (reply, "OK") != 0)
13463     error (_("Bogus reply from target: %s"), reply);
13464 }
13465
13466 traceframe_info_up
13467 remote_target::traceframe_info ()
13468 {
13469   gdb::optional<gdb::char_vector> text
13470     = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13471                             NULL);
13472   if (text)
13473     return parse_traceframe_info (text->data ());
13474
13475   return NULL;
13476 }
13477
13478 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13479    instruction on which a fast tracepoint may be placed.  Returns -1
13480    if the packet is not supported, and 0 if the minimum instruction
13481    length is unknown.  */
13482
13483 int
13484 remote_target::get_min_fast_tracepoint_insn_len ()
13485 {
13486   struct remote_state *rs = get_remote_state ();
13487   char *reply;
13488
13489   /* If we're not debugging a process yet, the IPA can't be
13490      loaded.  */
13491   if (!target_has_execution)
13492     return 0;
13493
13494   /* Make sure the remote is pointing at the right process.  */
13495   set_general_process ();
13496
13497   xsnprintf (rs->buf.data (), get_remote_packet_size (), "qTMinFTPILen");
13498   putpkt (rs->buf);
13499   reply = remote_get_noisy_reply ();
13500   if (*reply == '\0')
13501     return -1;
13502   else
13503     {
13504       ULONGEST min_insn_len;
13505
13506       unpack_varlen_hex (reply, &min_insn_len);
13507
13508       return (int) min_insn_len;
13509     }
13510 }
13511
13512 void
13513 remote_target::set_trace_buffer_size (LONGEST val)
13514 {
13515   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13516     {
13517       struct remote_state *rs = get_remote_state ();
13518       char *buf = rs->buf.data ();
13519       char *endbuf = buf + get_remote_packet_size ();
13520       enum packet_result result;
13521
13522       gdb_assert (val >= 0 || val == -1);
13523       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13524       /* Send -1 as literal "-1" to avoid host size dependency.  */
13525       if (val < 0)
13526         {
13527           *buf++ = '-';
13528           buf += hexnumstr (buf, (ULONGEST) -val);
13529         }
13530       else
13531         buf += hexnumstr (buf, (ULONGEST) val);
13532
13533       putpkt (rs->buf);
13534       remote_get_noisy_reply ();
13535       result = packet_ok (rs->buf,
13536                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13537
13538       if (result != PACKET_OK)
13539         warning (_("Bogus reply from target: %s"), rs->buf.data ());
13540     }
13541 }
13542
13543 bool
13544 remote_target::set_trace_notes (const char *user, const char *notes,
13545                                 const char *stop_notes)
13546 {
13547   struct remote_state *rs = get_remote_state ();
13548   char *reply;
13549   char *buf = rs->buf.data ();
13550   char *endbuf = buf + get_remote_packet_size ();
13551   int nbytes;
13552
13553   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13554   if (user)
13555     {
13556       buf += xsnprintf (buf, endbuf - buf, "user:");
13557       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13558       buf += 2 * nbytes;
13559       *buf++ = ';';
13560     }
13561   if (notes)
13562     {
13563       buf += xsnprintf (buf, endbuf - buf, "notes:");
13564       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13565       buf += 2 * nbytes;
13566       *buf++ = ';';
13567     }
13568   if (stop_notes)
13569     {
13570       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13571       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13572       buf += 2 * nbytes;
13573       *buf++ = ';';
13574     }
13575   /* Ensure the buffer is terminated.  */
13576   *buf = '\0';
13577
13578   putpkt (rs->buf);
13579   reply = remote_get_noisy_reply ();
13580   if (*reply == '\0')
13581     return false;
13582
13583   if (strcmp (reply, "OK") != 0)
13584     error (_("Bogus reply from target: %s"), reply);
13585
13586   return true;
13587 }
13588
13589 bool
13590 remote_target::use_agent (bool use)
13591 {
13592   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13593     {
13594       struct remote_state *rs = get_remote_state ();
13595
13596       /* If the stub supports QAgent.  */
13597       xsnprintf (rs->buf.data (), get_remote_packet_size (), "QAgent:%d", use);
13598       putpkt (rs->buf);
13599       getpkt (&rs->buf, 0);
13600
13601       if (strcmp (rs->buf.data (), "OK") == 0)
13602         {
13603           ::use_agent = use;
13604           return true;
13605         }
13606     }
13607
13608   return false;
13609 }
13610
13611 bool
13612 remote_target::can_use_agent ()
13613 {
13614   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13615 }
13616
13617 struct btrace_target_info
13618 {
13619   /* The ptid of the traced thread.  */
13620   ptid_t ptid;
13621
13622   /* The obtained branch trace configuration.  */
13623   struct btrace_config conf;
13624 };
13625
13626 /* Reset our idea of our target's btrace configuration.  */
13627
13628 static void
13629 remote_btrace_reset (remote_state *rs)
13630 {
13631   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13632 }
13633
13634 /* Synchronize the configuration with the target.  */
13635
13636 void
13637 remote_target::btrace_sync_conf (const btrace_config *conf)
13638 {
13639   struct packet_config *packet;
13640   struct remote_state *rs;
13641   char *buf, *pos, *endbuf;
13642
13643   rs = get_remote_state ();
13644   buf = rs->buf.data ();
13645   endbuf = buf + get_remote_packet_size ();
13646
13647   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13648   if (packet_config_support (packet) == PACKET_ENABLE
13649       && conf->bts.size != rs->btrace_config.bts.size)
13650     {
13651       pos = buf;
13652       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13653                         conf->bts.size);
13654
13655       putpkt (buf);
13656       getpkt (&rs->buf, 0);
13657
13658       if (packet_ok (buf, packet) == PACKET_ERROR)
13659         {
13660           if (buf[0] == 'E' && buf[1] == '.')
13661             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13662           else
13663             error (_("Failed to configure the BTS buffer size."));
13664         }
13665
13666       rs->btrace_config.bts.size = conf->bts.size;
13667     }
13668
13669   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13670   if (packet_config_support (packet) == PACKET_ENABLE
13671       && conf->pt.size != rs->btrace_config.pt.size)
13672     {
13673       pos = buf;
13674       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13675                         conf->pt.size);
13676
13677       putpkt (buf);
13678       getpkt (&rs->buf, 0);
13679
13680       if (packet_ok (buf, packet) == PACKET_ERROR)
13681         {
13682           if (buf[0] == 'E' && buf[1] == '.')
13683             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13684           else
13685             error (_("Failed to configure the trace buffer size."));
13686         }
13687
13688       rs->btrace_config.pt.size = conf->pt.size;
13689     }
13690 }
13691
13692 /* Read the current thread's btrace configuration from the target and
13693    store it into CONF.  */
13694
13695 static void
13696 btrace_read_config (struct btrace_config *conf)
13697 {
13698   gdb::optional<gdb::char_vector> xml
13699     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13700   if (xml)
13701     parse_xml_btrace_conf (conf, xml->data ());
13702 }
13703
13704 /* Maybe reopen target btrace.  */
13705
13706 void
13707 remote_target::remote_btrace_maybe_reopen ()
13708 {
13709   struct remote_state *rs = get_remote_state ();
13710   int btrace_target_pushed = 0;
13711 #if !defined (HAVE_LIBIPT)
13712   int warned = 0;
13713 #endif
13714
13715   scoped_restore_current_thread restore_thread;
13716
13717   for (thread_info *tp : all_non_exited_threads ())
13718     {
13719       set_general_thread (tp->ptid);
13720
13721       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13722       btrace_read_config (&rs->btrace_config);
13723
13724       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13725         continue;
13726
13727 #if !defined (HAVE_LIBIPT)
13728       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13729         {
13730           if (!warned)
13731             {
13732               warned = 1;
13733               warning (_("Target is recording using Intel Processor Trace "
13734                          "but support was disabled at compile time."));
13735             }
13736
13737           continue;
13738         }
13739 #endif /* !defined (HAVE_LIBIPT) */
13740
13741       /* Push target, once, but before anything else happens.  This way our
13742          changes to the threads will be cleaned up by unpushing the target
13743          in case btrace_read_config () throws.  */
13744       if (!btrace_target_pushed)
13745         {
13746           btrace_target_pushed = 1;
13747           record_btrace_push_target ();
13748           printf_filtered (_("Target is recording using %s.\n"),
13749                            btrace_format_string (rs->btrace_config.format));
13750         }
13751
13752       tp->btrace.target = XCNEW (struct btrace_target_info);
13753       tp->btrace.target->ptid = tp->ptid;
13754       tp->btrace.target->conf = rs->btrace_config;
13755     }
13756 }
13757
13758 /* Enable branch tracing.  */
13759
13760 struct btrace_target_info *
13761 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13762 {
13763   struct btrace_target_info *tinfo = NULL;
13764   struct packet_config *packet = NULL;
13765   struct remote_state *rs = get_remote_state ();
13766   char *buf = rs->buf.data ();
13767   char *endbuf = buf + get_remote_packet_size ();
13768
13769   switch (conf->format)
13770     {
13771       case BTRACE_FORMAT_BTS:
13772         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13773         break;
13774
13775       case BTRACE_FORMAT_PT:
13776         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13777         break;
13778     }
13779
13780   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13781     error (_("Target does not support branch tracing."));
13782
13783   btrace_sync_conf (conf);
13784
13785   set_general_thread (ptid);
13786
13787   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13788   putpkt (rs->buf);
13789   getpkt (&rs->buf, 0);
13790
13791   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13792     {
13793       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13794         error (_("Could not enable branch tracing for %s: %s"),
13795                target_pid_to_str (ptid).c_str (), &rs->buf[2]);
13796       else
13797         error (_("Could not enable branch tracing for %s."),
13798                target_pid_to_str (ptid).c_str ());
13799     }
13800
13801   tinfo = XCNEW (struct btrace_target_info);
13802   tinfo->ptid = ptid;
13803
13804   /* If we fail to read the configuration, we lose some information, but the
13805      tracing itself is not impacted.  */
13806   try
13807     {
13808       btrace_read_config (&tinfo->conf);
13809     }
13810   catch (const gdb_exception_error &err)
13811     {
13812       if (err.message != NULL)
13813         warning ("%s", err.what ());
13814     }
13815
13816   return tinfo;
13817 }
13818
13819 /* Disable branch tracing.  */
13820
13821 void
13822 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13823 {
13824   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13825   struct remote_state *rs = get_remote_state ();
13826   char *buf = rs->buf.data ();
13827   char *endbuf = buf + get_remote_packet_size ();
13828
13829   if (packet_config_support (packet) != PACKET_ENABLE)
13830     error (_("Target does not support branch tracing."));
13831
13832   set_general_thread (tinfo->ptid);
13833
13834   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13835   putpkt (rs->buf);
13836   getpkt (&rs->buf, 0);
13837
13838   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13839     {
13840       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13841         error (_("Could not disable branch tracing for %s: %s"),
13842                target_pid_to_str (tinfo->ptid).c_str (), &rs->buf[2]);
13843       else
13844         error (_("Could not disable branch tracing for %s."),
13845                target_pid_to_str (tinfo->ptid).c_str ());
13846     }
13847
13848   xfree (tinfo);
13849 }
13850
13851 /* Teardown branch tracing.  */
13852
13853 void
13854 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13855 {
13856   /* We must not talk to the target during teardown.  */
13857   xfree (tinfo);
13858 }
13859
13860 /* Read the branch trace.  */
13861
13862 enum btrace_error
13863 remote_target::read_btrace (struct btrace_data *btrace,
13864                             struct btrace_target_info *tinfo,
13865                             enum btrace_read_type type)
13866 {
13867   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13868   const char *annex;
13869
13870   if (packet_config_support (packet) != PACKET_ENABLE)
13871     error (_("Target does not support branch tracing."));
13872
13873 #if !defined(HAVE_LIBEXPAT)
13874   error (_("Cannot process branch tracing result. XML parsing not supported."));
13875 #endif
13876
13877   switch (type)
13878     {
13879     case BTRACE_READ_ALL:
13880       annex = "all";
13881       break;
13882     case BTRACE_READ_NEW:
13883       annex = "new";
13884       break;
13885     case BTRACE_READ_DELTA:
13886       annex = "delta";
13887       break;
13888     default:
13889       internal_error (__FILE__, __LINE__,
13890                       _("Bad branch tracing read type: %u."),
13891                       (unsigned int) type);
13892     }
13893
13894   gdb::optional<gdb::char_vector> xml
13895     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
13896   if (!xml)
13897     return BTRACE_ERR_UNKNOWN;
13898
13899   parse_xml_btrace (btrace, xml->data ());
13900
13901   return BTRACE_ERR_NONE;
13902 }
13903
13904 const struct btrace_config *
13905 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
13906 {
13907   return &tinfo->conf;
13908 }
13909
13910 bool
13911 remote_target::augmented_libraries_svr4_read ()
13912 {
13913   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
13914           == PACKET_ENABLE);
13915 }
13916
13917 /* Implementation of to_load.  */
13918
13919 void
13920 remote_target::load (const char *name, int from_tty)
13921 {
13922   generic_load (name, from_tty);
13923 }
13924
13925 /* Accepts an integer PID; returns a string representing a file that
13926    can be opened on the remote side to get the symbols for the child
13927    process.  Returns NULL if the operation is not supported.  */
13928
13929 char *
13930 remote_target::pid_to_exec_file (int pid)
13931 {
13932   static gdb::optional<gdb::char_vector> filename;
13933   struct inferior *inf;
13934   char *annex = NULL;
13935
13936   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
13937     return NULL;
13938
13939   inf = find_inferior_pid (pid);
13940   if (inf == NULL)
13941     internal_error (__FILE__, __LINE__,
13942                     _("not currently attached to process %d"), pid);
13943
13944   if (!inf->fake_pid_p)
13945     {
13946       const int annex_size = 9;
13947
13948       annex = (char *) alloca (annex_size);
13949       xsnprintf (annex, annex_size, "%x", pid);
13950     }
13951
13952   filename = target_read_stralloc (current_top_target (),
13953                                    TARGET_OBJECT_EXEC_FILE, annex);
13954
13955   return filename ? filename->data () : nullptr;
13956 }
13957
13958 /* Implement the to_can_do_single_step target_ops method.  */
13959
13960 int
13961 remote_target::can_do_single_step ()
13962 {
13963   /* We can only tell whether target supports single step or not by
13964      supported s and S vCont actions if the stub supports vContSupported
13965      feature.  If the stub doesn't support vContSupported feature,
13966      we have conservatively to think target doesn't supports single
13967      step.  */
13968   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
13969     {
13970       struct remote_state *rs = get_remote_state ();
13971
13972       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
13973         remote_vcont_probe ();
13974
13975       return rs->supports_vCont.s && rs->supports_vCont.S;
13976     }
13977   else
13978     return 0;
13979 }
13980
13981 /* Implementation of the to_execution_direction method for the remote
13982    target.  */
13983
13984 enum exec_direction_kind
13985 remote_target::execution_direction ()
13986 {
13987   struct remote_state *rs = get_remote_state ();
13988
13989   return rs->last_resume_exec_dir;
13990 }
13991
13992 /* Return pointer to the thread_info struct which corresponds to
13993    THREAD_HANDLE (having length HANDLE_LEN).  */
13994
13995 thread_info *
13996 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
13997                                              int handle_len,
13998                                              inferior *inf)
13999 {
14000   for (thread_info *tp : all_non_exited_threads ())
14001     {
14002       remote_thread_info *priv = get_remote_thread_info (tp);
14003
14004       if (tp->inf == inf && priv != NULL)
14005         {
14006           if (handle_len != priv->thread_handle.size ())
14007             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14008                    handle_len, priv->thread_handle.size ());
14009           if (memcmp (thread_handle, priv->thread_handle.data (),
14010                       handle_len) == 0)
14011             return tp;
14012         }
14013     }
14014
14015   return NULL;
14016 }
14017
14018 gdb::byte_vector
14019 remote_target::thread_info_to_thread_handle (struct thread_info *tp)
14020 {
14021   remote_thread_info *priv = get_remote_thread_info (tp);
14022   return priv->thread_handle;
14023 }
14024
14025 bool
14026 remote_target::can_async_p ()
14027 {
14028   struct remote_state *rs = get_remote_state ();
14029
14030   /* We don't go async if the user has explicitly prevented it with the
14031      "maint set target-async" command.  */
14032   if (!target_async_permitted)
14033     return false;
14034
14035   /* We're async whenever the serial device is.  */
14036   return serial_can_async_p (rs->remote_desc);
14037 }
14038
14039 bool
14040 remote_target::is_async_p ()
14041 {
14042   struct remote_state *rs = get_remote_state ();
14043
14044   if (!target_async_permitted)
14045     /* We only enable async when the user specifically asks for it.  */
14046     return false;
14047
14048   /* We're async whenever the serial device is.  */
14049   return serial_is_async_p (rs->remote_desc);
14050 }
14051
14052 /* Pass the SERIAL event on and up to the client.  One day this code
14053    will be able to delay notifying the client of an event until the
14054    point where an entire packet has been received.  */
14055
14056 static serial_event_ftype remote_async_serial_handler;
14057
14058 static void
14059 remote_async_serial_handler (struct serial *scb, void *context)
14060 {
14061   /* Don't propogate error information up to the client.  Instead let
14062      the client find out about the error by querying the target.  */
14063   inferior_event_handler (INF_REG_EVENT, NULL);
14064 }
14065
14066 static void
14067 remote_async_inferior_event_handler (gdb_client_data data)
14068 {
14069   inferior_event_handler (INF_REG_EVENT, data);
14070 }
14071
14072 void
14073 remote_target::async (int enable)
14074 {
14075   struct remote_state *rs = get_remote_state ();
14076
14077   if (enable)
14078     {
14079       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14080
14081       /* If there are pending events in the stop reply queue tell the
14082          event loop to process them.  */
14083       if (!rs->stop_reply_queue.empty ())
14084         mark_async_event_handler (rs->remote_async_inferior_event_token);
14085       /* For simplicity, below we clear the pending events token
14086          without remembering whether it is marked, so here we always
14087          mark it.  If there's actually no pending notification to
14088          process, this ends up being a no-op (other than a spurious
14089          event-loop wakeup).  */
14090       if (target_is_non_stop_p ())
14091         mark_async_event_handler (rs->notif_state->get_pending_events_token);
14092     }
14093   else
14094     {
14095       serial_async (rs->remote_desc, NULL, NULL);
14096       /* If the core is disabling async, it doesn't want to be
14097          disturbed with target events.  Clear all async event sources
14098          too.  */
14099       clear_async_event_handler (rs->remote_async_inferior_event_token);
14100       if (target_is_non_stop_p ())
14101         clear_async_event_handler (rs->notif_state->get_pending_events_token);
14102     }
14103 }
14104
14105 /* Implementation of the to_thread_events method.  */
14106
14107 void
14108 remote_target::thread_events (int enable)
14109 {
14110   struct remote_state *rs = get_remote_state ();
14111   size_t size = get_remote_packet_size ();
14112
14113   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14114     return;
14115
14116   xsnprintf (rs->buf.data (), size, "QThreadEvents:%x", enable ? 1 : 0);
14117   putpkt (rs->buf);
14118   getpkt (&rs->buf, 0);
14119
14120   switch (packet_ok (rs->buf,
14121                      &remote_protocol_packets[PACKET_QThreadEvents]))
14122     {
14123     case PACKET_OK:
14124       if (strcmp (rs->buf.data (), "OK") != 0)
14125         error (_("Remote refused setting thread events: %s"), rs->buf.data ());
14126       break;
14127     case PACKET_ERROR:
14128       warning (_("Remote failure reply: %s"), rs->buf.data ());
14129       break;
14130     case PACKET_UNKNOWN:
14131       break;
14132     }
14133 }
14134
14135 static void
14136 set_remote_cmd (const char *args, int from_tty)
14137 {
14138   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14139 }
14140
14141 static void
14142 show_remote_cmd (const char *args, int from_tty)
14143 {
14144   /* We can't just use cmd_show_list here, because we want to skip
14145      the redundant "show remote Z-packet" and the legacy aliases.  */
14146   struct cmd_list_element *list = remote_show_cmdlist;
14147   struct ui_out *uiout = current_uiout;
14148
14149   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14150   for (; list != NULL; list = list->next)
14151     if (strcmp (list->name, "Z-packet") == 0)
14152       continue;
14153     else if (list->type == not_set_cmd)
14154       /* Alias commands are exactly like the original, except they
14155          don't have the normal type.  */
14156       continue;
14157     else
14158       {
14159         ui_out_emit_tuple option_emitter (uiout, "option");
14160
14161         uiout->field_string ("name", list->name);
14162         uiout->text (":  ");
14163         if (list->type == show_cmd)
14164           do_show_command (NULL, from_tty, list);
14165         else
14166           cmd_func (list, NULL, from_tty);
14167       }
14168 }
14169
14170
14171 /* Function to be called whenever a new objfile (shlib) is detected.  */
14172 static void
14173 remote_new_objfile (struct objfile *objfile)
14174 {
14175   remote_target *remote = get_current_remote_target ();
14176
14177   if (remote != NULL)                   /* Have a remote connection.  */
14178     remote->remote_check_symbols ();
14179 }
14180
14181 /* Pull all the tracepoints defined on the target and create local
14182    data structures representing them.  We don't want to create real
14183    tracepoints yet, we don't want to mess up the user's existing
14184    collection.  */
14185   
14186 int
14187 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14188 {
14189   struct remote_state *rs = get_remote_state ();
14190   char *p;
14191
14192   /* Ask for a first packet of tracepoint definition.  */
14193   putpkt ("qTfP");
14194   getpkt (&rs->buf, 0);
14195   p = rs->buf.data ();
14196   while (*p && *p != 'l')
14197     {
14198       parse_tracepoint_definition (p, utpp);
14199       /* Ask for another packet of tracepoint definition.  */
14200       putpkt ("qTsP");
14201       getpkt (&rs->buf, 0);
14202       p = rs->buf.data ();
14203     }
14204   return 0;
14205 }
14206
14207 int
14208 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14209 {
14210   struct remote_state *rs = get_remote_state ();
14211   char *p;
14212
14213   /* Ask for a first packet of variable definition.  */
14214   putpkt ("qTfV");
14215   getpkt (&rs->buf, 0);
14216   p = rs->buf.data ();
14217   while (*p && *p != 'l')
14218     {
14219       parse_tsv_definition (p, utsvp);
14220       /* Ask for another packet of variable definition.  */
14221       putpkt ("qTsV");
14222       getpkt (&rs->buf, 0);
14223       p = rs->buf.data ();
14224     }
14225   return 0;
14226 }
14227
14228 /* The "set/show range-stepping" show hook.  */
14229
14230 static void
14231 show_range_stepping (struct ui_file *file, int from_tty,
14232                      struct cmd_list_element *c,
14233                      const char *value)
14234 {
14235   fprintf_filtered (file,
14236                     _("Debugger's willingness to use range stepping "
14237                       "is %s.\n"), value);
14238 }
14239
14240 /* Return true if the vCont;r action is supported by the remote
14241    stub.  */
14242
14243 bool
14244 remote_target::vcont_r_supported ()
14245 {
14246   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14247     remote_vcont_probe ();
14248
14249   return (packet_support (PACKET_vCont) == PACKET_ENABLE
14250           && get_remote_state ()->supports_vCont.r);
14251 }
14252
14253 /* The "set/show range-stepping" set hook.  */
14254
14255 static void
14256 set_range_stepping (const char *ignore_args, int from_tty,
14257                     struct cmd_list_element *c)
14258 {
14259   /* When enabling, check whether range stepping is actually supported
14260      by the target, and warn if not.  */
14261   if (use_range_stepping)
14262     {
14263       remote_target *remote = get_current_remote_target ();
14264       if (remote == NULL
14265           || !remote->vcont_r_supported ())
14266         warning (_("Range stepping is not supported by the current target"));
14267     }
14268 }
14269
14270 void
14271 _initialize_remote (void)
14272 {
14273   struct cmd_list_element *cmd;
14274   const char *cmd_name;
14275
14276   /* architecture specific data */
14277   remote_g_packet_data_handle =
14278     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14279
14280   remote_pspace_data
14281     = register_program_space_data_with_cleanup (NULL,
14282                                                 remote_pspace_data_cleanup);
14283
14284   add_target (remote_target_info, remote_target::open);
14285   add_target (extended_remote_target_info, extended_remote_target::open);
14286
14287   /* Hook into new objfile notification.  */
14288   gdb::observers::new_objfile.attach (remote_new_objfile);
14289
14290 #if 0
14291   init_remote_threadtests ();
14292 #endif
14293
14294   /* set/show remote ...  */
14295
14296   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14297 Remote protocol specific variables\n\
14298 Configure various remote-protocol specific variables such as\n\
14299 the packets being used"),
14300                   &remote_set_cmdlist, "set remote ",
14301                   0 /* allow-unknown */, &setlist);
14302   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14303 Remote protocol specific variables\n\
14304 Configure various remote-protocol specific variables such as\n\
14305 the packets being used"),
14306                   &remote_show_cmdlist, "show remote ",
14307                   0 /* allow-unknown */, &showlist);
14308
14309   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14310 Compare section data on target to the exec file.\n\
14311 Argument is a single section name (default: all loaded sections).\n\
14312 To compare only read-only loaded sections, specify the -r option."),
14313            &cmdlist);
14314
14315   add_cmd ("packet", class_maintenance, packet_command, _("\
14316 Send an arbitrary packet to a remote target.\n\
14317    maintenance packet TEXT\n\
14318 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14319 this command sends the string TEXT to the inferior, and displays the\n\
14320 response packet.  GDB supplies the initial `$' character, and the\n\
14321 terminating `#' character and checksum."),
14322            &maintenancelist);
14323
14324   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14325 Set whether to send break if interrupted."), _("\
14326 Show whether to send break if interrupted."), _("\
14327 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14328                            set_remotebreak, show_remotebreak,
14329                            &setlist, &showlist);
14330   cmd_name = "remotebreak";
14331   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14332   deprecate_cmd (cmd, "set remote interrupt-sequence");
14333   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14334   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14335   deprecate_cmd (cmd, "show remote interrupt-sequence");
14336
14337   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14338                         interrupt_sequence_modes, &interrupt_sequence_mode,
14339                         _("\
14340 Set interrupt sequence to remote target."), _("\
14341 Show interrupt sequence to remote target."), _("\
14342 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14343                         NULL, show_interrupt_sequence,
14344                         &remote_set_cmdlist,
14345                         &remote_show_cmdlist);
14346
14347   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14348                            &interrupt_on_connect, _("\
14349 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14350 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14351 If set, interrupt sequence is sent to remote target."),
14352                            NULL, NULL,
14353                            &remote_set_cmdlist, &remote_show_cmdlist);
14354
14355   /* Install commands for configuring memory read/write packets.  */
14356
14357   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14358 Set the maximum number of bytes per memory write packet (deprecated)."),
14359            &setlist);
14360   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14361 Show the maximum number of bytes per memory write packet (deprecated)."),
14362            &showlist);
14363   add_cmd ("memory-write-packet-size", no_class,
14364            set_memory_write_packet_size, _("\
14365 Set the maximum number of bytes per memory-write packet.\n\
14366 Specify the number of bytes in a packet or 0 (zero) for the\n\
14367 default packet size.  The actual limit is further reduced\n\
14368 dependent on the target.  Specify ``fixed'' to disable the\n\
14369 further restriction and ``limit'' to enable that restriction."),
14370            &remote_set_cmdlist);
14371   add_cmd ("memory-read-packet-size", no_class,
14372            set_memory_read_packet_size, _("\
14373 Set the maximum number of bytes per memory-read packet.\n\
14374 Specify the number of bytes in a packet or 0 (zero) for the\n\
14375 default packet size.  The actual limit is further reduced\n\
14376 dependent on the target.  Specify ``fixed'' to disable the\n\
14377 further restriction and ``limit'' to enable that restriction."),
14378            &remote_set_cmdlist);
14379   add_cmd ("memory-write-packet-size", no_class,
14380            show_memory_write_packet_size,
14381            _("Show the maximum number of bytes per memory-write packet."),
14382            &remote_show_cmdlist);
14383   add_cmd ("memory-read-packet-size", no_class,
14384            show_memory_read_packet_size,
14385            _("Show the maximum number of bytes per memory-read packet."),
14386            &remote_show_cmdlist);
14387
14388   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-limit", no_class,
14389                             &remote_hw_watchpoint_limit, _("\
14390 Set the maximum number of target hardware watchpoints."), _("\
14391 Show the maximum number of target hardware watchpoints."), _("\
14392 Specify \"unlimited\" for unlimited hardware watchpoints."),
14393                             NULL, show_hardware_watchpoint_limit,
14394                             &remote_set_cmdlist,
14395                             &remote_show_cmdlist);
14396   add_setshow_zuinteger_unlimited_cmd ("hardware-watchpoint-length-limit",
14397                             no_class,
14398                             &remote_hw_watchpoint_length_limit, _("\
14399 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14400 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14401 Specify \"unlimited\" to allow watchpoints of unlimited size."),
14402                             NULL, show_hardware_watchpoint_length_limit,
14403                             &remote_set_cmdlist, &remote_show_cmdlist);
14404   add_setshow_zuinteger_unlimited_cmd ("hardware-breakpoint-limit", no_class,
14405                             &remote_hw_breakpoint_limit, _("\
14406 Set the maximum number of target hardware breakpoints."), _("\
14407 Show the maximum number of target hardware breakpoints."), _("\
14408 Specify \"unlimited\" for unlimited hardware breakpoints."),
14409                             NULL, show_hardware_breakpoint_limit,
14410                             &remote_set_cmdlist, &remote_show_cmdlist);
14411
14412   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14413                              &remote_address_size, _("\
14414 Set the maximum size of the address (in bits) in a memory packet."), _("\
14415 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14416                              NULL,
14417                              NULL, /* FIXME: i18n: */
14418                              &setlist, &showlist);
14419
14420   init_all_packet_configs ();
14421
14422   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14423                          "X", "binary-download", 1);
14424
14425   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14426                          "vCont", "verbose-resume", 0);
14427
14428   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14429                          "QPassSignals", "pass-signals", 0);
14430
14431   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14432                          "QCatchSyscalls", "catch-syscalls", 0);
14433
14434   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14435                          "QProgramSignals", "program-signals", 0);
14436
14437   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14438                          "QSetWorkingDir", "set-working-dir", 0);
14439
14440   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14441                          "QStartupWithShell", "startup-with-shell", 0);
14442
14443   add_packet_config_cmd (&remote_protocol_packets
14444                          [PACKET_QEnvironmentHexEncoded],
14445                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14446                          0);
14447
14448   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14449                          "QEnvironmentReset", "environment-reset",
14450                          0);
14451
14452   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14453                          "QEnvironmentUnset", "environment-unset",
14454                          0);
14455
14456   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14457                          "qSymbol", "symbol-lookup", 0);
14458
14459   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14460                          "P", "set-register", 1);
14461
14462   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14463                          "p", "fetch-register", 1);
14464
14465   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14466                          "Z0", "software-breakpoint", 0);
14467
14468   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14469                          "Z1", "hardware-breakpoint", 0);
14470
14471   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14472                          "Z2", "write-watchpoint", 0);
14473
14474   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14475                          "Z3", "read-watchpoint", 0);
14476
14477   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14478                          "Z4", "access-watchpoint", 0);
14479
14480   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14481                          "qXfer:auxv:read", "read-aux-vector", 0);
14482
14483   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14484                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14485
14486   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14487                          "qXfer:features:read", "target-features", 0);
14488
14489   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14490                          "qXfer:libraries:read", "library-info", 0);
14491
14492   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14493                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14494
14495   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14496                          "qXfer:memory-map:read", "memory-map", 0);
14497
14498   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14499                          "qXfer:spu:read", "read-spu-object", 0);
14500
14501   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14502                          "qXfer:spu:write", "write-spu-object", 0);
14503
14504   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14505                         "qXfer:osdata:read", "osdata", 0);
14506
14507   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14508                          "qXfer:threads:read", "threads", 0);
14509
14510   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14511                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14512
14513   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14514                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14515
14516   add_packet_config_cmd
14517     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14518      "qXfer:traceframe-info:read", "traceframe-info", 0);
14519
14520   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14521                          "qXfer:uib:read", "unwind-info-block", 0);
14522
14523   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14524                          "qGetTLSAddr", "get-thread-local-storage-address",
14525                          0);
14526
14527   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14528                          "qGetTIBAddr", "get-thread-information-block-address",
14529                          0);
14530
14531   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14532                          "bc", "reverse-continue", 0);
14533
14534   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14535                          "bs", "reverse-step", 0);
14536
14537   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14538                          "qSupported", "supported-packets", 0);
14539
14540   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14541                          "qSearch:memory", "search-memory", 0);
14542
14543   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14544                          "qTStatus", "trace-status", 0);
14545
14546   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14547                          "vFile:setfs", "hostio-setfs", 0);
14548
14549   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14550                          "vFile:open", "hostio-open", 0);
14551
14552   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14553                          "vFile:pread", "hostio-pread", 0);
14554
14555   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14556                          "vFile:pwrite", "hostio-pwrite", 0);
14557
14558   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14559                          "vFile:close", "hostio-close", 0);
14560
14561   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14562                          "vFile:unlink", "hostio-unlink", 0);
14563
14564   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14565                          "vFile:readlink", "hostio-readlink", 0);
14566
14567   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14568                          "vFile:fstat", "hostio-fstat", 0);
14569
14570   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14571                          "vAttach", "attach", 0);
14572
14573   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14574                          "vRun", "run", 0);
14575
14576   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14577                          "QStartNoAckMode", "noack", 0);
14578
14579   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14580                          "vKill", "kill", 0);
14581
14582   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14583                          "qAttached", "query-attached", 0);
14584
14585   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14586                          "ConditionalTracepoints",
14587                          "conditional-tracepoints", 0);
14588
14589   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14590                          "ConditionalBreakpoints",
14591                          "conditional-breakpoints", 0);
14592
14593   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14594                          "BreakpointCommands",
14595                          "breakpoint-commands", 0);
14596
14597   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14598                          "FastTracepoints", "fast-tracepoints", 0);
14599
14600   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14601                          "TracepointSource", "TracepointSource", 0);
14602
14603   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14604                          "QAllow", "allow", 0);
14605
14606   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14607                          "StaticTracepoints", "static-tracepoints", 0);
14608
14609   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14610                          "InstallInTrace", "install-in-trace", 0);
14611
14612   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14613                          "qXfer:statictrace:read", "read-sdata-object", 0);
14614
14615   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14616                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14617
14618   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14619                          "QDisableRandomization", "disable-randomization", 0);
14620
14621   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14622                          "QAgent", "agent", 0);
14623
14624   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14625                          "QTBuffer:size", "trace-buffer-size", 0);
14626
14627   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14628        "Qbtrace:off", "disable-btrace", 0);
14629
14630   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14631        "Qbtrace:bts", "enable-btrace-bts", 0);
14632
14633   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14634        "Qbtrace:pt", "enable-btrace-pt", 0);
14635
14636   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14637        "qXfer:btrace", "read-btrace", 0);
14638
14639   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14640        "qXfer:btrace-conf", "read-btrace-conf", 0);
14641
14642   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14643        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14644
14645   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14646        "multiprocess-feature", "multiprocess-feature", 0);
14647
14648   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14649                          "swbreak-feature", "swbreak-feature", 0);
14650
14651   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14652                          "hwbreak-feature", "hwbreak-feature", 0);
14653
14654   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14655                          "fork-event-feature", "fork-event-feature", 0);
14656
14657   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14658                          "vfork-event-feature", "vfork-event-feature", 0);
14659
14660   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14661        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14662
14663   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14664                          "vContSupported", "verbose-resume-supported", 0);
14665
14666   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14667                          "exec-event-feature", "exec-event-feature", 0);
14668
14669   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14670                          "vCtrlC", "ctrl-c", 0);
14671
14672   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14673                          "QThreadEvents", "thread-events", 0);
14674
14675   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14676                          "N stop reply", "no-resumed-stop-reply", 0);
14677
14678   /* Assert that we've registered "set remote foo-packet" commands
14679      for all packet configs.  */
14680   {
14681     int i;
14682
14683     for (i = 0; i < PACKET_MAX; i++)
14684       {
14685         /* Ideally all configs would have a command associated.  Some
14686            still don't though.  */
14687         int excepted;
14688
14689         switch (i)
14690           {
14691           case PACKET_QNonStop:
14692           case PACKET_EnableDisableTracepoints_feature:
14693           case PACKET_tracenz_feature:
14694           case PACKET_DisconnectedTracing_feature:
14695           case PACKET_augmented_libraries_svr4_read_feature:
14696           case PACKET_qCRC:
14697             /* Additions to this list need to be well justified:
14698                pre-existing packets are OK; new packets are not.  */
14699             excepted = 1;
14700             break;
14701           default:
14702             excepted = 0;
14703             break;
14704           }
14705
14706         /* This catches both forgetting to add a config command, and
14707            forgetting to remove a packet from the exception list.  */
14708         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14709       }
14710   }
14711
14712   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14713      Z sub-packet has its own set and show commands, but users may
14714      have sets to this variable in their .gdbinit files (or in their
14715      documentation).  */
14716   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14717                                 &remote_Z_packet_detect, _("\
14718 Set use of remote protocol `Z' packets"), _("\
14719 Show use of remote protocol `Z' packets "), _("\
14720 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14721 packets."),
14722                                 set_remote_protocol_Z_packet_cmd,
14723                                 show_remote_protocol_Z_packet_cmd,
14724                                 /* FIXME: i18n: Use of remote protocol
14725                                    `Z' packets is %s.  */
14726                                 &remote_set_cmdlist, &remote_show_cmdlist);
14727
14728   add_prefix_cmd ("remote", class_files, remote_command, _("\
14729 Manipulate files on the remote system\n\
14730 Transfer files to and from the remote target system."),
14731                   &remote_cmdlist, "remote ",
14732                   0 /* allow-unknown */, &cmdlist);
14733
14734   add_cmd ("put", class_files, remote_put_command,
14735            _("Copy a local file to the remote system."),
14736            &remote_cmdlist);
14737
14738   add_cmd ("get", class_files, remote_get_command,
14739            _("Copy a remote file to the local system."),
14740            &remote_cmdlist);
14741
14742   add_cmd ("delete", class_files, remote_delete_command,
14743            _("Delete a remote file."),
14744            &remote_cmdlist);
14745
14746   add_setshow_string_noescape_cmd ("exec-file", class_files,
14747                                    &remote_exec_file_var, _("\
14748 Set the remote pathname for \"run\""), _("\
14749 Show the remote pathname for \"run\""), NULL,
14750                                    set_remote_exec_file,
14751                                    show_remote_exec_file,
14752                                    &remote_set_cmdlist,
14753                                    &remote_show_cmdlist);
14754
14755   add_setshow_boolean_cmd ("range-stepping", class_run,
14756                            &use_range_stepping, _("\
14757 Enable or disable range stepping."), _("\
14758 Show whether target-assisted range stepping is enabled."), _("\
14759 If on, and the target supports it, when stepping a source line, GDB\n\
14760 tells the target to step the corresponding range of addresses itself instead\n\
14761 of issuing multiple single-steps.  This speeds up source level\n\
14762 stepping.  If off, GDB always issues single-steps, even if range\n\
14763 stepping is supported by the target.  The default is on."),
14764                            set_range_stepping,
14765                            show_range_stepping,
14766                            &setlist,
14767                            &showlist);
14768
14769   add_setshow_zinteger_cmd ("watchdog", class_maintenance, &watchdog, _("\
14770 Set watchdog timer."), _("\
14771 Show watchdog timer."), _("\
14772 When non-zero, this timeout is used instead of waiting forever for a target\n\
14773 to finish a low-level step or continue operation.  If the specified amount\n\
14774 of time passes without a response from the target, an error occurs."),
14775                             NULL,
14776                             show_watchdog,
14777                             &setlist, &showlist);
14778
14779   /* Eventually initialize fileio.  See fileio.c */
14780   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14781 }