79ae8f66c743ab670796678368febd38f94a6fb3
[external/binutils.git] / gdb / remote.c
1 /* Remote target communications for serial-line targets in custom GDB protocol
2
3    Copyright (C) 1988-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* See the GDB User Guide for details of the GDB remote protocol.  */
21
22 #include "defs.h"
23 #include <ctype.h>
24 #include <fcntl.h>
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "bfd.h"
28 #include "symfile.h"
29 #include "target.h"
30 /*#include "terminal.h" */
31 #include "gdbcmd.h"
32 #include "objfiles.h"
33 #include "gdb-stabs.h"
34 #include "gdbthread.h"
35 #include "remote.h"
36 #include "remote-notif.h"
37 #include "regcache.h"
38 #include "value.h"
39 #include "observable.h"
40 #include "solib.h"
41 #include "cli/cli-decode.h"
42 #include "cli/cli-setshow.h"
43 #include "target-descriptions.h"
44 #include "gdb_bfd.h"
45 #include "filestuff.h"
46 #include "rsp-low.h"
47 #include "disasm.h"
48 #include "location.h"
49
50 #include "gdb_sys_time.h"
51
52 #include "event-loop.h"
53 #include "event-top.h"
54 #include "inf-loop.h"
55
56 #include <signal.h>
57 #include "serial.h"
58
59 #include "gdbcore.h" /* for exec_bfd */
60
61 #include "remote-fileio.h"
62 #include "gdb/fileio.h"
63 #include <sys/stat.h>
64 #include "xml-support.h"
65
66 #include "memory-map.h"
67
68 #include "tracepoint.h"
69 #include "ax.h"
70 #include "ax-gdb.h"
71 #include "agent.h"
72 #include "btrace.h"
73 #include "record-btrace.h"
74 #include <algorithm>
75 #include "common/scoped_restore.h"
76 #include "environ.h"
77 #include "common/byte-vector.h"
78 #include <unordered_map>
79
80 /* The remote target.  */
81
82 static const char remote_doc[] = N_("\
83 Use a remote computer via a serial line, using a gdb-specific protocol.\n\
84 Specify the serial device it is connected to\n\
85 (e.g. /dev/ttyS0, /dev/ttya, COM1, etc.).");
86
87 #define OPAQUETHREADBYTES 8
88
89 /* a 64 bit opaque identifier */
90 typedef unsigned char threadref[OPAQUETHREADBYTES];
91
92 struct gdb_ext_thread_info;
93 struct threads_listing_context;
94 typedef int (*rmt_thread_action) (threadref *ref, void *context);
95 struct protocol_feature;
96 struct packet_reg;
97
98 struct stop_reply;
99 typedef struct stop_reply *stop_reply_p;
100
101 DECLARE_QUEUE_P (stop_reply_p);
102 DEFINE_QUEUE_P (stop_reply_p);
103
104 /* Generic configuration support for packets the stub optionally
105    supports.  Allows the user to specify the use of the packet as well
106    as allowing GDB to auto-detect support in the remote stub.  */
107
108 enum packet_support
109   {
110     PACKET_SUPPORT_UNKNOWN = 0,
111     PACKET_ENABLE,
112     PACKET_DISABLE
113   };
114
115 /* Analyze a packet's return value and update the packet config
116    accordingly.  */
117
118 enum packet_result
119 {
120   PACKET_ERROR,
121   PACKET_OK,
122   PACKET_UNKNOWN
123 };
124
125 struct threads_listing_context;
126
127 /* Stub vCont actions support.
128
129    Each field is a boolean flag indicating whether the stub reports
130    support for the corresponding action.  */
131
132 struct vCont_action_support
133 {
134   /* vCont;t */
135   bool t = false;
136
137   /* vCont;r */
138   bool r = false;
139
140   /* vCont;s */
141   bool s = false;
142
143   /* vCont;S */
144   bool S = false;
145 };
146
147 /* About this many threadisds fit in a packet.  */
148
149 #define MAXTHREADLISTRESULTS 32
150
151 /* Data for the vFile:pread readahead cache.  */
152
153 struct readahead_cache
154 {
155   /* Invalidate the readahead cache.  */
156   void invalidate ();
157
158   /* Invalidate the readahead cache if it is holding data for FD.  */
159   void invalidate_fd (int fd);
160
161   /* Serve pread from the readahead cache.  Returns number of bytes
162      read, or 0 if the request can't be served from the cache.  */
163   int pread (int fd, gdb_byte *read_buf, size_t len, ULONGEST offset);
164
165   /* The file descriptor for the file that is being cached.  -1 if the
166      cache is invalid.  */
167   int fd = -1;
168
169   /* The offset into the file that the cache buffer corresponds
170      to.  */
171   ULONGEST offset = 0;
172
173   /* The buffer holding the cache contents.  */
174   gdb_byte *buf = nullptr;
175   /* The buffer's size.  We try to read as much as fits into a packet
176      at a time.  */
177   size_t bufsize = 0;
178
179   /* Cache hit and miss counters.  */
180   ULONGEST hit_count = 0;
181   ULONGEST miss_count = 0;
182 };
183
184 /* Description of the remote protocol for a given architecture.  */
185
186 struct packet_reg
187 {
188   long offset; /* Offset into G packet.  */
189   long regnum; /* GDB's internal register number.  */
190   LONGEST pnum; /* Remote protocol register number.  */
191   int in_g_packet; /* Always part of G packet.  */
192   /* long size in bytes;  == register_size (target_gdbarch (), regnum);
193      at present.  */
194   /* char *name; == gdbarch_register_name (target_gdbarch (), regnum);
195      at present.  */
196 };
197
198 struct remote_arch_state
199 {
200   explicit remote_arch_state (struct gdbarch *gdbarch);
201
202   /* Description of the remote protocol registers.  */
203   long sizeof_g_packet;
204
205   /* Description of the remote protocol registers indexed by REGNUM
206      (making an array gdbarch_num_regs in size).  */
207   std::unique_ptr<packet_reg[]> regs;
208
209   /* This is the size (in chars) of the first response to the ``g''
210      packet.  It is used as a heuristic when determining the maximum
211      size of memory-read and memory-write packets.  A target will
212      typically only reserve a buffer large enough to hold the ``g''
213      packet.  The size does not include packet overhead (headers and
214      trailers).  */
215   long actual_register_packet_size;
216
217   /* This is the maximum size (in chars) of a non read/write packet.
218      It is also used as a cap on the size of read/write packets.  */
219   long remote_packet_size;
220 };
221
222 /* Description of the remote protocol state for the currently
223    connected target.  This is per-target state, and independent of the
224    selected architecture.  */
225
226 class remote_state
227 {
228 public:
229
230   remote_state ();
231   ~remote_state ();
232
233   /* Get the remote arch state for GDBARCH.  */
234   struct remote_arch_state *get_remote_arch_state (struct gdbarch *gdbarch);
235
236 public: /* data */
237
238   /* A buffer to use for incoming packets, and its current size.  The
239      buffer is grown dynamically for larger incoming packets.
240      Outgoing packets may also be constructed in this buffer.
241      BUF_SIZE is always at least REMOTE_PACKET_SIZE;
242      REMOTE_PACKET_SIZE should be used to limit the length of outgoing
243      packets.  */
244   char *buf;
245   long buf_size;
246
247   /* True if we're going through initial connection setup (finding out
248      about the remote side's threads, relocating symbols, etc.).  */
249   bool starting_up = false;
250
251   /* If we negotiated packet size explicitly (and thus can bypass
252      heuristics for the largest packet size that will not overflow
253      a buffer in the stub), this will be set to that packet size.
254      Otherwise zero, meaning to use the guessed size.  */
255   long explicit_packet_size = 0;
256
257   /* remote_wait is normally called when the target is running and
258      waits for a stop reply packet.  But sometimes we need to call it
259      when the target is already stopped.  We can send a "?" packet
260      and have remote_wait read the response.  Or, if we already have
261      the response, we can stash it in BUF and tell remote_wait to
262      skip calling getpkt.  This flag is set when BUF contains a
263      stop reply packet and the target is not waiting.  */
264   int cached_wait_status = 0;
265
266   /* True, if in no ack mode.  That is, neither GDB nor the stub will
267      expect acks from each other.  The connection is assumed to be
268      reliable.  */
269   bool noack_mode = false;
270
271   /* True if we're connected in extended remote mode.  */
272   bool extended = false;
273
274   /* True if we resumed the target and we're waiting for the target to
275      stop.  In the mean time, we can't start another command/query.
276      The remote server wouldn't be ready to process it, so we'd
277      timeout waiting for a reply that would never come and eventually
278      we'd close the connection.  This can happen in asynchronous mode
279      because we allow GDB commands while the target is running.  */
280   bool waiting_for_stop_reply = false;
281
282   /* The status of the stub support for the various vCont actions.  */
283   vCont_action_support supports_vCont;
284
285   /* True if the user has pressed Ctrl-C, but the target hasn't
286      responded to that.  */
287   bool ctrlc_pending_p = false;
288
289   /* True if we saw a Ctrl-C while reading or writing from/to the
290      remote descriptor.  At that point it is not safe to send a remote
291      interrupt packet, so we instead remember we saw the Ctrl-C and
292      process it once we're done with sending/receiving the current
293      packet, which should be shortly.  If however that takes too long,
294      and the user presses Ctrl-C again, we offer to disconnect.  */
295   bool got_ctrlc_during_io = false;
296
297   /* Descriptor for I/O to remote machine.  Initialize it to NULL so that
298      remote_open knows that we don't have a file open when the program
299      starts.  */
300   struct serial *remote_desc = nullptr;
301
302   /* These are the threads which we last sent to the remote system.  The
303      TID member will be -1 for all or -2 for not sent yet.  */
304   ptid_t general_thread = null_ptid;
305   ptid_t continue_thread = null_ptid;
306
307   /* This is the traceframe which we last selected on the remote system.
308      It will be -1 if no traceframe is selected.  */
309   int remote_traceframe_number = -1;
310
311   char *last_pass_packet = nullptr;
312
313   /* The last QProgramSignals packet sent to the target.  We bypass
314      sending a new program signals list down to the target if the new
315      packet is exactly the same as the last we sent.  IOW, we only let
316      the target know about program signals list changes.  */
317   char *last_program_signals_packet = nullptr;
318
319   gdb_signal last_sent_signal = GDB_SIGNAL_0;
320
321   bool last_sent_step = false;
322
323   /* The execution direction of the last resume we got.  */
324   exec_direction_kind last_resume_exec_dir = EXEC_FORWARD;
325
326   char *finished_object = nullptr;
327   char *finished_annex = nullptr;
328   ULONGEST finished_offset = 0;
329
330   /* Should we try the 'ThreadInfo' query packet?
331
332      This variable (NOT available to the user: auto-detect only!)
333      determines whether GDB will use the new, simpler "ThreadInfo"
334      query or the older, more complex syntax for thread queries.
335      This is an auto-detect variable (set to true at each connect,
336      and set to false when the target fails to recognize it).  */
337   bool use_threadinfo_query = false;
338   bool use_threadextra_query = false;
339
340   threadref echo_nextthread {};
341   threadref nextthread {};
342   threadref resultthreadlist[MAXTHREADLISTRESULTS] {};
343
344   /* The state of remote notification.  */
345   struct remote_notif_state *notif_state = nullptr;
346
347   /* The branch trace configuration.  */
348   struct btrace_config btrace_config {};
349
350   /* The argument to the last "vFile:setfs:" packet we sent, used
351      to avoid sending repeated unnecessary "vFile:setfs:" packets.
352      Initialized to -1 to indicate that no "vFile:setfs:" packet
353      has yet been sent.  */
354   int fs_pid = -1;
355
356   /* A readahead cache for vFile:pread.  Often, reading a binary
357      involves a sequence of small reads.  E.g., when parsing an ELF
358      file.  A readahead cache helps mostly the case of remote
359      debugging on a connection with higher latency, due to the
360      request/reply nature of the RSP.  We only cache data for a single
361      file descriptor at a time.  */
362   struct readahead_cache readahead_cache;
363
364   /* The list of already fetched and acknowledged stop events.  This
365      queue is used for notification Stop, and other notifications
366      don't need queue for their events, because the notification
367      events of Stop can't be consumed immediately, so that events
368      should be queued first, and be consumed by remote_wait_{ns,as}
369      one per time.  Other notifications can consume their events
370      immediately, so queue is not needed for them.  */
371   QUEUE (stop_reply_p) *stop_reply_queue;
372
373   /* Asynchronous signal handle registered as event loop source for
374      when we have pending events ready to be passed to the core.  */
375   struct async_event_handler *remote_async_inferior_event_token = nullptr;
376
377   /* FIXME: cagney/1999-09-23: Even though getpkt was called with
378      ``forever'' still use the normal timeout mechanism.  This is
379      currently used by the ASYNC code to guarentee that target reads
380      during the initial connect always time-out.  Once getpkt has been
381      modified to return a timeout indication and, in turn
382      remote_wait()/wait_for_inferior() have gained a timeout parameter
383      this can go away.  */
384   int wait_forever_enabled_p = 1;
385
386 private:
387   /* Mapping of remote protocol data for each gdbarch.  Usually there
388      is only one entry here, though we may see more with stubs that
389      support multi-process.  */
390   std::unordered_map<struct gdbarch *, remote_arch_state>
391     m_arch_states;
392 };
393
394 static const target_info remote_target_info = {
395   "remote",
396   N_("Remote serial target in gdb-specific protocol"),
397   remote_doc
398 };
399
400 class remote_target : public target_ops
401 {
402 public:
403   remote_target ()
404   {
405     to_stratum = process_stratum;
406   }
407   ~remote_target () override;
408
409   const target_info &info () const override
410   { return remote_target_info; }
411
412   thread_control_capabilities get_thread_control_capabilities () override
413   { return tc_schedlock; }
414
415   /* Open a remote connection.  */
416   static void open (const char *, int);
417
418   void close () override;
419
420   void detach (inferior *, int) override;
421   void disconnect (const char *, int) override;
422
423   void commit_resume () override;
424   void resume (ptid_t, int, enum gdb_signal) override;
425   ptid_t wait (ptid_t, struct target_waitstatus *, int) override;
426
427   void fetch_registers (struct regcache *, int) override;
428   void store_registers (struct regcache *, int) override;
429   void prepare_to_store (struct regcache *) override;
430
431   void files_info () override;
432
433   int insert_breakpoint (struct gdbarch *, struct bp_target_info *) override;
434
435   int remove_breakpoint (struct gdbarch *, struct bp_target_info *,
436                          enum remove_bp_reason) override;
437
438
439   bool stopped_by_sw_breakpoint () override;
440   bool supports_stopped_by_sw_breakpoint () override;
441
442   bool stopped_by_hw_breakpoint () override;
443
444   bool supports_stopped_by_hw_breakpoint () override;
445
446   bool stopped_by_watchpoint () override;
447
448   bool stopped_data_address (CORE_ADDR *) override;
449
450   bool watchpoint_addr_within_range (CORE_ADDR, CORE_ADDR, int) override;
451
452   int can_use_hw_breakpoint (enum bptype, int, int) override;
453
454   int insert_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
455
456   int remove_hw_breakpoint (struct gdbarch *, struct bp_target_info *) override;
457
458   int region_ok_for_hw_watchpoint (CORE_ADDR, int) override;
459
460   int insert_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
461                          struct expression *) override;
462
463   int remove_watchpoint (CORE_ADDR, int, enum target_hw_bp_type,
464                          struct expression *) override;
465
466   void kill () override;
467
468   void load (const char *, int) override;
469
470   void mourn_inferior () override;
471
472   void pass_signals (int, unsigned char *) override;
473
474   int set_syscall_catchpoint (int, bool, int,
475                               gdb::array_view<const int>) override;
476
477   void program_signals (int, unsigned char *) override;
478
479   bool thread_alive (ptid_t ptid) override;
480
481   const char *thread_name (struct thread_info *) override;
482
483   void update_thread_list () override;
484
485   const char *pid_to_str (ptid_t) override;
486
487   const char *extra_thread_info (struct thread_info *) override;
488
489   ptid_t get_ada_task_ptid (long lwp, long thread) override;
490
491   thread_info *thread_handle_to_thread_info (const gdb_byte *thread_handle,
492                                              int handle_len,
493                                              inferior *inf) override;
494
495   void stop (ptid_t) override;
496
497   void interrupt () override;
498
499   void pass_ctrlc () override;
500
501   enum target_xfer_status xfer_partial (enum target_object object,
502                                         const char *annex,
503                                         gdb_byte *readbuf,
504                                         const gdb_byte *writebuf,
505                                         ULONGEST offset, ULONGEST len,
506                                         ULONGEST *xfered_len) override;
507
508   ULONGEST get_memory_xfer_limit () override;
509
510   void rcmd (const char *command, struct ui_file *output) override;
511
512   char *pid_to_exec_file (int pid) override;
513
514   void log_command (const char *cmd) override
515   {
516     serial_log_command (this, cmd);
517   }
518
519   CORE_ADDR get_thread_local_address (ptid_t ptid,
520                                       CORE_ADDR load_module_addr,
521                                       CORE_ADDR offset) override;
522
523   bool has_all_memory ()  override { return default_child_has_all_memory (); }
524   bool has_memory ()  override { return default_child_has_memory (); }
525   bool has_stack ()  override { return default_child_has_stack (); }
526   bool has_registers ()  override { return default_child_has_registers (); }
527   bool has_execution (ptid_t ptid)  override { return default_child_has_execution (ptid); }
528
529   bool can_execute_reverse () override;
530
531   std::vector<mem_region> memory_map () override;
532
533   void flash_erase (ULONGEST address, LONGEST length) override;
534
535   void flash_done () override;
536
537   const struct target_desc *read_description () override;
538
539   int search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
540                      const gdb_byte *pattern, ULONGEST pattern_len,
541                      CORE_ADDR *found_addrp) override;
542
543   bool can_async_p () override;
544
545   bool is_async_p () override;
546
547   void async (int) override;
548
549   void thread_events (int) override;
550
551   int can_do_single_step () override;
552
553   void terminal_inferior () override;
554
555   void terminal_ours () override;
556
557   bool supports_non_stop () override;
558
559   bool supports_multi_process () override;
560
561   bool supports_disable_randomization () override;
562
563   bool filesystem_is_local () override;
564
565
566   int fileio_open (struct inferior *inf, const char *filename,
567                    int flags, int mode, int warn_if_slow,
568                    int *target_errno) override;
569
570   int fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
571                      ULONGEST offset, int *target_errno) override;
572
573   int fileio_pread (int fd, gdb_byte *read_buf, int len,
574                     ULONGEST offset, int *target_errno) override;
575
576   int fileio_fstat (int fd, struct stat *sb, int *target_errno) override;
577
578   int fileio_close (int fd, int *target_errno) override;
579
580   int fileio_unlink (struct inferior *inf,
581                      const char *filename,
582                      int *target_errno) override;
583
584   gdb::optional<std::string>
585     fileio_readlink (struct inferior *inf,
586                      const char *filename,
587                      int *target_errno) override;
588
589   bool supports_enable_disable_tracepoint () override;
590
591   bool supports_string_tracing () override;
592
593   bool supports_evaluation_of_breakpoint_conditions () override;
594
595   bool can_run_breakpoint_commands () override;
596
597   void trace_init () override;
598
599   void download_tracepoint (struct bp_location *location) override;
600
601   bool can_download_tracepoint () override;
602
603   void download_trace_state_variable (const trace_state_variable &tsv) override;
604
605   void enable_tracepoint (struct bp_location *location) override;
606
607   void disable_tracepoint (struct bp_location *location) override;
608
609   void trace_set_readonly_regions () override;
610
611   void trace_start () override;
612
613   int get_trace_status (struct trace_status *ts) override;
614
615   void get_tracepoint_status (struct breakpoint *tp, struct uploaded_tp *utp)
616     override;
617
618   void trace_stop () override;
619
620   int trace_find (enum trace_find_type type, int num,
621                   CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
622
623   bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
624
625   int save_trace_data (const char *filename) override;
626
627   int upload_tracepoints (struct uploaded_tp **utpp) override;
628
629   int upload_trace_state_variables (struct uploaded_tsv **utsvp) override;
630
631   LONGEST get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len) override;
632
633   int get_min_fast_tracepoint_insn_len () override;
634
635   void set_disconnected_tracing (int val) override;
636
637   void set_circular_trace_buffer (int val) override;
638
639   void set_trace_buffer_size (LONGEST val) override;
640
641   bool set_trace_notes (const char *user, const char *notes,
642                         const char *stopnotes) override;
643
644   int core_of_thread (ptid_t ptid) override;
645
646   int verify_memory (const gdb_byte *data,
647                      CORE_ADDR memaddr, ULONGEST size) override;
648
649
650   bool get_tib_address (ptid_t ptid, CORE_ADDR *addr) override;
651
652   void set_permissions () override;
653
654   bool static_tracepoint_marker_at (CORE_ADDR,
655                                     struct static_tracepoint_marker *marker)
656     override;
657
658   std::vector<static_tracepoint_marker>
659     static_tracepoint_markers_by_strid (const char *id) override;
660
661   traceframe_info_up traceframe_info () override;
662
663   bool use_agent (bool use) override;
664   bool can_use_agent () override;
665
666   struct btrace_target_info *enable_btrace (ptid_t ptid,
667                                             const struct btrace_config *conf) override;
668
669   void disable_btrace (struct btrace_target_info *tinfo) override;
670
671   void teardown_btrace (struct btrace_target_info *tinfo) override;
672
673   enum btrace_error read_btrace (struct btrace_data *data,
674                                  struct btrace_target_info *btinfo,
675                                  enum btrace_read_type type) override;
676
677   const struct btrace_config *btrace_conf (const struct btrace_target_info *) override;
678   bool augmented_libraries_svr4_read () override;
679   int follow_fork (int, int) override;
680   void follow_exec (struct inferior *, char *) override;
681   int insert_fork_catchpoint (int) override;
682   int remove_fork_catchpoint (int) override;
683   int insert_vfork_catchpoint (int) override;
684   int remove_vfork_catchpoint (int) override;
685   int insert_exec_catchpoint (int) override;
686   int remove_exec_catchpoint (int) override;
687   enum exec_direction_kind execution_direction () override;
688
689 public: /* Remote specific methods.  */
690
691   void remote_download_command_source (int num, ULONGEST addr,
692                                        struct command_line *cmds);
693
694   void remote_file_put (const char *local_file, const char *remote_file,
695                         int from_tty);
696   void remote_file_get (const char *remote_file, const char *local_file,
697                         int from_tty);
698   void remote_file_delete (const char *remote_file, int from_tty);
699
700   int remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
701                            ULONGEST offset, int *remote_errno);
702   int remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
703                             ULONGEST offset, int *remote_errno);
704   int remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
705                                  ULONGEST offset, int *remote_errno);
706
707   int remote_hostio_send_command (int command_bytes, int which_packet,
708                                   int *remote_errno, char **attachment,
709                                   int *attachment_len);
710   int remote_hostio_set_filesystem (struct inferior *inf,
711                                     int *remote_errno);
712   /* We should get rid of this and use fileio_open directly.  */
713   int remote_hostio_open (struct inferior *inf, const char *filename,
714                           int flags, int mode, int warn_if_slow,
715                           int *remote_errno);
716   int remote_hostio_close (int fd, int *remote_errno);
717
718   int remote_hostio_unlink (inferior *inf, const char *filename,
719                             int *remote_errno);
720
721   struct remote_state *get_remote_state ();
722
723   long get_remote_packet_size (void);
724   long get_memory_packet_size (struct memory_packet_config *config);
725
726   long get_memory_write_packet_size ();
727   long get_memory_read_packet_size ();
728
729   char *append_pending_thread_resumptions (char *p, char *endp,
730                                            ptid_t ptid);
731   static void open_1 (const char *name, int from_tty, int extended_p);
732   void start_remote (int from_tty, int extended_p);
733   void remote_detach_1 (int from_tty, struct inferior *inf);
734
735   char *append_resumption (char *p, char *endp,
736                            ptid_t ptid, int step, gdb_signal siggnal);
737   int remote_resume_with_vcont (ptid_t ptid, int step,
738                                 gdb_signal siggnal);
739
740   void add_current_inferior_and_thread (char *wait_status);
741
742   ptid_t wait_ns (ptid_t ptid, struct target_waitstatus *status,
743                   int options);
744   ptid_t wait_as (ptid_t ptid, target_waitstatus *status,
745                   int options);
746
747   ptid_t process_stop_reply (struct stop_reply *stop_reply,
748                              target_waitstatus *status);
749
750   void remote_notice_new_inferior (ptid_t currthread, int executing);
751
752   void process_initial_stop_replies (int from_tty);
753
754   void remote_add_thread (ptid_t ptid, bool running, bool executing);
755
756   void btrace_sync_conf (const btrace_config *conf);
757
758   void remote_btrace_maybe_reopen ();
759
760   void remove_new_fork_children (threads_listing_context *context);
761   void kill_new_fork_children (int pid);
762   void discard_pending_stop_replies (struct inferior *inf);
763   int stop_reply_queue_length ();
764
765   void check_pending_events_prevent_wildcard_vcont
766     (int *may_global_wildcard_vcont);
767
768   void discard_pending_stop_replies_in_queue ();
769   struct stop_reply *remote_notif_remove_queued_reply (ptid_t ptid);
770   struct stop_reply *queued_stop_reply (ptid_t ptid);
771   int peek_stop_reply (ptid_t ptid);
772   void remote_parse_stop_reply (char *buf, stop_reply *event);
773
774   void remote_stop_ns (ptid_t ptid);
775   void remote_interrupt_as ();
776   void remote_interrupt_ns ();
777
778   char *remote_get_noisy_reply ();
779   int remote_query_attached (int pid);
780   inferior *remote_add_inferior (int fake_pid_p, int pid, int attached,
781                                  int try_open_exec);
782
783   ptid_t remote_current_thread (ptid_t oldpid);
784   ptid_t get_current_thread (char *wait_status);
785
786   void set_thread (ptid_t ptid, int gen);
787   void set_general_thread (ptid_t ptid);
788   void set_continue_thread (ptid_t ptid);
789   void set_general_process ();
790
791   char *write_ptid (char *buf, const char *endbuf, ptid_t ptid);
792
793   int remote_unpack_thread_info_response (char *pkt, threadref *expectedref,
794                                           gdb_ext_thread_info *info);
795   int remote_get_threadinfo (threadref *threadid, int fieldset,
796                              gdb_ext_thread_info *info);
797
798   int parse_threadlist_response (char *pkt, int result_limit,
799                                  threadref *original_echo,
800                                  threadref *resultlist,
801                                  int *doneflag);
802   int remote_get_threadlist (int startflag, threadref *nextthread,
803                              int result_limit, int *done, int *result_count,
804                              threadref *threadlist);
805
806   int remote_threadlist_iterator (rmt_thread_action stepfunction,
807                                   void *context, int looplimit);
808
809   int remote_get_threads_with_ql (threads_listing_context *context);
810   int remote_get_threads_with_qxfer (threads_listing_context *context);
811   int remote_get_threads_with_qthreadinfo (threads_listing_context *context);
812
813   void extended_remote_restart ();
814
815   void get_offsets ();
816
817   void remote_check_symbols ();
818
819   void remote_supported_packet (const struct protocol_feature *feature,
820                                 enum packet_support support,
821                                 const char *argument);
822
823   void remote_query_supported ();
824
825   void remote_packet_size (const protocol_feature *feature,
826                            packet_support support, const char *value);
827
828   void remote_serial_quit_handler ();
829
830   void remote_detach_pid (int pid);
831
832   void remote_vcont_probe ();
833
834   void remote_resume_with_hc (ptid_t ptid, int step,
835                               gdb_signal siggnal);
836
837   void send_interrupt_sequence ();
838   void interrupt_query ();
839
840   void remote_notif_get_pending_events (notif_client *nc);
841
842   int fetch_register_using_p (struct regcache *regcache,
843                               packet_reg *reg);
844   int send_g_packet ();
845   void process_g_packet (struct regcache *regcache);
846   void fetch_registers_using_g (struct regcache *regcache);
847   int store_register_using_P (const struct regcache *regcache,
848                               packet_reg *reg);
849   void store_registers_using_G (const struct regcache *regcache);
850
851   void set_remote_traceframe ();
852
853   void check_binary_download (CORE_ADDR addr);
854
855   target_xfer_status remote_write_bytes_aux (const char *header,
856                                              CORE_ADDR memaddr,
857                                              const gdb_byte *myaddr,
858                                              ULONGEST len_units,
859                                              int unit_size,
860                                              ULONGEST *xfered_len_units,
861                                              char packet_format,
862                                              int use_length);
863
864   target_xfer_status remote_write_bytes (CORE_ADDR memaddr,
865                                          const gdb_byte *myaddr, ULONGEST len,
866                                          int unit_size, ULONGEST *xfered_len);
867
868   target_xfer_status remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
869                                           ULONGEST len_units,
870                                           int unit_size, ULONGEST *xfered_len_units);
871
872   target_xfer_status remote_xfer_live_readonly_partial (gdb_byte *readbuf,
873                                                         ULONGEST memaddr,
874                                                         ULONGEST len,
875                                                         int unit_size,
876                                                         ULONGEST *xfered_len);
877
878   target_xfer_status remote_read_bytes (CORE_ADDR memaddr,
879                                         gdb_byte *myaddr, ULONGEST len,
880                                         int unit_size,
881                                         ULONGEST *xfered_len);
882
883   packet_result remote_send_printf (const char *format, ...)
884     ATTRIBUTE_PRINTF (2, 3);
885
886   target_xfer_status remote_flash_write (ULONGEST address,
887                                          ULONGEST length, ULONGEST *xfered_len,
888                                          const gdb_byte *data);
889
890   int readchar (int timeout);
891
892   void remote_serial_write (const char *str, int len);
893
894   int putpkt (const char *buf);
895   int putpkt_binary (const char *buf, int cnt);
896
897   void skip_frame ();
898   long read_frame (char **buf_p, long *sizeof_buf);
899   void getpkt (char **buf, long *sizeof_buf, int forever);
900   int getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf, int forever,
901                               int expecting_notif, int *is_notif);
902   int getpkt_sane (char **buf, long *sizeof_buf, int forever);
903   int getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
904                             int *is_notif);
905   int remote_vkill (int pid);
906   void remote_kill_k ();
907
908   void extended_remote_disable_randomization (int val);
909   int extended_remote_run (const std::string &args);
910
911   void send_environment_packet (const char *action,
912                                 const char *packet,
913                                 const char *value);
914
915   void extended_remote_environment_support ();
916   void extended_remote_set_inferior_cwd ();
917
918   target_xfer_status remote_write_qxfer (const char *object_name,
919                                          const char *annex,
920                                          const gdb_byte *writebuf,
921                                          ULONGEST offset, LONGEST len,
922                                          ULONGEST *xfered_len,
923                                          struct packet_config *packet);
924
925   target_xfer_status remote_read_qxfer (const char *object_name,
926                                         const char *annex,
927                                         gdb_byte *readbuf, ULONGEST offset,
928                                         LONGEST len,
929                                         ULONGEST *xfered_len,
930                                         struct packet_config *packet);
931
932   void push_stop_reply (struct stop_reply *new_event);
933
934   bool vcont_r_supported ();
935
936   void packet_command (const char *args, int from_tty);
937
938 private: /* data fields */
939
940   /* The remote state.  Don't reference this directly.  Use the
941      get_remote_state method instead.  */
942   remote_state m_remote_state;
943 };
944
945 static const target_info extended_remote_target_info = {
946   "extended-remote",
947   N_("Extended remote serial target in gdb-specific protocol"),
948   remote_doc
949 };
950
951 /* Set up the extended remote target by extending the standard remote
952    target and adding to it.  */
953
954 class extended_remote_target final : public remote_target
955 {
956 public:
957   const target_info &info () const override
958   { return extended_remote_target_info; }
959
960   /* Open an extended-remote connection.  */
961   static void open (const char *, int);
962
963   bool can_create_inferior () override { return true; }
964   void create_inferior (const char *, const std::string &,
965                         char **, int) override;
966
967   void detach (inferior *, int) override;
968
969   bool can_attach () override { return true; }
970   void attach (const char *, int) override;
971
972   void post_attach (int) override;
973   bool supports_disable_randomization () override;
974 };
975
976 /* Per-program-space data key.  */
977 static const struct program_space_data *remote_pspace_data;
978
979 /* The variable registered as the control variable used by the
980    remote exec-file commands.  While the remote exec-file setting is
981    per-program-space, the set/show machinery uses this as the 
982    location of the remote exec-file value.  */
983 static char *remote_exec_file_var;
984
985 /* The size to align memory write packets, when practical.  The protocol
986    does not guarantee any alignment, and gdb will generate short
987    writes and unaligned writes, but even as a best-effort attempt this
988    can improve bulk transfers.  For instance, if a write is misaligned
989    relative to the target's data bus, the stub may need to make an extra
990    round trip fetching data from the target.  This doesn't make a
991    huge difference, but it's easy to do, so we try to be helpful.
992
993    The alignment chosen is arbitrary; usually data bus width is
994    important here, not the possibly larger cache line size.  */
995 enum { REMOTE_ALIGN_WRITES = 16 };
996
997 /* Prototypes for local functions.  */
998
999 static int hexnumlen (ULONGEST num);
1000
1001 static int stubhex (int ch);
1002
1003 static int hexnumstr (char *, ULONGEST);
1004
1005 static int hexnumnstr (char *, ULONGEST, int);
1006
1007 static CORE_ADDR remote_address_masked (CORE_ADDR);
1008
1009 static void print_packet (const char *);
1010
1011 static int stub_unpack_int (char *buff, int fieldlength);
1012
1013 struct packet_config;
1014
1015 static void show_packet_config_cmd (struct packet_config *config);
1016
1017 static void show_remote_protocol_packet_cmd (struct ui_file *file,
1018                                              int from_tty,
1019                                              struct cmd_list_element *c,
1020                                              const char *value);
1021
1022 static ptid_t read_ptid (const char *buf, const char **obuf);
1023
1024 struct stop_reply;
1025 static void stop_reply_xfree (struct stop_reply *);
1026
1027 static void remote_async_inferior_event_handler (gdb_client_data);
1028
1029 static int remote_read_description_p (struct target_ops *target);
1030
1031 static void remote_console_output (char *msg);
1032
1033 static void remote_btrace_reset (remote_state *rs);
1034
1035 static void remote_unpush_and_throw (void);
1036
1037 /* For "remote".  */
1038
1039 static struct cmd_list_element *remote_cmdlist;
1040
1041 /* For "set remote" and "show remote".  */
1042
1043 static struct cmd_list_element *remote_set_cmdlist;
1044 static struct cmd_list_element *remote_show_cmdlist;
1045
1046 /* Controls whether GDB is willing to use range stepping.  */
1047
1048 static int use_range_stepping = 1;
1049
1050 /* The max number of chars in debug output.  The rest of chars are
1051    omitted.  */
1052
1053 #define REMOTE_DEBUG_MAX_CHAR 512
1054
1055 /* Private data that we'll store in (struct thread_info)->priv.  */
1056 struct remote_thread_info : public private_thread_info
1057 {
1058   std::string extra;
1059   std::string name;
1060   int core = -1;
1061
1062   /* Thread handle, perhaps a pthread_t or thread_t value, stored as a
1063      sequence of bytes.  */
1064   gdb::byte_vector thread_handle;
1065
1066   /* Whether the target stopped for a breakpoint/watchpoint.  */
1067   enum target_stop_reason stop_reason = TARGET_STOPPED_BY_NO_REASON;
1068
1069   /* This is set to the data address of the access causing the target
1070      to stop for a watchpoint.  */
1071   CORE_ADDR watch_data_address = 0;
1072
1073   /* Fields used by the vCont action coalescing implemented in
1074      remote_resume / remote_commit_resume.  remote_resume stores each
1075      thread's last resume request in these fields, so that a later
1076      remote_commit_resume knows which is the proper action for this
1077      thread to include in the vCont packet.  */
1078
1079   /* True if the last target_resume call for this thread was a step
1080      request, false if a continue request.  */
1081   int last_resume_step = 0;
1082
1083   /* The signal specified in the last target_resume call for this
1084      thread.  */
1085   gdb_signal last_resume_sig = GDB_SIGNAL_0;
1086
1087   /* Whether this thread was already vCont-resumed on the remote
1088      side.  */
1089   int vcont_resumed = 0;
1090 };
1091
1092 remote_state::remote_state ()
1093 {
1094   /* The default buffer size is unimportant; it will be expanded
1095      whenever a larger buffer is needed. */
1096   this->buf_size = 400;
1097   this->buf = (char *) xmalloc (this->buf_size);
1098
1099   this->stop_reply_queue = QUEUE_alloc (stop_reply_p, stop_reply_xfree);
1100 }
1101
1102 remote_state::~remote_state ()
1103 {
1104   xfree (this->last_pass_packet);
1105   xfree (this->last_program_signals_packet);
1106   xfree (this->buf);
1107   xfree (this->finished_object);
1108   xfree (this->finished_annex);
1109   QUEUE_free (stop_reply_p, this->stop_reply_queue);
1110 }
1111
1112 /* Utility: generate error from an incoming stub packet.  */
1113 static void
1114 trace_error (char *buf)
1115 {
1116   if (*buf++ != 'E')
1117     return;                     /* not an error msg */
1118   switch (*buf)
1119     {
1120     case '1':                   /* malformed packet error */
1121       if (*++buf == '0')        /*   general case: */
1122         error (_("remote.c: error in outgoing packet."));
1123       else
1124         error (_("remote.c: error in outgoing packet at field #%ld."),
1125                strtol (buf, NULL, 16));
1126     default:
1127       error (_("Target returns error code '%s'."), buf);
1128     }
1129 }
1130
1131 /* Utility: wait for reply from stub, while accepting "O" packets.  */
1132
1133 char *
1134 remote_target::remote_get_noisy_reply ()
1135 {
1136   struct remote_state *rs = get_remote_state ();
1137
1138   do                            /* Loop on reply from remote stub.  */
1139     {
1140       char *buf;
1141
1142       QUIT;                     /* Allow user to bail out with ^C.  */
1143       getpkt (&rs->buf, &rs->buf_size, 0);
1144       buf = rs->buf;
1145       if (buf[0] == 'E')
1146         trace_error (buf);
1147       else if (startswith (buf, "qRelocInsn:"))
1148         {
1149           ULONGEST ul;
1150           CORE_ADDR from, to, org_to;
1151           const char *p, *pp;
1152           int adjusted_size = 0;
1153           int relocated = 0;
1154
1155           p = buf + strlen ("qRelocInsn:");
1156           pp = unpack_varlen_hex (p, &ul);
1157           if (*pp != ';')
1158             error (_("invalid qRelocInsn packet: %s"), buf);
1159           from = ul;
1160
1161           p = pp + 1;
1162           unpack_varlen_hex (p, &ul);
1163           to = ul;
1164
1165           org_to = to;
1166
1167           TRY
1168             {
1169               gdbarch_relocate_instruction (target_gdbarch (), &to, from);
1170               relocated = 1;
1171             }
1172           CATCH (ex, RETURN_MASK_ALL)
1173             {
1174               if (ex.error == MEMORY_ERROR)
1175                 {
1176                   /* Propagate memory errors silently back to the
1177                      target.  The stub may have limited the range of
1178                      addresses we can write to, for example.  */
1179                 }
1180               else
1181                 {
1182                   /* Something unexpectedly bad happened.  Be verbose
1183                      so we can tell what, and propagate the error back
1184                      to the stub, so it doesn't get stuck waiting for
1185                      a response.  */
1186                   exception_fprintf (gdb_stderr, ex,
1187                                      _("warning: relocating instruction: "));
1188                 }
1189               putpkt ("E01");
1190             }
1191           END_CATCH
1192
1193           if (relocated)
1194             {
1195               adjusted_size = to - org_to;
1196
1197               xsnprintf (buf, rs->buf_size, "qRelocInsn:%x", adjusted_size);
1198               putpkt (buf);
1199             }
1200         }
1201       else if (buf[0] == 'O' && buf[1] != 'K')
1202         remote_console_output (buf + 1);        /* 'O' message from stub */
1203       else
1204         return buf;             /* Here's the actual reply.  */
1205     }
1206   while (1);
1207 }
1208
1209 struct remote_arch_state *
1210 remote_state::get_remote_arch_state (struct gdbarch *gdbarch)
1211 {
1212   remote_arch_state *rsa;
1213
1214   auto it = this->m_arch_states.find (gdbarch);
1215   if (it == this->m_arch_states.end ())
1216     {
1217       auto p = this->m_arch_states.emplace (std::piecewise_construct,
1218                                             std::forward_as_tuple (gdbarch),
1219                                             std::forward_as_tuple (gdbarch));
1220       rsa = &p.first->second;
1221
1222       /* Make sure that the packet buffer is plenty big enough for
1223          this architecture.  */
1224       if (this->buf_size < rsa->remote_packet_size)
1225         {
1226           this->buf_size = 2 * rsa->remote_packet_size;
1227           this->buf = (char *) xrealloc (this->buf, this->buf_size);
1228         }
1229     }
1230   else
1231     rsa = &it->second;
1232
1233   return rsa;
1234 }
1235
1236 /* Fetch the global remote target state.  */
1237
1238 remote_state *
1239 remote_target::get_remote_state ()
1240 {
1241   /* Make sure that the remote architecture state has been
1242      initialized, because doing so might reallocate rs->buf.  Any
1243      function which calls getpkt also needs to be mindful of changes
1244      to rs->buf, but this call limits the number of places which run
1245      into trouble.  */
1246   m_remote_state.get_remote_arch_state (target_gdbarch ());
1247
1248   return &m_remote_state;
1249 }
1250
1251 /* Cleanup routine for the remote module's pspace data.  */
1252
1253 static void
1254 remote_pspace_data_cleanup (struct program_space *pspace, void *arg)
1255 {
1256   char *remote_exec_file = (char *) arg;
1257
1258   xfree (remote_exec_file);
1259 }
1260
1261 /* Fetch the remote exec-file from the current program space.  */
1262
1263 static const char *
1264 get_remote_exec_file (void)
1265 {
1266   char *remote_exec_file;
1267
1268   remote_exec_file
1269     = (char *) program_space_data (current_program_space,
1270                                    remote_pspace_data);
1271   if (remote_exec_file == NULL)
1272     return "";
1273
1274   return remote_exec_file;
1275 }
1276
1277 /* Set the remote exec file for PSPACE.  */
1278
1279 static void
1280 set_pspace_remote_exec_file (struct program_space *pspace,
1281                         char *remote_exec_file)
1282 {
1283   char *old_file = (char *) program_space_data (pspace, remote_pspace_data);
1284
1285   xfree (old_file);
1286   set_program_space_data (pspace, remote_pspace_data,
1287                           xstrdup (remote_exec_file));
1288 }
1289
1290 /* The "set/show remote exec-file" set command hook.  */
1291
1292 static void
1293 set_remote_exec_file (const char *ignored, int from_tty,
1294                       struct cmd_list_element *c)
1295 {
1296   gdb_assert (remote_exec_file_var != NULL);
1297   set_pspace_remote_exec_file (current_program_space, remote_exec_file_var);
1298 }
1299
1300 /* The "set/show remote exec-file" show command hook.  */
1301
1302 static void
1303 show_remote_exec_file (struct ui_file *file, int from_tty,
1304                        struct cmd_list_element *cmd, const char *value)
1305 {
1306   fprintf_filtered (file, "%s\n", remote_exec_file_var);
1307 }
1308
1309 static int
1310 compare_pnums (const void *lhs_, const void *rhs_)
1311 {
1312   const struct packet_reg * const *lhs
1313     = (const struct packet_reg * const *) lhs_;
1314   const struct packet_reg * const *rhs
1315     = (const struct packet_reg * const *) rhs_;
1316
1317   if ((*lhs)->pnum < (*rhs)->pnum)
1318     return -1;
1319   else if ((*lhs)->pnum == (*rhs)->pnum)
1320     return 0;
1321   else
1322     return 1;
1323 }
1324
1325 static int
1326 map_regcache_remote_table (struct gdbarch *gdbarch, struct packet_reg *regs)
1327 {
1328   int regnum, num_remote_regs, offset;
1329   struct packet_reg **remote_regs;
1330
1331   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1332     {
1333       struct packet_reg *r = &regs[regnum];
1334
1335       if (register_size (gdbarch, regnum) == 0)
1336         /* Do not try to fetch zero-sized (placeholder) registers.  */
1337         r->pnum = -1;
1338       else
1339         r->pnum = gdbarch_remote_register_number (gdbarch, regnum);
1340
1341       r->regnum = regnum;
1342     }
1343
1344   /* Define the g/G packet format as the contents of each register
1345      with a remote protocol number, in order of ascending protocol
1346      number.  */
1347
1348   remote_regs = XALLOCAVEC (struct packet_reg *, gdbarch_num_regs (gdbarch));
1349   for (num_remote_regs = 0, regnum = 0;
1350        regnum < gdbarch_num_regs (gdbarch);
1351        regnum++)
1352     if (regs[regnum].pnum != -1)
1353       remote_regs[num_remote_regs++] = &regs[regnum];
1354
1355   qsort (remote_regs, num_remote_regs, sizeof (struct packet_reg *),
1356          compare_pnums);
1357
1358   for (regnum = 0, offset = 0; regnum < num_remote_regs; regnum++)
1359     {
1360       remote_regs[regnum]->in_g_packet = 1;
1361       remote_regs[regnum]->offset = offset;
1362       offset += register_size (gdbarch, remote_regs[regnum]->regnum);
1363     }
1364
1365   return offset;
1366 }
1367
1368 /* Given the architecture described by GDBARCH, return the remote
1369    protocol register's number and the register's offset in the g/G
1370    packets of GDB register REGNUM, in PNUM and POFFSET respectively.
1371    If the target does not have a mapping for REGNUM, return false,
1372    otherwise, return true.  */
1373
1374 int
1375 remote_register_number_and_offset (struct gdbarch *gdbarch, int regnum,
1376                                    int *pnum, int *poffset)
1377 {
1378   gdb_assert (regnum < gdbarch_num_regs (gdbarch));
1379
1380   std::vector<packet_reg> regs (gdbarch_num_regs (gdbarch));
1381
1382   map_regcache_remote_table (gdbarch, regs.data ());
1383
1384   *pnum = regs[regnum].pnum;
1385   *poffset = regs[regnum].offset;
1386
1387   return *pnum != -1;
1388 }
1389
1390 remote_arch_state::remote_arch_state (struct gdbarch *gdbarch)
1391 {
1392   /* Use the architecture to build a regnum<->pnum table, which will be
1393      1:1 unless a feature set specifies otherwise.  */
1394   this->regs.reset (new packet_reg [gdbarch_num_regs (gdbarch)] ());
1395
1396   /* Record the maximum possible size of the g packet - it may turn out
1397      to be smaller.  */
1398   this->sizeof_g_packet
1399     = map_regcache_remote_table (gdbarch, this->regs.get ());
1400
1401   /* Default maximum number of characters in a packet body.  Many
1402      remote stubs have a hardwired buffer size of 400 bytes
1403      (c.f. BUFMAX in m68k-stub.c and i386-stub.c).  BUFMAX-1 is used
1404      as the maximum packet-size to ensure that the packet and an extra
1405      NUL character can always fit in the buffer.  This stops GDB
1406      trashing stubs that try to squeeze an extra NUL into what is
1407      already a full buffer (As of 1999-12-04 that was most stubs).  */
1408   this->remote_packet_size = 400 - 1;
1409
1410   /* This one is filled in when a ``g'' packet is received.  */
1411   this->actual_register_packet_size = 0;
1412
1413   /* Should rsa->sizeof_g_packet needs more space than the
1414      default, adjust the size accordingly.  Remember that each byte is
1415      encoded as two characters.  32 is the overhead for the packet
1416      header / footer.  NOTE: cagney/1999-10-26: I suspect that 8
1417      (``$NN:G...#NN'') is a better guess, the below has been padded a
1418      little.  */
1419   if (this->sizeof_g_packet > ((this->remote_packet_size - 32) / 2))
1420     this->remote_packet_size = (this->sizeof_g_packet * 2 + 32);
1421 }
1422
1423 /* Get a pointer to the current remote target.  If not connected to a
1424    remote target, return NULL.  */
1425
1426 static remote_target *
1427 get_current_remote_target ()
1428 {
1429   target_ops *proc_target = find_target_at (process_stratum);
1430   return dynamic_cast<remote_target *> (proc_target);
1431 }
1432
1433 /* Return the current allowed size of a remote packet.  This is
1434    inferred from the current architecture, and should be used to
1435    limit the length of outgoing packets.  */
1436 long
1437 remote_target::get_remote_packet_size ()
1438 {
1439   struct remote_state *rs = get_remote_state ();
1440   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1441
1442   if (rs->explicit_packet_size)
1443     return rs->explicit_packet_size;
1444
1445   return rsa->remote_packet_size;
1446 }
1447
1448 static struct packet_reg *
1449 packet_reg_from_regnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1450                         long regnum)
1451 {
1452   if (regnum < 0 && regnum >= gdbarch_num_regs (gdbarch))
1453     return NULL;
1454   else
1455     {
1456       struct packet_reg *r = &rsa->regs[regnum];
1457
1458       gdb_assert (r->regnum == regnum);
1459       return r;
1460     }
1461 }
1462
1463 static struct packet_reg *
1464 packet_reg_from_pnum (struct gdbarch *gdbarch, struct remote_arch_state *rsa,
1465                       LONGEST pnum)
1466 {
1467   int i;
1468
1469   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
1470     {
1471       struct packet_reg *r = &rsa->regs[i];
1472
1473       if (r->pnum == pnum)
1474         return r;
1475     }
1476   return NULL;
1477 }
1478
1479 /* Allow the user to specify what sequence to send to the remote
1480    when he requests a program interruption: Although ^C is usually
1481    what remote systems expect (this is the default, here), it is
1482    sometimes preferable to send a break.  On other systems such
1483    as the Linux kernel, a break followed by g, which is Magic SysRq g
1484    is required in order to interrupt the execution.  */
1485 const char interrupt_sequence_control_c[] = "Ctrl-C";
1486 const char interrupt_sequence_break[] = "BREAK";
1487 const char interrupt_sequence_break_g[] = "BREAK-g";
1488 static const char *const interrupt_sequence_modes[] =
1489   {
1490     interrupt_sequence_control_c,
1491     interrupt_sequence_break,
1492     interrupt_sequence_break_g,
1493     NULL
1494   };
1495 static const char *interrupt_sequence_mode = interrupt_sequence_control_c;
1496
1497 static void
1498 show_interrupt_sequence (struct ui_file *file, int from_tty,
1499                          struct cmd_list_element *c,
1500                          const char *value)
1501 {
1502   if (interrupt_sequence_mode == interrupt_sequence_control_c)
1503     fprintf_filtered (file,
1504                       _("Send the ASCII ETX character (Ctrl-c) "
1505                         "to the remote target to interrupt the "
1506                         "execution of the program.\n"));
1507   else if (interrupt_sequence_mode == interrupt_sequence_break)
1508     fprintf_filtered (file,
1509                       _("send a break signal to the remote target "
1510                         "to interrupt the execution of the program.\n"));
1511   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
1512     fprintf_filtered (file,
1513                       _("Send a break signal and 'g' a.k.a. Magic SysRq g to "
1514                         "the remote target to interrupt the execution "
1515                         "of Linux kernel.\n"));
1516   else
1517     internal_error (__FILE__, __LINE__,
1518                     _("Invalid value for interrupt_sequence_mode: %s."),
1519                     interrupt_sequence_mode);
1520 }
1521
1522 /* This boolean variable specifies whether interrupt_sequence is sent
1523    to the remote target when gdb connects to it.
1524    This is mostly needed when you debug the Linux kernel: The Linux kernel
1525    expects BREAK g which is Magic SysRq g for connecting gdb.  */
1526 static int interrupt_on_connect = 0;
1527
1528 /* This variable is used to implement the "set/show remotebreak" commands.
1529    Since these commands are now deprecated in favor of "set/show remote
1530    interrupt-sequence", it no longer has any effect on the code.  */
1531 static int remote_break;
1532
1533 static void
1534 set_remotebreak (const char *args, int from_tty, struct cmd_list_element *c)
1535 {
1536   if (remote_break)
1537     interrupt_sequence_mode = interrupt_sequence_break;
1538   else
1539     interrupt_sequence_mode = interrupt_sequence_control_c;
1540 }
1541
1542 static void
1543 show_remotebreak (struct ui_file *file, int from_tty,
1544                   struct cmd_list_element *c,
1545                   const char *value)
1546 {
1547 }
1548
1549 /* This variable sets the number of bits in an address that are to be
1550    sent in a memory ("M" or "m") packet.  Normally, after stripping
1551    leading zeros, the entire address would be sent.  This variable
1552    restricts the address to REMOTE_ADDRESS_SIZE bits.  HISTORY: The
1553    initial implementation of remote.c restricted the address sent in
1554    memory packets to ``host::sizeof long'' bytes - (typically 32
1555    bits).  Consequently, for 64 bit targets, the upper 32 bits of an
1556    address was never sent.  Since fixing this bug may cause a break in
1557    some remote targets this variable is principly provided to
1558    facilitate backward compatibility.  */
1559
1560 static unsigned int remote_address_size;
1561
1562 \f
1563 /* User configurable variables for the number of characters in a
1564    memory read/write packet.  MIN (rsa->remote_packet_size,
1565    rsa->sizeof_g_packet) is the default.  Some targets need smaller
1566    values (fifo overruns, et.al.) and some users need larger values
1567    (speed up transfers).  The variables ``preferred_*'' (the user
1568    request), ``current_*'' (what was actually set) and ``forced_*''
1569    (Positive - a soft limit, negative - a hard limit).  */
1570
1571 struct memory_packet_config
1572 {
1573   const char *name;
1574   long size;
1575   int fixed_p;
1576 };
1577
1578 /* The default max memory-write-packet-size, when the setting is
1579    "fixed".  The 16k is historical.  (It came from older GDB's using
1580    alloca for buffers and the knowledge (folklore?) that some hosts
1581    don't cope very well with large alloca calls.)  */
1582 #define DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED 16384
1583
1584 /* The minimum remote packet size for memory transfers.  Ensures we
1585    can write at least one byte.  */
1586 #define MIN_MEMORY_PACKET_SIZE 20
1587
1588 /* Get the memory packet size, assuming it is fixed.  */
1589
1590 static long
1591 get_fixed_memory_packet_size (struct memory_packet_config *config)
1592 {
1593   gdb_assert (config->fixed_p);
1594
1595   if (config->size <= 0)
1596     return DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED;
1597   else
1598     return config->size;
1599 }
1600
1601 /* Compute the current size of a read/write packet.  Since this makes
1602    use of ``actual_register_packet_size'' the computation is dynamic.  */
1603
1604 long
1605 remote_target::get_memory_packet_size (struct memory_packet_config *config)
1606 {
1607   struct remote_state *rs = get_remote_state ();
1608   remote_arch_state *rsa = rs->get_remote_arch_state (target_gdbarch ());
1609
1610   long what_they_get;
1611   if (config->fixed_p)
1612     what_they_get = get_fixed_memory_packet_size (config);
1613   else
1614     {
1615       what_they_get = get_remote_packet_size ();
1616       /* Limit the packet to the size specified by the user.  */
1617       if (config->size > 0
1618           && what_they_get > config->size)
1619         what_they_get = config->size;
1620
1621       /* Limit it to the size of the targets ``g'' response unless we have
1622          permission from the stub to use a larger packet size.  */
1623       if (rs->explicit_packet_size == 0
1624           && rsa->actual_register_packet_size > 0
1625           && what_they_get > rsa->actual_register_packet_size)
1626         what_they_get = rsa->actual_register_packet_size;
1627     }
1628   if (what_they_get < MIN_MEMORY_PACKET_SIZE)
1629     what_they_get = MIN_MEMORY_PACKET_SIZE;
1630
1631   /* Make sure there is room in the global buffer for this packet
1632      (including its trailing NUL byte).  */
1633   if (rs->buf_size < what_they_get + 1)
1634     {
1635       rs->buf_size = 2 * what_they_get;
1636       rs->buf = (char *) xrealloc (rs->buf, 2 * what_they_get);
1637     }
1638
1639   return what_they_get;
1640 }
1641
1642 /* Update the size of a read/write packet.  If they user wants
1643    something really big then do a sanity check.  */
1644
1645 static void
1646 set_memory_packet_size (const char *args, struct memory_packet_config *config)
1647 {
1648   int fixed_p = config->fixed_p;
1649   long size = config->size;
1650
1651   if (args == NULL)
1652     error (_("Argument required (integer, `fixed' or `limited')."));
1653   else if (strcmp (args, "hard") == 0
1654       || strcmp (args, "fixed") == 0)
1655     fixed_p = 1;
1656   else if (strcmp (args, "soft") == 0
1657            || strcmp (args, "limit") == 0)
1658     fixed_p = 0;
1659   else
1660     {
1661       char *end;
1662
1663       size = strtoul (args, &end, 0);
1664       if (args == end)
1665         error (_("Invalid %s (bad syntax)."), config->name);
1666
1667       /* Instead of explicitly capping the size of a packet to or
1668          disallowing it, the user is allowed to set the size to
1669          something arbitrarily large.  */
1670     }
1671
1672   /* Extra checks?  */
1673   if (fixed_p && !config->fixed_p)
1674     {
1675       /* So that the query shows the correct value.  */
1676       long query_size = (size <= 0
1677                          ? DEFAULT_MAX_MEMORY_PACKET_SIZE_FIXED
1678                          : size);
1679
1680       if (! query (_("The target may not be able to correctly handle a %s\n"
1681                    "of %ld bytes. Change the packet size? "),
1682                    config->name, query_size))
1683         error (_("Packet size not changed."));
1684     }
1685   /* Update the config.  */
1686   config->fixed_p = fixed_p;
1687   config->size = size;
1688 }
1689
1690 static void
1691 show_memory_packet_size (struct memory_packet_config *config)
1692 {
1693   if (config->size == 0)
1694     printf_filtered (_("The %s is 0 (default). "), config->name);
1695   else
1696     printf_filtered (_("The %s is %ld. "), config->name, config->size);
1697   if (config->fixed_p)
1698     printf_filtered (_("Packets are fixed at %ld bytes.\n"),
1699                      get_fixed_memory_packet_size (config));
1700   else
1701     {
1702       remote_target *remote = get_current_remote_target ();
1703
1704       if (remote != NULL)
1705         printf_filtered (_("Packets are limited to %ld bytes.\n"),
1706                          remote->get_memory_packet_size (config));
1707       else
1708         puts_filtered ("The actual limit will be further reduced "
1709                        "dependent on the target.\n");
1710     }
1711 }
1712
1713 static struct memory_packet_config memory_write_packet_config =
1714 {
1715   "memory-write-packet-size",
1716 };
1717
1718 static void
1719 set_memory_write_packet_size (const char *args, int from_tty)
1720 {
1721   set_memory_packet_size (args, &memory_write_packet_config);
1722 }
1723
1724 static void
1725 show_memory_write_packet_size (const char *args, int from_tty)
1726 {
1727   show_memory_packet_size (&memory_write_packet_config);
1728 }
1729
1730 long
1731 remote_target::get_memory_write_packet_size ()
1732 {
1733   return get_memory_packet_size (&memory_write_packet_config);
1734 }
1735
1736 static struct memory_packet_config memory_read_packet_config =
1737 {
1738   "memory-read-packet-size",
1739 };
1740
1741 static void
1742 set_memory_read_packet_size (const char *args, int from_tty)
1743 {
1744   set_memory_packet_size (args, &memory_read_packet_config);
1745 }
1746
1747 static void
1748 show_memory_read_packet_size (const char *args, int from_tty)
1749 {
1750   show_memory_packet_size (&memory_read_packet_config);
1751 }
1752
1753 long
1754 remote_target::get_memory_read_packet_size ()
1755 {
1756   long size = get_memory_packet_size (&memory_read_packet_config);
1757
1758   /* FIXME: cagney/1999-11-07: Functions like getpkt() need to get an
1759      extra buffer size argument before the memory read size can be
1760      increased beyond this.  */
1761   if (size > get_remote_packet_size ())
1762     size = get_remote_packet_size ();
1763   return size;
1764 }
1765
1766 \f
1767
1768 struct packet_config
1769   {
1770     const char *name;
1771     const char *title;
1772
1773     /* If auto, GDB auto-detects support for this packet or feature,
1774        either through qSupported, or by trying the packet and looking
1775        at the response.  If true, GDB assumes the target supports this
1776        packet.  If false, the packet is disabled.  Configs that don't
1777        have an associated command always have this set to auto.  */
1778     enum auto_boolean detect;
1779
1780     /* Does the target support this packet?  */
1781     enum packet_support support;
1782   };
1783
1784 static enum packet_support packet_config_support (struct packet_config *config);
1785 static enum packet_support packet_support (int packet);
1786
1787 static void
1788 show_packet_config_cmd (struct packet_config *config)
1789 {
1790   const char *support = "internal-error";
1791
1792   switch (packet_config_support (config))
1793     {
1794     case PACKET_ENABLE:
1795       support = "enabled";
1796       break;
1797     case PACKET_DISABLE:
1798       support = "disabled";
1799       break;
1800     case PACKET_SUPPORT_UNKNOWN:
1801       support = "unknown";
1802       break;
1803     }
1804   switch (config->detect)
1805     {
1806     case AUTO_BOOLEAN_AUTO:
1807       printf_filtered (_("Support for the `%s' packet "
1808                          "is auto-detected, currently %s.\n"),
1809                        config->name, support);
1810       break;
1811     case AUTO_BOOLEAN_TRUE:
1812     case AUTO_BOOLEAN_FALSE:
1813       printf_filtered (_("Support for the `%s' packet is currently %s.\n"),
1814                        config->name, support);
1815       break;
1816     }
1817 }
1818
1819 static void
1820 add_packet_config_cmd (struct packet_config *config, const char *name,
1821                        const char *title, int legacy)
1822 {
1823   char *set_doc;
1824   char *show_doc;
1825   char *cmd_name;
1826
1827   config->name = name;
1828   config->title = title;
1829   set_doc = xstrprintf ("Set use of remote protocol `%s' (%s) packet",
1830                         name, title);
1831   show_doc = xstrprintf ("Show current use of remote "
1832                          "protocol `%s' (%s) packet",
1833                          name, title);
1834   /* set/show TITLE-packet {auto,on,off} */
1835   cmd_name = xstrprintf ("%s-packet", title);
1836   add_setshow_auto_boolean_cmd (cmd_name, class_obscure,
1837                                 &config->detect, set_doc,
1838                                 show_doc, NULL, /* help_doc */
1839                                 NULL,
1840                                 show_remote_protocol_packet_cmd,
1841                                 &remote_set_cmdlist, &remote_show_cmdlist);
1842   /* The command code copies the documentation strings.  */
1843   xfree (set_doc);
1844   xfree (show_doc);
1845   /* set/show remote NAME-packet {auto,on,off} -- legacy.  */
1846   if (legacy)
1847     {
1848       char *legacy_name;
1849
1850       legacy_name = xstrprintf ("%s-packet", name);
1851       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1852                      &remote_set_cmdlist);
1853       add_alias_cmd (legacy_name, cmd_name, class_obscure, 0,
1854                      &remote_show_cmdlist);
1855     }
1856 }
1857
1858 static enum packet_result
1859 packet_check_result (const char *buf)
1860 {
1861   if (buf[0] != '\0')
1862     {
1863       /* The stub recognized the packet request.  Check that the
1864          operation succeeded.  */
1865       if (buf[0] == 'E'
1866           && isxdigit (buf[1]) && isxdigit (buf[2])
1867           && buf[3] == '\0')
1868         /* "Enn"  - definitly an error.  */
1869         return PACKET_ERROR;
1870
1871       /* Always treat "E." as an error.  This will be used for
1872          more verbose error messages, such as E.memtypes.  */
1873       if (buf[0] == 'E' && buf[1] == '.')
1874         return PACKET_ERROR;
1875
1876       /* The packet may or may not be OK.  Just assume it is.  */
1877       return PACKET_OK;
1878     }
1879   else
1880     /* The stub does not support the packet.  */
1881     return PACKET_UNKNOWN;
1882 }
1883
1884 static enum packet_result
1885 packet_ok (const char *buf, struct packet_config *config)
1886 {
1887   enum packet_result result;
1888
1889   if (config->detect != AUTO_BOOLEAN_TRUE
1890       && config->support == PACKET_DISABLE)
1891     internal_error (__FILE__, __LINE__,
1892                     _("packet_ok: attempt to use a disabled packet"));
1893
1894   result = packet_check_result (buf);
1895   switch (result)
1896     {
1897     case PACKET_OK:
1898     case PACKET_ERROR:
1899       /* The stub recognized the packet request.  */
1900       if (config->support == PACKET_SUPPORT_UNKNOWN)
1901         {
1902           if (remote_debug)
1903             fprintf_unfiltered (gdb_stdlog,
1904                                 "Packet %s (%s) is supported\n",
1905                                 config->name, config->title);
1906           config->support = PACKET_ENABLE;
1907         }
1908       break;
1909     case PACKET_UNKNOWN:
1910       /* The stub does not support the packet.  */
1911       if (config->detect == AUTO_BOOLEAN_AUTO
1912           && config->support == PACKET_ENABLE)
1913         {
1914           /* If the stub previously indicated that the packet was
1915              supported then there is a protocol error.  */
1916           error (_("Protocol error: %s (%s) conflicting enabled responses."),
1917                  config->name, config->title);
1918         }
1919       else if (config->detect == AUTO_BOOLEAN_TRUE)
1920         {
1921           /* The user set it wrong.  */
1922           error (_("Enabled packet %s (%s) not recognized by stub"),
1923                  config->name, config->title);
1924         }
1925
1926       if (remote_debug)
1927         fprintf_unfiltered (gdb_stdlog,
1928                             "Packet %s (%s) is NOT supported\n",
1929                             config->name, config->title);
1930       config->support = PACKET_DISABLE;
1931       break;
1932     }
1933
1934   return result;
1935 }
1936
1937 enum {
1938   PACKET_vCont = 0,
1939   PACKET_X,
1940   PACKET_qSymbol,
1941   PACKET_P,
1942   PACKET_p,
1943   PACKET_Z0,
1944   PACKET_Z1,
1945   PACKET_Z2,
1946   PACKET_Z3,
1947   PACKET_Z4,
1948   PACKET_vFile_setfs,
1949   PACKET_vFile_open,
1950   PACKET_vFile_pread,
1951   PACKET_vFile_pwrite,
1952   PACKET_vFile_close,
1953   PACKET_vFile_unlink,
1954   PACKET_vFile_readlink,
1955   PACKET_vFile_fstat,
1956   PACKET_qXfer_auxv,
1957   PACKET_qXfer_features,
1958   PACKET_qXfer_exec_file,
1959   PACKET_qXfer_libraries,
1960   PACKET_qXfer_libraries_svr4,
1961   PACKET_qXfer_memory_map,
1962   PACKET_qXfer_spu_read,
1963   PACKET_qXfer_spu_write,
1964   PACKET_qXfer_osdata,
1965   PACKET_qXfer_threads,
1966   PACKET_qXfer_statictrace_read,
1967   PACKET_qXfer_traceframe_info,
1968   PACKET_qXfer_uib,
1969   PACKET_qGetTIBAddr,
1970   PACKET_qGetTLSAddr,
1971   PACKET_qSupported,
1972   PACKET_qTStatus,
1973   PACKET_QPassSignals,
1974   PACKET_QCatchSyscalls,
1975   PACKET_QProgramSignals,
1976   PACKET_QSetWorkingDir,
1977   PACKET_QStartupWithShell,
1978   PACKET_QEnvironmentHexEncoded,
1979   PACKET_QEnvironmentReset,
1980   PACKET_QEnvironmentUnset,
1981   PACKET_qCRC,
1982   PACKET_qSearch_memory,
1983   PACKET_vAttach,
1984   PACKET_vRun,
1985   PACKET_QStartNoAckMode,
1986   PACKET_vKill,
1987   PACKET_qXfer_siginfo_read,
1988   PACKET_qXfer_siginfo_write,
1989   PACKET_qAttached,
1990
1991   /* Support for conditional tracepoints.  */
1992   PACKET_ConditionalTracepoints,
1993
1994   /* Support for target-side breakpoint conditions.  */
1995   PACKET_ConditionalBreakpoints,
1996
1997   /* Support for target-side breakpoint commands.  */
1998   PACKET_BreakpointCommands,
1999
2000   /* Support for fast tracepoints.  */
2001   PACKET_FastTracepoints,
2002
2003   /* Support for static tracepoints.  */
2004   PACKET_StaticTracepoints,
2005
2006   /* Support for installing tracepoints while a trace experiment is
2007      running.  */
2008   PACKET_InstallInTrace,
2009
2010   PACKET_bc,
2011   PACKET_bs,
2012   PACKET_TracepointSource,
2013   PACKET_QAllow,
2014   PACKET_qXfer_fdpic,
2015   PACKET_QDisableRandomization,
2016   PACKET_QAgent,
2017   PACKET_QTBuffer_size,
2018   PACKET_Qbtrace_off,
2019   PACKET_Qbtrace_bts,
2020   PACKET_Qbtrace_pt,
2021   PACKET_qXfer_btrace,
2022
2023   /* Support for the QNonStop packet.  */
2024   PACKET_QNonStop,
2025
2026   /* Support for the QThreadEvents packet.  */
2027   PACKET_QThreadEvents,
2028
2029   /* Support for multi-process extensions.  */
2030   PACKET_multiprocess_feature,
2031
2032   /* Support for enabling and disabling tracepoints while a trace
2033      experiment is running.  */
2034   PACKET_EnableDisableTracepoints_feature,
2035
2036   /* Support for collecting strings using the tracenz bytecode.  */
2037   PACKET_tracenz_feature,
2038
2039   /* Support for continuing to run a trace experiment while GDB is
2040      disconnected.  */
2041   PACKET_DisconnectedTracing_feature,
2042
2043   /* Support for qXfer:libraries-svr4:read with a non-empty annex.  */
2044   PACKET_augmented_libraries_svr4_read_feature,
2045
2046   /* Support for the qXfer:btrace-conf:read packet.  */
2047   PACKET_qXfer_btrace_conf,
2048
2049   /* Support for the Qbtrace-conf:bts:size packet.  */
2050   PACKET_Qbtrace_conf_bts_size,
2051
2052   /* Support for swbreak+ feature.  */
2053   PACKET_swbreak_feature,
2054
2055   /* Support for hwbreak+ feature.  */
2056   PACKET_hwbreak_feature,
2057
2058   /* Support for fork events.  */
2059   PACKET_fork_event_feature,
2060
2061   /* Support for vfork events.  */
2062   PACKET_vfork_event_feature,
2063
2064   /* Support for the Qbtrace-conf:pt:size packet.  */
2065   PACKET_Qbtrace_conf_pt_size,
2066
2067   /* Support for exec events.  */
2068   PACKET_exec_event_feature,
2069
2070   /* Support for query supported vCont actions.  */
2071   PACKET_vContSupported,
2072
2073   /* Support remote CTRL-C.  */
2074   PACKET_vCtrlC,
2075
2076   /* Support TARGET_WAITKIND_NO_RESUMED.  */
2077   PACKET_no_resumed,
2078
2079   PACKET_MAX
2080 };
2081
2082 static struct packet_config remote_protocol_packets[PACKET_MAX];
2083
2084 /* Returns the packet's corresponding "set remote foo-packet" command
2085    state.  See struct packet_config for more details.  */
2086
2087 static enum auto_boolean
2088 packet_set_cmd_state (int packet)
2089 {
2090   return remote_protocol_packets[packet].detect;
2091 }
2092
2093 /* Returns whether a given packet or feature is supported.  This takes
2094    into account the state of the corresponding "set remote foo-packet"
2095    command, which may be used to bypass auto-detection.  */
2096
2097 static enum packet_support
2098 packet_config_support (struct packet_config *config)
2099 {
2100   switch (config->detect)
2101     {
2102     case AUTO_BOOLEAN_TRUE:
2103       return PACKET_ENABLE;
2104     case AUTO_BOOLEAN_FALSE:
2105       return PACKET_DISABLE;
2106     case AUTO_BOOLEAN_AUTO:
2107       return config->support;
2108     default:
2109       gdb_assert_not_reached (_("bad switch"));
2110     }
2111 }
2112
2113 /* Same as packet_config_support, but takes the packet's enum value as
2114    argument.  */
2115
2116 static enum packet_support
2117 packet_support (int packet)
2118 {
2119   struct packet_config *config = &remote_protocol_packets[packet];
2120
2121   return packet_config_support (config);
2122 }
2123
2124 static void
2125 show_remote_protocol_packet_cmd (struct ui_file *file, int from_tty,
2126                                  struct cmd_list_element *c,
2127                                  const char *value)
2128 {
2129   struct packet_config *packet;
2130
2131   for (packet = remote_protocol_packets;
2132        packet < &remote_protocol_packets[PACKET_MAX];
2133        packet++)
2134     {
2135       if (&packet->detect == c->var)
2136         {
2137           show_packet_config_cmd (packet);
2138           return;
2139         }
2140     }
2141   internal_error (__FILE__, __LINE__, _("Could not find config for %s"),
2142                   c->name);
2143 }
2144
2145 /* Should we try one of the 'Z' requests?  */
2146
2147 enum Z_packet_type
2148 {
2149   Z_PACKET_SOFTWARE_BP,
2150   Z_PACKET_HARDWARE_BP,
2151   Z_PACKET_WRITE_WP,
2152   Z_PACKET_READ_WP,
2153   Z_PACKET_ACCESS_WP,
2154   NR_Z_PACKET_TYPES
2155 };
2156
2157 /* For compatibility with older distributions.  Provide a ``set remote
2158    Z-packet ...'' command that updates all the Z packet types.  */
2159
2160 static enum auto_boolean remote_Z_packet_detect;
2161
2162 static void
2163 set_remote_protocol_Z_packet_cmd (const char *args, int from_tty,
2164                                   struct cmd_list_element *c)
2165 {
2166   int i;
2167
2168   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2169     remote_protocol_packets[PACKET_Z0 + i].detect = remote_Z_packet_detect;
2170 }
2171
2172 static void
2173 show_remote_protocol_Z_packet_cmd (struct ui_file *file, int from_tty,
2174                                    struct cmd_list_element *c,
2175                                    const char *value)
2176 {
2177   int i;
2178
2179   for (i = 0; i < NR_Z_PACKET_TYPES; i++)
2180     {
2181       show_packet_config_cmd (&remote_protocol_packets[PACKET_Z0 + i]);
2182     }
2183 }
2184
2185 /* Returns true if the multi-process extensions are in effect.  */
2186
2187 static int
2188 remote_multi_process_p (struct remote_state *rs)
2189 {
2190   return packet_support (PACKET_multiprocess_feature) == PACKET_ENABLE;
2191 }
2192
2193 /* Returns true if fork events are supported.  */
2194
2195 static int
2196 remote_fork_event_p (struct remote_state *rs)
2197 {
2198   return packet_support (PACKET_fork_event_feature) == PACKET_ENABLE;
2199 }
2200
2201 /* Returns true if vfork events are supported.  */
2202
2203 static int
2204 remote_vfork_event_p (struct remote_state *rs)
2205 {
2206   return packet_support (PACKET_vfork_event_feature) == PACKET_ENABLE;
2207 }
2208
2209 /* Returns true if exec events are supported.  */
2210
2211 static int
2212 remote_exec_event_p (struct remote_state *rs)
2213 {
2214   return packet_support (PACKET_exec_event_feature) == PACKET_ENABLE;
2215 }
2216
2217 /* Insert fork catchpoint target routine.  If fork events are enabled
2218    then return success, nothing more to do.  */
2219
2220 int
2221 remote_target::insert_fork_catchpoint (int pid)
2222 {
2223   struct remote_state *rs = get_remote_state ();
2224
2225   return !remote_fork_event_p (rs);
2226 }
2227
2228 /* Remove fork catchpoint target routine.  Nothing to do, just
2229    return success.  */
2230
2231 int
2232 remote_target::remove_fork_catchpoint (int pid)
2233 {
2234   return 0;
2235 }
2236
2237 /* Insert vfork catchpoint target routine.  If vfork events are enabled
2238    then return success, nothing more to do.  */
2239
2240 int
2241 remote_target::insert_vfork_catchpoint (int pid)
2242 {
2243   struct remote_state *rs = get_remote_state ();
2244
2245   return !remote_vfork_event_p (rs);
2246 }
2247
2248 /* Remove vfork catchpoint target routine.  Nothing to do, just
2249    return success.  */
2250
2251 int
2252 remote_target::remove_vfork_catchpoint (int pid)
2253 {
2254   return 0;
2255 }
2256
2257 /* Insert exec catchpoint target routine.  If exec events are
2258    enabled, just return success.  */
2259
2260 int
2261 remote_target::insert_exec_catchpoint (int pid)
2262 {
2263   struct remote_state *rs = get_remote_state ();
2264
2265   return !remote_exec_event_p (rs);
2266 }
2267
2268 /* Remove exec catchpoint target routine.  Nothing to do, just
2269    return success.  */
2270
2271 int
2272 remote_target::remove_exec_catchpoint (int pid)
2273 {
2274   return 0;
2275 }
2276
2277 \f
2278
2279 static ptid_t magic_null_ptid;
2280 static ptid_t not_sent_ptid;
2281 static ptid_t any_thread_ptid;
2282
2283 /* Find out if the stub attached to PID (and hence GDB should offer to
2284    detach instead of killing it when bailing out).  */
2285
2286 int
2287 remote_target::remote_query_attached (int pid)
2288 {
2289   struct remote_state *rs = get_remote_state ();
2290   size_t size = get_remote_packet_size ();
2291
2292   if (packet_support (PACKET_qAttached) == PACKET_DISABLE)
2293     return 0;
2294
2295   if (remote_multi_process_p (rs))
2296     xsnprintf (rs->buf, size, "qAttached:%x", pid);
2297   else
2298     xsnprintf (rs->buf, size, "qAttached");
2299
2300   putpkt (rs->buf);
2301   getpkt (&rs->buf, &rs->buf_size, 0);
2302
2303   switch (packet_ok (rs->buf,
2304                      &remote_protocol_packets[PACKET_qAttached]))
2305     {
2306     case PACKET_OK:
2307       if (strcmp (rs->buf, "1") == 0)
2308         return 1;
2309       break;
2310     case PACKET_ERROR:
2311       warning (_("Remote failure reply: %s"), rs->buf);
2312       break;
2313     case PACKET_UNKNOWN:
2314       break;
2315     }
2316
2317   return 0;
2318 }
2319
2320 /* Add PID to GDB's inferior table.  If FAKE_PID_P is true, then PID
2321    has been invented by GDB, instead of reported by the target.  Since
2322    we can be connected to a remote system before before knowing about
2323    any inferior, mark the target with execution when we find the first
2324    inferior.  If ATTACHED is 1, then we had just attached to this
2325    inferior.  If it is 0, then we just created this inferior.  If it
2326    is -1, then try querying the remote stub to find out if it had
2327    attached to the inferior or not.  If TRY_OPEN_EXEC is true then
2328    attempt to open this inferior's executable as the main executable
2329    if no main executable is open already.  */
2330
2331 inferior *
2332 remote_target::remote_add_inferior (int fake_pid_p, int pid, int attached,
2333                                     int try_open_exec)
2334 {
2335   struct inferior *inf;
2336
2337   /* Check whether this process we're learning about is to be
2338      considered attached, or if is to be considered to have been
2339      spawned by the stub.  */
2340   if (attached == -1)
2341     attached = remote_query_attached (pid);
2342
2343   if (gdbarch_has_global_solist (target_gdbarch ()))
2344     {
2345       /* If the target shares code across all inferiors, then every
2346          attach adds a new inferior.  */
2347       inf = add_inferior (pid);
2348
2349       /* ... and every inferior is bound to the same program space.
2350          However, each inferior may still have its own address
2351          space.  */
2352       inf->aspace = maybe_new_address_space ();
2353       inf->pspace = current_program_space;
2354     }
2355   else
2356     {
2357       /* In the traditional debugging scenario, there's a 1-1 match
2358          between program/address spaces.  We simply bind the inferior
2359          to the program space's address space.  */
2360       inf = current_inferior ();
2361       inferior_appeared (inf, pid);
2362     }
2363
2364   inf->attach_flag = attached;
2365   inf->fake_pid_p = fake_pid_p;
2366
2367   /* If no main executable is currently open then attempt to
2368      open the file that was executed to create this inferior.  */
2369   if (try_open_exec && get_exec_file (0) == NULL)
2370     exec_file_locate_attach (pid, 0, 1);
2371
2372   return inf;
2373 }
2374
2375 static remote_thread_info *get_remote_thread_info (thread_info *thread);
2376
2377 /* Add thread PTID to GDB's thread list.  Tag it as executing/running
2378    according to RUNNING.  */
2379
2380 void
2381 remote_target::remote_add_thread (ptid_t ptid, bool running, bool executing)
2382 {
2383   struct remote_state *rs = get_remote_state ();
2384   struct thread_info *thread;
2385
2386   /* GDB historically didn't pull threads in the initial connection
2387      setup.  If the remote target doesn't even have a concept of
2388      threads (e.g., a bare-metal target), even if internally we
2389      consider that a single-threaded target, mentioning a new thread
2390      might be confusing to the user.  Be silent then, preserving the
2391      age old behavior.  */
2392   if (rs->starting_up)
2393     thread = add_thread_silent (ptid);
2394   else
2395     thread = add_thread (ptid);
2396
2397   get_remote_thread_info (thread)->vcont_resumed = executing;
2398   set_executing (ptid, executing);
2399   set_running (ptid, running);
2400 }
2401
2402 /* Come here when we learn about a thread id from the remote target.
2403    It may be the first time we hear about such thread, so take the
2404    opportunity to add it to GDB's thread list.  In case this is the
2405    first time we're noticing its corresponding inferior, add it to
2406    GDB's inferior list as well.  EXECUTING indicates whether the
2407    thread is (internally) executing or stopped.  */
2408
2409 void
2410 remote_target::remote_notice_new_inferior (ptid_t currthread, int executing)
2411 {
2412   /* In non-stop mode, we assume new found threads are (externally)
2413      running until proven otherwise with a stop reply.  In all-stop,
2414      we can only get here if all threads are stopped.  */
2415   int running = target_is_non_stop_p () ? 1 : 0;
2416
2417   /* If this is a new thread, add it to GDB's thread list.
2418      If we leave it up to WFI to do this, bad things will happen.  */
2419
2420   if (in_thread_list (currthread) && is_exited (currthread))
2421     {
2422       /* We're seeing an event on a thread id we knew had exited.
2423          This has to be a new thread reusing the old id.  Add it.  */
2424       remote_add_thread (currthread, running, executing);
2425       return;
2426     }
2427
2428   if (!in_thread_list (currthread))
2429     {
2430       struct inferior *inf = NULL;
2431       int pid = ptid_get_pid (currthread);
2432
2433       if (ptid_is_pid (inferior_ptid)
2434           && pid == ptid_get_pid (inferior_ptid))
2435         {
2436           /* inferior_ptid has no thread member yet.  This can happen
2437              with the vAttach -> remote_wait,"TAAthread:" path if the
2438              stub doesn't support qC.  This is the first stop reported
2439              after an attach, so this is the main thread.  Update the
2440              ptid in the thread list.  */
2441           if (in_thread_list (pid_to_ptid (pid)))
2442             thread_change_ptid (inferior_ptid, currthread);
2443           else
2444             {
2445               remote_add_thread (currthread, running, executing);
2446               inferior_ptid = currthread;
2447             }
2448           return;
2449         }
2450
2451       if (ptid_equal (magic_null_ptid, inferior_ptid))
2452         {
2453           /* inferior_ptid is not set yet.  This can happen with the
2454              vRun -> remote_wait,"TAAthread:" path if the stub
2455              doesn't support qC.  This is the first stop reported
2456              after an attach, so this is the main thread.  Update the
2457              ptid in the thread list.  */
2458           thread_change_ptid (inferior_ptid, currthread);
2459           return;
2460         }
2461
2462       /* When connecting to a target remote, or to a target
2463          extended-remote which already was debugging an inferior, we
2464          may not know about it yet.  Add it before adding its child
2465          thread, so notifications are emitted in a sensible order.  */
2466       if (!in_inferior_list (ptid_get_pid (currthread)))
2467         {
2468           struct remote_state *rs = get_remote_state ();
2469           int fake_pid_p = !remote_multi_process_p (rs);
2470
2471           inf = remote_add_inferior (fake_pid_p,
2472                                      ptid_get_pid (currthread), -1, 1);
2473         }
2474
2475       /* This is really a new thread.  Add it.  */
2476       remote_add_thread (currthread, running, executing);
2477
2478       /* If we found a new inferior, let the common code do whatever
2479          it needs to with it (e.g., read shared libraries, insert
2480          breakpoints), unless we're just setting up an all-stop
2481          connection.  */
2482       if (inf != NULL)
2483         {
2484           struct remote_state *rs = get_remote_state ();
2485
2486           if (!rs->starting_up)
2487             notice_new_inferior (currthread, executing, 0);
2488         }
2489     }
2490 }
2491
2492 /* Return THREAD's private thread data, creating it if necessary.  */
2493
2494 static remote_thread_info *
2495 get_remote_thread_info (thread_info *thread)
2496 {
2497   gdb_assert (thread != NULL);
2498
2499   if (thread->priv == NULL)
2500     thread->priv.reset (new remote_thread_info);
2501
2502   return static_cast<remote_thread_info *> (thread->priv.get ());
2503 }
2504
2505 /* Return PTID's private thread data, creating it if necessary.  */
2506
2507 static remote_thread_info *
2508 get_remote_thread_info (ptid_t ptid)
2509 {
2510   struct thread_info *info = find_thread_ptid (ptid);
2511
2512   return get_remote_thread_info (info);
2513 }
2514
2515 /* Call this function as a result of
2516    1) A halt indication (T packet) containing a thread id
2517    2) A direct query of currthread
2518    3) Successful execution of set thread */
2519
2520 static void
2521 record_currthread (struct remote_state *rs, ptid_t currthread)
2522 {
2523   rs->general_thread = currthread;
2524 }
2525
2526 /* If 'QPassSignals' is supported, tell the remote stub what signals
2527    it can simply pass through to the inferior without reporting.  */
2528
2529 void
2530 remote_target::pass_signals (int numsigs, unsigned char *pass_signals)
2531 {
2532   if (packet_support (PACKET_QPassSignals) != PACKET_DISABLE)
2533     {
2534       char *pass_packet, *p;
2535       int count = 0, i;
2536       struct remote_state *rs = get_remote_state ();
2537
2538       gdb_assert (numsigs < 256);
2539       for (i = 0; i < numsigs; i++)
2540         {
2541           if (pass_signals[i])
2542             count++;
2543         }
2544       pass_packet = (char *) xmalloc (count * 3 + strlen ("QPassSignals:") + 1);
2545       strcpy (pass_packet, "QPassSignals:");
2546       p = pass_packet + strlen (pass_packet);
2547       for (i = 0; i < numsigs; i++)
2548         {
2549           if (pass_signals[i])
2550             {
2551               if (i >= 16)
2552                 *p++ = tohex (i >> 4);
2553               *p++ = tohex (i & 15);
2554               if (count)
2555                 *p++ = ';';
2556               else
2557                 break;
2558               count--;
2559             }
2560         }
2561       *p = 0;
2562       if (!rs->last_pass_packet || strcmp (rs->last_pass_packet, pass_packet))
2563         {
2564           putpkt (pass_packet);
2565           getpkt (&rs->buf, &rs->buf_size, 0);
2566           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QPassSignals]);
2567           if (rs->last_pass_packet)
2568             xfree (rs->last_pass_packet);
2569           rs->last_pass_packet = pass_packet;
2570         }
2571       else
2572         xfree (pass_packet);
2573     }
2574 }
2575
2576 /* If 'QCatchSyscalls' is supported, tell the remote stub
2577    to report syscalls to GDB.  */
2578
2579 int
2580 remote_target::set_syscall_catchpoint (int pid, bool needed, int any_count,
2581                                        gdb::array_view<const int> syscall_counts)
2582 {
2583   const char *catch_packet;
2584   enum packet_result result;
2585   int n_sysno = 0;
2586
2587   if (packet_support (PACKET_QCatchSyscalls) == PACKET_DISABLE)
2588     {
2589       /* Not supported.  */
2590       return 1;
2591     }
2592
2593   if (needed && any_count == 0)
2594     {
2595       /* Count how many syscalls are to be caught.  */
2596       for (size_t i = 0; i < syscall_counts.size (); i++)
2597         {
2598           if (syscall_counts[i] != 0)
2599             n_sysno++;
2600         }
2601     }
2602
2603   if (remote_debug)
2604     {
2605       fprintf_unfiltered (gdb_stdlog,
2606                           "remote_set_syscall_catchpoint "
2607                           "pid %d needed %d any_count %d n_sysno %d\n",
2608                           pid, needed, any_count, n_sysno);
2609     }
2610
2611   std::string built_packet;
2612   if (needed)
2613     {
2614       /* Prepare a packet with the sysno list, assuming max 8+1
2615          characters for a sysno.  If the resulting packet size is too
2616          big, fallback on the non-selective packet.  */
2617       const int maxpktsz = strlen ("QCatchSyscalls:1") + n_sysno * 9 + 1;
2618       built_packet.reserve (maxpktsz);
2619       built_packet = "QCatchSyscalls:1";
2620       if (any_count == 0)
2621         {
2622           /* Add in each syscall to be caught.  */
2623           for (size_t i = 0; i < syscall_counts.size (); i++)
2624             {
2625               if (syscall_counts[i] != 0)
2626                 string_appendf (built_packet, ";%zx", i);
2627             }
2628         }
2629       if (built_packet.size () > get_remote_packet_size ())
2630         {
2631           /* catch_packet too big.  Fallback to less efficient
2632              non selective mode, with GDB doing the filtering.  */
2633           catch_packet = "QCatchSyscalls:1";
2634         }
2635       else
2636         catch_packet = built_packet.c_str ();
2637     }
2638   else
2639     catch_packet = "QCatchSyscalls:0";
2640
2641   struct remote_state *rs = get_remote_state ();
2642
2643   putpkt (catch_packet);
2644   getpkt (&rs->buf, &rs->buf_size, 0);
2645   result = packet_ok (rs->buf, &remote_protocol_packets[PACKET_QCatchSyscalls]);
2646   if (result == PACKET_OK)
2647     return 0;
2648   else
2649     return -1;
2650 }
2651
2652 /* If 'QProgramSignals' is supported, tell the remote stub what
2653    signals it should pass through to the inferior when detaching.  */
2654
2655 void
2656 remote_target::program_signals (int numsigs, unsigned char *signals)
2657 {
2658   if (packet_support (PACKET_QProgramSignals) != PACKET_DISABLE)
2659     {
2660       char *packet, *p;
2661       int count = 0, i;
2662       struct remote_state *rs = get_remote_state ();
2663
2664       gdb_assert (numsigs < 256);
2665       for (i = 0; i < numsigs; i++)
2666         {
2667           if (signals[i])
2668             count++;
2669         }
2670       packet = (char *) xmalloc (count * 3 + strlen ("QProgramSignals:") + 1);
2671       strcpy (packet, "QProgramSignals:");
2672       p = packet + strlen (packet);
2673       for (i = 0; i < numsigs; i++)
2674         {
2675           if (signal_pass_state (i))
2676             {
2677               if (i >= 16)
2678                 *p++ = tohex (i >> 4);
2679               *p++ = tohex (i & 15);
2680               if (count)
2681                 *p++ = ';';
2682               else
2683                 break;
2684               count--;
2685             }
2686         }
2687       *p = 0;
2688       if (!rs->last_program_signals_packet
2689           || strcmp (rs->last_program_signals_packet, packet) != 0)
2690         {
2691           putpkt (packet);
2692           getpkt (&rs->buf, &rs->buf_size, 0);
2693           packet_ok (rs->buf, &remote_protocol_packets[PACKET_QProgramSignals]);
2694           xfree (rs->last_program_signals_packet);
2695           rs->last_program_signals_packet = packet;
2696         }
2697       else
2698         xfree (packet);
2699     }
2700 }
2701
2702 /* If PTID is MAGIC_NULL_PTID, don't set any thread.  If PTID is
2703    MINUS_ONE_PTID, set the thread to -1, so the stub returns the
2704    thread.  If GEN is set, set the general thread, if not, then set
2705    the step/continue thread.  */
2706 void
2707 remote_target::set_thread (ptid_t ptid, int gen)
2708 {
2709   struct remote_state *rs = get_remote_state ();
2710   ptid_t state = gen ? rs->general_thread : rs->continue_thread;
2711   char *buf = rs->buf;
2712   char *endbuf = rs->buf + get_remote_packet_size ();
2713
2714   if (ptid_equal (state, ptid))
2715     return;
2716
2717   *buf++ = 'H';
2718   *buf++ = gen ? 'g' : 'c';
2719   if (ptid_equal (ptid, magic_null_ptid))
2720     xsnprintf (buf, endbuf - buf, "0");
2721   else if (ptid_equal (ptid, any_thread_ptid))
2722     xsnprintf (buf, endbuf - buf, "0");
2723   else if (ptid_equal (ptid, minus_one_ptid))
2724     xsnprintf (buf, endbuf - buf, "-1");
2725   else
2726     write_ptid (buf, endbuf, ptid);
2727   putpkt (rs->buf);
2728   getpkt (&rs->buf, &rs->buf_size, 0);
2729   if (gen)
2730     rs->general_thread = ptid;
2731   else
2732     rs->continue_thread = ptid;
2733 }
2734
2735 void
2736 remote_target::set_general_thread (ptid_t ptid)
2737 {
2738   set_thread (ptid, 1);
2739 }
2740
2741 void
2742 remote_target::set_continue_thread (ptid_t ptid)
2743 {
2744   set_thread (ptid, 0);
2745 }
2746
2747 /* Change the remote current process.  Which thread within the process
2748    ends up selected isn't important, as long as it is the same process
2749    as what INFERIOR_PTID points to.
2750
2751    This comes from that fact that there is no explicit notion of
2752    "selected process" in the protocol.  The selected process for
2753    general operations is the process the selected general thread
2754    belongs to.  */
2755
2756 void
2757 remote_target::set_general_process ()
2758 {
2759   struct remote_state *rs = get_remote_state ();
2760
2761   /* If the remote can't handle multiple processes, don't bother.  */
2762   if (!remote_multi_process_p (rs))
2763     return;
2764
2765   /* We only need to change the remote current thread if it's pointing
2766      at some other process.  */
2767   if (ptid_get_pid (rs->general_thread) != ptid_get_pid (inferior_ptid))
2768     set_general_thread (inferior_ptid);
2769 }
2770
2771 \f
2772 /* Return nonzero if this is the main thread that we made up ourselves
2773    to model non-threaded targets as single-threaded.  */
2774
2775 static int
2776 remote_thread_always_alive (ptid_t ptid)
2777 {
2778   if (ptid_equal (ptid, magic_null_ptid))
2779     /* The main thread is always alive.  */
2780     return 1;
2781
2782   if (ptid_get_pid (ptid) != 0 && ptid_get_lwp (ptid) == 0)
2783     /* The main thread is always alive.  This can happen after a
2784        vAttach, if the remote side doesn't support
2785        multi-threading.  */
2786     return 1;
2787
2788   return 0;
2789 }
2790
2791 /* Return nonzero if the thread PTID is still alive on the remote
2792    system.  */
2793
2794 bool
2795 remote_target::thread_alive (ptid_t ptid)
2796 {
2797   struct remote_state *rs = get_remote_state ();
2798   char *p, *endp;
2799
2800   /* Check if this is a thread that we made up ourselves to model
2801      non-threaded targets as single-threaded.  */
2802   if (remote_thread_always_alive (ptid))
2803     return 1;
2804
2805   p = rs->buf;
2806   endp = rs->buf + get_remote_packet_size ();
2807
2808   *p++ = 'T';
2809   write_ptid (p, endp, ptid);
2810
2811   putpkt (rs->buf);
2812   getpkt (&rs->buf, &rs->buf_size, 0);
2813   return (rs->buf[0] == 'O' && rs->buf[1] == 'K');
2814 }
2815
2816 /* Return a pointer to a thread name if we know it and NULL otherwise.
2817    The thread_info object owns the memory for the name.  */
2818
2819 const char *
2820 remote_target::thread_name (struct thread_info *info)
2821 {
2822   if (info->priv != NULL)
2823     {
2824       const std::string &name = get_remote_thread_info (info)->name;
2825       return !name.empty () ? name.c_str () : NULL;
2826     }
2827
2828   return NULL;
2829 }
2830
2831 /* About these extended threadlist and threadinfo packets.  They are
2832    variable length packets but, the fields within them are often fixed
2833    length.  They are redundent enough to send over UDP as is the
2834    remote protocol in general.  There is a matching unit test module
2835    in libstub.  */
2836
2837 /* WARNING: This threadref data structure comes from the remote O.S.,
2838    libstub protocol encoding, and remote.c.  It is not particularly
2839    changable.  */
2840
2841 /* Right now, the internal structure is int. We want it to be bigger.
2842    Plan to fix this.  */
2843
2844 typedef int gdb_threadref;      /* Internal GDB thread reference.  */
2845
2846 /* gdb_ext_thread_info is an internal GDB data structure which is
2847    equivalent to the reply of the remote threadinfo packet.  */
2848
2849 struct gdb_ext_thread_info
2850   {
2851     threadref threadid;         /* External form of thread reference.  */
2852     int active;                 /* Has state interesting to GDB?
2853                                    regs, stack.  */
2854     char display[256];          /* Brief state display, name,
2855                                    blocked/suspended.  */
2856     char shortname[32];         /* To be used to name threads.  */
2857     char more_display[256];     /* Long info, statistics, queue depth,
2858                                    whatever.  */
2859   };
2860
2861 /* The volume of remote transfers can be limited by submitting
2862    a mask containing bits specifying the desired information.
2863    Use a union of these values as the 'selection' parameter to
2864    get_thread_info.  FIXME: Make these TAG names more thread specific.  */
2865
2866 #define TAG_THREADID 1
2867 #define TAG_EXISTS 2
2868 #define TAG_DISPLAY 4
2869 #define TAG_THREADNAME 8
2870 #define TAG_MOREDISPLAY 16
2871
2872 #define BUF_THREAD_ID_SIZE (OPAQUETHREADBYTES * 2)
2873
2874 static char *unpack_nibble (char *buf, int *val);
2875
2876 static char *unpack_byte (char *buf, int *value);
2877
2878 static char *pack_int (char *buf, int value);
2879
2880 static char *unpack_int (char *buf, int *value);
2881
2882 static char *unpack_string (char *src, char *dest, int length);
2883
2884 static char *pack_threadid (char *pkt, threadref *id);
2885
2886 static char *unpack_threadid (char *inbuf, threadref *id);
2887
2888 void int_to_threadref (threadref *id, int value);
2889
2890 static int threadref_to_int (threadref *ref);
2891
2892 static void copy_threadref (threadref *dest, threadref *src);
2893
2894 static int threadmatch (threadref *dest, threadref *src);
2895
2896 static char *pack_threadinfo_request (char *pkt, int mode,
2897                                       threadref *id);
2898
2899 static char *pack_threadlist_request (char *pkt, int startflag,
2900                                       int threadcount,
2901                                       threadref *nextthread);
2902
2903 static int remote_newthread_step (threadref *ref, void *context);
2904
2905
2906 /* Write a PTID to BUF.  ENDBUF points to one-passed-the-end of the
2907    buffer we're allowed to write to.  Returns
2908    BUF+CHARACTERS_WRITTEN.  */
2909
2910 char *
2911 remote_target::write_ptid (char *buf, const char *endbuf, ptid_t ptid)
2912 {
2913   int pid, tid;
2914   struct remote_state *rs = get_remote_state ();
2915
2916   if (remote_multi_process_p (rs))
2917     {
2918       pid = ptid_get_pid (ptid);
2919       if (pid < 0)
2920         buf += xsnprintf (buf, endbuf - buf, "p-%x.", -pid);
2921       else
2922         buf += xsnprintf (buf, endbuf - buf, "p%x.", pid);
2923     }
2924   tid = ptid_get_lwp (ptid);
2925   if (tid < 0)
2926     buf += xsnprintf (buf, endbuf - buf, "-%x", -tid);
2927   else
2928     buf += xsnprintf (buf, endbuf - buf, "%x", tid);
2929
2930   return buf;
2931 }
2932
2933 /* Extract a PTID from BUF.  If non-null, OBUF is set to one past the
2934    last parsed char.  Returns null_ptid if no thread id is found, and
2935    throws an error if the thread id has an invalid format.  */
2936
2937 static ptid_t
2938 read_ptid (const char *buf, const char **obuf)
2939 {
2940   const char *p = buf;
2941   const char *pp;
2942   ULONGEST pid = 0, tid = 0;
2943
2944   if (*p == 'p')
2945     {
2946       /* Multi-process ptid.  */
2947       pp = unpack_varlen_hex (p + 1, &pid);
2948       if (*pp != '.')
2949         error (_("invalid remote ptid: %s"), p);
2950
2951       p = pp;
2952       pp = unpack_varlen_hex (p + 1, &tid);
2953       if (obuf)
2954         *obuf = pp;
2955       return ptid_build (pid, tid, 0);
2956     }
2957
2958   /* No multi-process.  Just a tid.  */
2959   pp = unpack_varlen_hex (p, &tid);
2960
2961   /* Return null_ptid when no thread id is found.  */
2962   if (p == pp)
2963     {
2964       if (obuf)
2965         *obuf = pp;
2966       return null_ptid;
2967     }
2968
2969   /* Since the stub is not sending a process id, then default to
2970      what's in inferior_ptid, unless it's null at this point.  If so,
2971      then since there's no way to know the pid of the reported
2972      threads, use the magic number.  */
2973   if (ptid_equal (inferior_ptid, null_ptid))
2974     pid = ptid_get_pid (magic_null_ptid);
2975   else
2976     pid = ptid_get_pid (inferior_ptid);
2977
2978   if (obuf)
2979     *obuf = pp;
2980   return ptid_build (pid, tid, 0);
2981 }
2982
2983 static int
2984 stubhex (int ch)
2985 {
2986   if (ch >= 'a' && ch <= 'f')
2987     return ch - 'a' + 10;
2988   if (ch >= '0' && ch <= '9')
2989     return ch - '0';
2990   if (ch >= 'A' && ch <= 'F')
2991     return ch - 'A' + 10;
2992   return -1;
2993 }
2994
2995 static int
2996 stub_unpack_int (char *buff, int fieldlength)
2997 {
2998   int nibble;
2999   int retval = 0;
3000
3001   while (fieldlength)
3002     {
3003       nibble = stubhex (*buff++);
3004       retval |= nibble;
3005       fieldlength--;
3006       if (fieldlength)
3007         retval = retval << 4;
3008     }
3009   return retval;
3010 }
3011
3012 static char *
3013 unpack_nibble (char *buf, int *val)
3014 {
3015   *val = fromhex (*buf++);
3016   return buf;
3017 }
3018
3019 static char *
3020 unpack_byte (char *buf, int *value)
3021 {
3022   *value = stub_unpack_int (buf, 2);
3023   return buf + 2;
3024 }
3025
3026 static char *
3027 pack_int (char *buf, int value)
3028 {
3029   buf = pack_hex_byte (buf, (value >> 24) & 0xff);
3030   buf = pack_hex_byte (buf, (value >> 16) & 0xff);
3031   buf = pack_hex_byte (buf, (value >> 8) & 0x0ff);
3032   buf = pack_hex_byte (buf, (value & 0xff));
3033   return buf;
3034 }
3035
3036 static char *
3037 unpack_int (char *buf, int *value)
3038 {
3039   *value = stub_unpack_int (buf, 8);
3040   return buf + 8;
3041 }
3042
3043 #if 0                   /* Currently unused, uncomment when needed.  */
3044 static char *pack_string (char *pkt, char *string);
3045
3046 static char *
3047 pack_string (char *pkt, char *string)
3048 {
3049   char ch;
3050   int len;
3051
3052   len = strlen (string);
3053   if (len > 200)
3054     len = 200;          /* Bigger than most GDB packets, junk???  */
3055   pkt = pack_hex_byte (pkt, len);
3056   while (len-- > 0)
3057     {
3058       ch = *string++;
3059       if ((ch == '\0') || (ch == '#'))
3060         ch = '*';               /* Protect encapsulation.  */
3061       *pkt++ = ch;
3062     }
3063   return pkt;
3064 }
3065 #endif /* 0 (unused) */
3066
3067 static char *
3068 unpack_string (char *src, char *dest, int length)
3069 {
3070   while (length--)
3071     *dest++ = *src++;
3072   *dest = '\0';
3073   return src;
3074 }
3075
3076 static char *
3077 pack_threadid (char *pkt, threadref *id)
3078 {
3079   char *limit;
3080   unsigned char *altid;
3081
3082   altid = (unsigned char *) id;
3083   limit = pkt + BUF_THREAD_ID_SIZE;
3084   while (pkt < limit)
3085     pkt = pack_hex_byte (pkt, *altid++);
3086   return pkt;
3087 }
3088
3089
3090 static char *
3091 unpack_threadid (char *inbuf, threadref *id)
3092 {
3093   char *altref;
3094   char *limit = inbuf + BUF_THREAD_ID_SIZE;
3095   int x, y;
3096
3097   altref = (char *) id;
3098
3099   while (inbuf < limit)
3100     {
3101       x = stubhex (*inbuf++);
3102       y = stubhex (*inbuf++);
3103       *altref++ = (x << 4) | y;
3104     }
3105   return inbuf;
3106 }
3107
3108 /* Externally, threadrefs are 64 bits but internally, they are still
3109    ints.  This is due to a mismatch of specifications.  We would like
3110    to use 64bit thread references internally.  This is an adapter
3111    function.  */
3112
3113 void
3114 int_to_threadref (threadref *id, int value)
3115 {
3116   unsigned char *scan;
3117
3118   scan = (unsigned char *) id;
3119   {
3120     int i = 4;
3121     while (i--)
3122       *scan++ = 0;
3123   }
3124   *scan++ = (value >> 24) & 0xff;
3125   *scan++ = (value >> 16) & 0xff;
3126   *scan++ = (value >> 8) & 0xff;
3127   *scan++ = (value & 0xff);
3128 }
3129
3130 static int
3131 threadref_to_int (threadref *ref)
3132 {
3133   int i, value = 0;
3134   unsigned char *scan;
3135
3136   scan = *ref;
3137   scan += 4;
3138   i = 4;
3139   while (i-- > 0)
3140     value = (value << 8) | ((*scan++) & 0xff);
3141   return value;
3142 }
3143
3144 static void
3145 copy_threadref (threadref *dest, threadref *src)
3146 {
3147   int i;
3148   unsigned char *csrc, *cdest;
3149
3150   csrc = (unsigned char *) src;
3151   cdest = (unsigned char *) dest;
3152   i = 8;
3153   while (i--)
3154     *cdest++ = *csrc++;
3155 }
3156
3157 static int
3158 threadmatch (threadref *dest, threadref *src)
3159 {
3160   /* Things are broken right now, so just assume we got a match.  */
3161 #if 0
3162   unsigned char *srcp, *destp;
3163   int i, result;
3164   srcp = (char *) src;
3165   destp = (char *) dest;
3166
3167   result = 1;
3168   while (i-- > 0)
3169     result &= (*srcp++ == *destp++) ? 1 : 0;
3170   return result;
3171 #endif
3172   return 1;
3173 }
3174
3175 /*
3176    threadid:1,        # always request threadid
3177    context_exists:2,
3178    display:4,
3179    unique_name:8,
3180    more_display:16
3181  */
3182
3183 /* Encoding:  'Q':8,'P':8,mask:32,threadid:64 */
3184
3185 static char *
3186 pack_threadinfo_request (char *pkt, int mode, threadref *id)
3187 {
3188   *pkt++ = 'q';                         /* Info Query */
3189   *pkt++ = 'P';                         /* process or thread info */
3190   pkt = pack_int (pkt, mode);           /* mode */
3191   pkt = pack_threadid (pkt, id);        /* threadid */
3192   *pkt = '\0';                          /* terminate */
3193   return pkt;
3194 }
3195
3196 /* These values tag the fields in a thread info response packet.  */
3197 /* Tagging the fields allows us to request specific fields and to
3198    add more fields as time goes by.  */
3199
3200 #define TAG_THREADID 1          /* Echo the thread identifier.  */
3201 #define TAG_EXISTS 2            /* Is this process defined enough to
3202                                    fetch registers and its stack?  */
3203 #define TAG_DISPLAY 4           /* A short thing maybe to put on a window */
3204 #define TAG_THREADNAME 8        /* string, maps 1-to-1 with a thread is.  */
3205 #define TAG_MOREDISPLAY 16      /* Whatever the kernel wants to say about
3206                                    the process.  */
3207
3208 int
3209 remote_target::remote_unpack_thread_info_response (char *pkt,
3210                                                    threadref *expectedref,
3211                                                    gdb_ext_thread_info *info)
3212 {
3213   struct remote_state *rs = get_remote_state ();
3214   int mask, length;
3215   int tag;
3216   threadref ref;
3217   char *limit = pkt + rs->buf_size; /* Plausible parsing limit.  */
3218   int retval = 1;
3219
3220   /* info->threadid = 0; FIXME: implement zero_threadref.  */
3221   info->active = 0;
3222   info->display[0] = '\0';
3223   info->shortname[0] = '\0';
3224   info->more_display[0] = '\0';
3225
3226   /* Assume the characters indicating the packet type have been
3227      stripped.  */
3228   pkt = unpack_int (pkt, &mask);        /* arg mask */
3229   pkt = unpack_threadid (pkt, &ref);
3230
3231   if (mask == 0)
3232     warning (_("Incomplete response to threadinfo request."));
3233   if (!threadmatch (&ref, expectedref))
3234     {                   /* This is an answer to a different request.  */
3235       warning (_("ERROR RMT Thread info mismatch."));
3236       return 0;
3237     }
3238   copy_threadref (&info->threadid, &ref);
3239
3240   /* Loop on tagged fields , try to bail if somthing goes wrong.  */
3241
3242   /* Packets are terminated with nulls.  */
3243   while ((pkt < limit) && mask && *pkt)
3244     {
3245       pkt = unpack_int (pkt, &tag);     /* tag */
3246       pkt = unpack_byte (pkt, &length); /* length */
3247       if (!(tag & mask))                /* Tags out of synch with mask.  */
3248         {
3249           warning (_("ERROR RMT: threadinfo tag mismatch."));
3250           retval = 0;
3251           break;
3252         }
3253       if (tag == TAG_THREADID)
3254         {
3255           if (length != 16)
3256             {
3257               warning (_("ERROR RMT: length of threadid is not 16."));
3258               retval = 0;
3259               break;
3260             }
3261           pkt = unpack_threadid (pkt, &ref);
3262           mask = mask & ~TAG_THREADID;
3263           continue;
3264         }
3265       if (tag == TAG_EXISTS)
3266         {
3267           info->active = stub_unpack_int (pkt, length);
3268           pkt += length;
3269           mask = mask & ~(TAG_EXISTS);
3270           if (length > 8)
3271             {
3272               warning (_("ERROR RMT: 'exists' length too long."));
3273               retval = 0;
3274               break;
3275             }
3276           continue;
3277         }
3278       if (tag == TAG_THREADNAME)
3279         {
3280           pkt = unpack_string (pkt, &info->shortname[0], length);
3281           mask = mask & ~TAG_THREADNAME;
3282           continue;
3283         }
3284       if (tag == TAG_DISPLAY)
3285         {
3286           pkt = unpack_string (pkt, &info->display[0], length);
3287           mask = mask & ~TAG_DISPLAY;
3288           continue;
3289         }
3290       if (tag == TAG_MOREDISPLAY)
3291         {
3292           pkt = unpack_string (pkt, &info->more_display[0], length);
3293           mask = mask & ~TAG_MOREDISPLAY;
3294           continue;
3295         }
3296       warning (_("ERROR RMT: unknown thread info tag."));
3297       break;                    /* Not a tag we know about.  */
3298     }
3299   return retval;
3300 }
3301
3302 int
3303 remote_target::remote_get_threadinfo (threadref *threadid,
3304                                       int fieldset,
3305                                       gdb_ext_thread_info *info)
3306 {
3307   struct remote_state *rs = get_remote_state ();
3308   int result;
3309
3310   pack_threadinfo_request (rs->buf, fieldset, threadid);
3311   putpkt (rs->buf);
3312   getpkt (&rs->buf, &rs->buf_size, 0);
3313
3314   if (rs->buf[0] == '\0')
3315     return 0;
3316
3317   result = remote_unpack_thread_info_response (rs->buf + 2,
3318                                                threadid, info);
3319   return result;
3320 }
3321
3322 /*    Format: i'Q':8,i"L":8,initflag:8,batchsize:16,lastthreadid:32   */
3323
3324 static char *
3325 pack_threadlist_request (char *pkt, int startflag, int threadcount,
3326                          threadref *nextthread)
3327 {
3328   *pkt++ = 'q';                 /* info query packet */
3329   *pkt++ = 'L';                 /* Process LIST or threadLIST request */
3330   pkt = pack_nibble (pkt, startflag);           /* initflag 1 bytes */
3331   pkt = pack_hex_byte (pkt, threadcount);       /* threadcount 2 bytes */
3332   pkt = pack_threadid (pkt, nextthread);        /* 64 bit thread identifier */
3333   *pkt = '\0';
3334   return pkt;
3335 }
3336
3337 /* Encoding:   'q':8,'M':8,count:16,done:8,argthreadid:64,(threadid:64)* */
3338
3339 int
3340 remote_target::parse_threadlist_response (char *pkt, int result_limit,
3341                                           threadref *original_echo,
3342                                           threadref *resultlist,
3343                                           int *doneflag)
3344 {
3345   struct remote_state *rs = get_remote_state ();
3346   char *limit;
3347   int count, resultcount, done;
3348
3349   resultcount = 0;
3350   /* Assume the 'q' and 'M chars have been stripped.  */
3351   limit = pkt + (rs->buf_size - BUF_THREAD_ID_SIZE);
3352   /* done parse past here */
3353   pkt = unpack_byte (pkt, &count);      /* count field */
3354   pkt = unpack_nibble (pkt, &done);
3355   /* The first threadid is the argument threadid.  */
3356   pkt = unpack_threadid (pkt, original_echo);   /* should match query packet */
3357   while ((count-- > 0) && (pkt < limit))
3358     {
3359       pkt = unpack_threadid (pkt, resultlist++);
3360       if (resultcount++ >= result_limit)
3361         break;
3362     }
3363   if (doneflag)
3364     *doneflag = done;
3365   return resultcount;
3366 }
3367
3368 /* Fetch the next batch of threads from the remote.  Returns -1 if the
3369    qL packet is not supported, 0 on error and 1 on success.  */
3370
3371 int
3372 remote_target::remote_get_threadlist (int startflag, threadref *nextthread,
3373                                       int result_limit, int *done, int *result_count,
3374                                       threadref *threadlist)
3375 {
3376   struct remote_state *rs = get_remote_state ();
3377   int result = 1;
3378
3379   /* Trancate result limit to be smaller than the packet size.  */
3380   if ((((result_limit + 1) * BUF_THREAD_ID_SIZE) + 10)
3381       >= get_remote_packet_size ())
3382     result_limit = (get_remote_packet_size () / BUF_THREAD_ID_SIZE) - 2;
3383
3384   pack_threadlist_request (rs->buf, startflag, result_limit, nextthread);
3385   putpkt (rs->buf);
3386   getpkt (&rs->buf, &rs->buf_size, 0);
3387   if (*rs->buf == '\0')
3388     {
3389       /* Packet not supported.  */
3390       return -1;
3391     }
3392
3393   *result_count =
3394     parse_threadlist_response (rs->buf + 2, result_limit,
3395                                &rs->echo_nextthread, threadlist, done);
3396
3397   if (!threadmatch (&rs->echo_nextthread, nextthread))
3398     {
3399       /* FIXME: This is a good reason to drop the packet.  */
3400       /* Possably, there is a duplicate response.  */
3401       /* Possabilities :
3402          retransmit immediatly - race conditions
3403          retransmit after timeout - yes
3404          exit
3405          wait for packet, then exit
3406        */
3407       warning (_("HMM: threadlist did not echo arg thread, dropping it."));
3408       return 0;                 /* I choose simply exiting.  */
3409     }
3410   if (*result_count <= 0)
3411     {
3412       if (*done != 1)
3413         {
3414           warning (_("RMT ERROR : failed to get remote thread list."));
3415           result = 0;
3416         }
3417       return result;            /* break; */
3418     }
3419   if (*result_count > result_limit)
3420     {
3421       *result_count = 0;
3422       warning (_("RMT ERROR: threadlist response longer than requested."));
3423       return 0;
3424     }
3425   return result;
3426 }
3427
3428 /* Fetch the list of remote threads, with the qL packet, and call
3429    STEPFUNCTION for each thread found.  Stops iterating and returns 1
3430    if STEPFUNCTION returns true.  Stops iterating and returns 0 if the
3431    STEPFUNCTION returns false.  If the packet is not supported,
3432    returns -1.  */
3433
3434 int
3435 remote_target::remote_threadlist_iterator (rmt_thread_action stepfunction,
3436                                            void *context, int looplimit)
3437 {
3438   struct remote_state *rs = get_remote_state ();
3439   int done, i, result_count;
3440   int startflag = 1;
3441   int result = 1;
3442   int loopcount = 0;
3443
3444   done = 0;
3445   while (!done)
3446     {
3447       if (loopcount++ > looplimit)
3448         {
3449           result = 0;
3450           warning (_("Remote fetch threadlist -infinite loop-."));
3451           break;
3452         }
3453       result = remote_get_threadlist (startflag, &rs->nextthread,
3454                                       MAXTHREADLISTRESULTS,
3455                                       &done, &result_count,
3456                                       rs->resultthreadlist);
3457       if (result <= 0)
3458         break;
3459       /* Clear for later iterations.  */
3460       startflag = 0;
3461       /* Setup to resume next batch of thread references, set nextthread.  */
3462       if (result_count >= 1)
3463         copy_threadref (&rs->nextthread,
3464                         &rs->resultthreadlist[result_count - 1]);
3465       i = 0;
3466       while (result_count--)
3467         {
3468           if (!(*stepfunction) (&rs->resultthreadlist[i++], context))
3469             {
3470               result = 0;
3471               break;
3472             }
3473         }
3474     }
3475   return result;
3476 }
3477
3478 /* A thread found on the remote target.  */
3479
3480 struct thread_item
3481 {
3482   explicit thread_item (ptid_t ptid_)
3483   : ptid (ptid_)
3484   {}
3485
3486   thread_item (thread_item &&other) = default;
3487   thread_item &operator= (thread_item &&other) = default;
3488
3489   DISABLE_COPY_AND_ASSIGN (thread_item);
3490
3491   /* The thread's PTID.  */
3492   ptid_t ptid;
3493
3494   /* The thread's extra info.  */
3495   std::string extra;
3496
3497   /* The thread's name.  */
3498   std::string name;
3499
3500   /* The core the thread was running on.  -1 if not known.  */
3501   int core = -1;
3502
3503   /* The thread handle associated with the thread.  */
3504   gdb::byte_vector thread_handle;
3505 };
3506
3507 /* Context passed around to the various methods listing remote
3508    threads.  As new threads are found, they're added to the ITEMS
3509    vector.  */
3510
3511 struct threads_listing_context
3512 {
3513   /* Return true if this object contains an entry for a thread with ptid
3514      PTID.  */
3515
3516   bool contains_thread (ptid_t ptid) const
3517   {
3518     auto match_ptid = [&] (const thread_item &item)
3519       {
3520         return item.ptid == ptid;
3521       };
3522
3523     auto it = std::find_if (this->items.begin (),
3524                             this->items.end (),
3525                             match_ptid);
3526
3527     return it != this->items.end ();
3528   }
3529
3530   /* Remove the thread with ptid PTID.  */
3531
3532   void remove_thread (ptid_t ptid)
3533   {
3534     auto match_ptid = [&] (const thread_item &item)
3535       {
3536         return item.ptid == ptid;
3537       };
3538
3539     auto it = std::remove_if (this->items.begin (),
3540                               this->items.end (),
3541                               match_ptid);
3542
3543     if (it != this->items.end ())
3544       this->items.erase (it);
3545   }
3546
3547   /* The threads found on the remote target.  */
3548   std::vector<thread_item> items;
3549 };
3550
3551 static int
3552 remote_newthread_step (threadref *ref, void *data)
3553 {
3554   struct threads_listing_context *context
3555     = (struct threads_listing_context *) data;
3556   int pid = inferior_ptid.pid ();
3557   int lwp = threadref_to_int (ref);
3558   ptid_t ptid (pid, lwp);
3559
3560   context->items.emplace_back (ptid);
3561
3562   return 1;                     /* continue iterator */
3563 }
3564
3565 #define CRAZY_MAX_THREADS 1000
3566
3567 ptid_t
3568 remote_target::remote_current_thread (ptid_t oldpid)
3569 {
3570   struct remote_state *rs = get_remote_state ();
3571
3572   putpkt ("qC");
3573   getpkt (&rs->buf, &rs->buf_size, 0);
3574   if (rs->buf[0] == 'Q' && rs->buf[1] == 'C')
3575     {
3576       const char *obuf;
3577       ptid_t result;
3578
3579       result = read_ptid (&rs->buf[2], &obuf);
3580       if (*obuf != '\0' && remote_debug)
3581         fprintf_unfiltered (gdb_stdlog,
3582                             "warning: garbage in qC reply\n");
3583
3584       return result;
3585     }
3586   else
3587     return oldpid;
3588 }
3589
3590 /* List remote threads using the deprecated qL packet.  */
3591
3592 int
3593 remote_target::remote_get_threads_with_ql (threads_listing_context *context)
3594 {
3595   if (remote_threadlist_iterator (remote_newthread_step, context,
3596                                   CRAZY_MAX_THREADS) >= 0)
3597     return 1;
3598
3599   return 0;
3600 }
3601
3602 #if defined(HAVE_LIBEXPAT)
3603
3604 static void
3605 start_thread (struct gdb_xml_parser *parser,
3606               const struct gdb_xml_element *element,
3607               void *user_data,
3608               std::vector<gdb_xml_value> &attributes)
3609 {
3610   struct threads_listing_context *data
3611     = (struct threads_listing_context *) user_data;
3612   struct gdb_xml_value *attr;
3613
3614   char *id = (char *) xml_find_attribute (attributes, "id")->value.get ();
3615   ptid_t ptid = read_ptid (id, NULL);
3616
3617   data->items.emplace_back (ptid);
3618   thread_item &item = data->items.back ();
3619
3620   attr = xml_find_attribute (attributes, "core");
3621   if (attr != NULL)
3622     item.core = *(ULONGEST *) attr->value.get ();
3623
3624   attr = xml_find_attribute (attributes, "name");
3625   if (attr != NULL)
3626     item.name = (const char *) attr->value.get ();
3627
3628   attr = xml_find_attribute (attributes, "handle");
3629   if (attr != NULL)
3630     item.thread_handle = hex2bin ((const char *) attr->value.get ());
3631 }
3632
3633 static void
3634 end_thread (struct gdb_xml_parser *parser,
3635             const struct gdb_xml_element *element,
3636             void *user_data, const char *body_text)
3637 {
3638   struct threads_listing_context *data
3639     = (struct threads_listing_context *) user_data;
3640
3641   if (body_text != NULL && *body_text != '\0')
3642     data->items.back ().extra = body_text;
3643 }
3644
3645 const struct gdb_xml_attribute thread_attributes[] = {
3646   { "id", GDB_XML_AF_NONE, NULL, NULL },
3647   { "core", GDB_XML_AF_OPTIONAL, gdb_xml_parse_attr_ulongest, NULL },
3648   { "name", GDB_XML_AF_OPTIONAL, NULL, NULL },
3649   { "handle", GDB_XML_AF_OPTIONAL, NULL, NULL },
3650   { NULL, GDB_XML_AF_NONE, NULL, NULL }
3651 };
3652
3653 const struct gdb_xml_element thread_children[] = {
3654   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3655 };
3656
3657 const struct gdb_xml_element threads_children[] = {
3658   { "thread", thread_attributes, thread_children,
3659     GDB_XML_EF_REPEATABLE | GDB_XML_EF_OPTIONAL,
3660     start_thread, end_thread },
3661   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3662 };
3663
3664 const struct gdb_xml_element threads_elements[] = {
3665   { "threads", NULL, threads_children,
3666     GDB_XML_EF_NONE, NULL, NULL },
3667   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
3668 };
3669
3670 #endif
3671
3672 /* List remote threads using qXfer:threads:read.  */
3673
3674 int
3675 remote_target::remote_get_threads_with_qxfer (threads_listing_context *context)
3676 {
3677 #if defined(HAVE_LIBEXPAT)
3678   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3679     {
3680       gdb::optional<gdb::char_vector> xml
3681         = target_read_stralloc (this, TARGET_OBJECT_THREADS, NULL);
3682
3683       if (xml && (*xml)[0] != '\0')
3684         {
3685           gdb_xml_parse_quick (_("threads"), "threads.dtd",
3686                                threads_elements, xml->data (), context);
3687         }
3688
3689       return 1;
3690     }
3691 #endif
3692
3693   return 0;
3694 }
3695
3696 /* List remote threads using qfThreadInfo/qsThreadInfo.  */
3697
3698 int
3699 remote_target::remote_get_threads_with_qthreadinfo (threads_listing_context *context)
3700 {
3701   struct remote_state *rs = get_remote_state ();
3702
3703   if (rs->use_threadinfo_query)
3704     {
3705       const char *bufp;
3706
3707       putpkt ("qfThreadInfo");
3708       getpkt (&rs->buf, &rs->buf_size, 0);
3709       bufp = rs->buf;
3710       if (bufp[0] != '\0')              /* q packet recognized */
3711         {
3712           while (*bufp++ == 'm')        /* reply contains one or more TID */
3713             {
3714               do
3715                 {
3716                   ptid_t ptid = read_ptid (bufp, &bufp);
3717                   context->items.emplace_back (ptid);
3718                 }
3719               while (*bufp++ == ',');   /* comma-separated list */
3720               putpkt ("qsThreadInfo");
3721               getpkt (&rs->buf, &rs->buf_size, 0);
3722               bufp = rs->buf;
3723             }
3724           return 1;
3725         }
3726       else
3727         {
3728           /* Packet not recognized.  */
3729           rs->use_threadinfo_query = 0;
3730         }
3731     }
3732
3733   return 0;
3734 }
3735
3736 /* Implement the to_update_thread_list function for the remote
3737    targets.  */
3738
3739 void
3740 remote_target::update_thread_list ()
3741 {
3742   struct threads_listing_context context;
3743   int got_list = 0;
3744
3745   /* We have a few different mechanisms to fetch the thread list.  Try
3746      them all, starting with the most preferred one first, falling
3747      back to older methods.  */
3748   if (remote_get_threads_with_qxfer (&context)
3749       || remote_get_threads_with_qthreadinfo (&context)
3750       || remote_get_threads_with_ql (&context))
3751     {
3752       struct thread_info *tp, *tmp;
3753
3754       got_list = 1;
3755
3756       if (context.items.empty ()
3757           && remote_thread_always_alive (inferior_ptid))
3758         {
3759           /* Some targets don't really support threads, but still
3760              reply an (empty) thread list in response to the thread
3761              listing packets, instead of replying "packet not
3762              supported".  Exit early so we don't delete the main
3763              thread.  */
3764           return;
3765         }
3766
3767       /* CONTEXT now holds the current thread list on the remote
3768          target end.  Delete GDB-side threads no longer found on the
3769          target.  */
3770       ALL_THREADS_SAFE (tp, tmp)
3771         {
3772           if (!context.contains_thread (tp->ptid))
3773             {
3774               /* Not found.  */
3775               delete_thread (tp->ptid);
3776             }
3777         }
3778
3779       /* Remove any unreported fork child threads from CONTEXT so
3780          that we don't interfere with follow fork, which is where
3781          creation of such threads is handled.  */
3782       remove_new_fork_children (&context);
3783
3784       /* And now add threads we don't know about yet to our list.  */
3785       for (thread_item &item : context.items)
3786         {
3787           if (item.ptid != null_ptid)
3788             {
3789               /* In non-stop mode, we assume new found threads are
3790                  executing until proven otherwise with a stop reply.
3791                  In all-stop, we can only get here if all threads are
3792                  stopped.  */
3793               int executing = target_is_non_stop_p () ? 1 : 0;
3794
3795               remote_notice_new_inferior (item.ptid, executing);
3796
3797               remote_thread_info *info = get_remote_thread_info (item.ptid);
3798               info->core = item.core;
3799               info->extra = std::move (item.extra);
3800               info->name = std::move (item.name);
3801               info->thread_handle = std::move (item.thread_handle);
3802             }
3803         }
3804     }
3805
3806   if (!got_list)
3807     {
3808       /* If no thread listing method is supported, then query whether
3809          each known thread is alive, one by one, with the T packet.
3810          If the target doesn't support threads at all, then this is a
3811          no-op.  See remote_thread_alive.  */
3812       prune_threads ();
3813     }
3814 }
3815
3816 /*
3817  * Collect a descriptive string about the given thread.
3818  * The target may say anything it wants to about the thread
3819  * (typically info about its blocked / runnable state, name, etc.).
3820  * This string will appear in the info threads display.
3821  *
3822  * Optional: targets are not required to implement this function.
3823  */
3824
3825 const char *
3826 remote_target::extra_thread_info (thread_info *tp)
3827 {
3828   struct remote_state *rs = get_remote_state ();
3829   int result;
3830   int set;
3831   threadref id;
3832   struct gdb_ext_thread_info threadinfo;
3833   static char display_buf[100]; /* arbitrary...  */
3834   int n = 0;                    /* position in display_buf */
3835
3836   if (rs->remote_desc == 0)             /* paranoia */
3837     internal_error (__FILE__, __LINE__,
3838                     _("remote_threads_extra_info"));
3839
3840   if (ptid_equal (tp->ptid, magic_null_ptid)
3841       || (ptid_get_pid (tp->ptid) != 0 && ptid_get_lwp (tp->ptid) == 0))
3842     /* This is the main thread which was added by GDB.  The remote
3843        server doesn't know about it.  */
3844     return NULL;
3845
3846   if (packet_support (PACKET_qXfer_threads) == PACKET_ENABLE)
3847     {
3848       struct thread_info *info = find_thread_ptid (tp->ptid);
3849
3850       if (info != NULL && info->priv != NULL)
3851         {
3852           const std::string &extra = get_remote_thread_info (info)->extra;
3853           return !extra.empty () ? extra.c_str () : NULL;
3854         }
3855       else
3856         return NULL;
3857     }
3858
3859   if (rs->use_threadextra_query)
3860     {
3861       char *b = rs->buf;
3862       char *endb = rs->buf + get_remote_packet_size ();
3863
3864       xsnprintf (b, endb - b, "qThreadExtraInfo,");
3865       b += strlen (b);
3866       write_ptid (b, endb, tp->ptid);
3867
3868       putpkt (rs->buf);
3869       getpkt (&rs->buf, &rs->buf_size, 0);
3870       if (rs->buf[0] != 0)
3871         {
3872           n = std::min (strlen (rs->buf) / 2, sizeof (display_buf));
3873           result = hex2bin (rs->buf, (gdb_byte *) display_buf, n);
3874           display_buf [result] = '\0';
3875           return display_buf;
3876         }
3877     }
3878
3879   /* If the above query fails, fall back to the old method.  */
3880   rs->use_threadextra_query = 0;
3881   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
3882     | TAG_MOREDISPLAY | TAG_DISPLAY;
3883   int_to_threadref (&id, ptid_get_lwp (tp->ptid));
3884   if (remote_get_threadinfo (&id, set, &threadinfo))
3885     if (threadinfo.active)
3886       {
3887         if (*threadinfo.shortname)
3888           n += xsnprintf (&display_buf[0], sizeof (display_buf) - n,
3889                           " Name: %s,", threadinfo.shortname);
3890         if (*threadinfo.display)
3891           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3892                           " State: %s,", threadinfo.display);
3893         if (*threadinfo.more_display)
3894           n += xsnprintf (&display_buf[n], sizeof (display_buf) - n,
3895                           " Priority: %s", threadinfo.more_display);
3896
3897         if (n > 0)
3898           {
3899             /* For purely cosmetic reasons, clear up trailing commas.  */
3900             if (',' == display_buf[n-1])
3901               display_buf[n-1] = ' ';
3902             return display_buf;
3903           }
3904       }
3905   return NULL;
3906 }
3907 \f
3908
3909 bool
3910 remote_target::static_tracepoint_marker_at (CORE_ADDR addr,
3911                                             struct static_tracepoint_marker *marker)
3912 {
3913   struct remote_state *rs = get_remote_state ();
3914   char *p = rs->buf;
3915
3916   xsnprintf (p, get_remote_packet_size (), "qTSTMat:");
3917   p += strlen (p);
3918   p += hexnumstr (p, addr);
3919   putpkt (rs->buf);
3920   getpkt (&rs->buf, &rs->buf_size, 0);
3921   p = rs->buf;
3922
3923   if (*p == 'E')
3924     error (_("Remote failure reply: %s"), p);
3925
3926   if (*p++ == 'm')
3927     {
3928       parse_static_tracepoint_marker_definition (p, NULL, marker);
3929       return true;
3930     }
3931
3932   return false;
3933 }
3934
3935 std::vector<static_tracepoint_marker>
3936 remote_target::static_tracepoint_markers_by_strid (const char *strid)
3937 {
3938   struct remote_state *rs = get_remote_state ();
3939   std::vector<static_tracepoint_marker> markers;
3940   const char *p;
3941   static_tracepoint_marker marker;
3942
3943   /* Ask for a first packet of static tracepoint marker
3944      definition.  */
3945   putpkt ("qTfSTM");
3946   getpkt (&rs->buf, &rs->buf_size, 0);
3947   p = rs->buf;
3948   if (*p == 'E')
3949     error (_("Remote failure reply: %s"), p);
3950
3951   while (*p++ == 'm')
3952     {
3953       do
3954         {
3955           parse_static_tracepoint_marker_definition (p, &p, &marker);
3956
3957           if (strid == NULL || marker.str_id == strid)
3958             markers.push_back (std::move (marker));
3959         }
3960       while (*p++ == ',');      /* comma-separated list */
3961       /* Ask for another packet of static tracepoint definition.  */
3962       putpkt ("qTsSTM");
3963       getpkt (&rs->buf, &rs->buf_size, 0);
3964       p = rs->buf;
3965     }
3966
3967   return markers;
3968 }
3969
3970 \f
3971 /* Implement the to_get_ada_task_ptid function for the remote targets.  */
3972
3973 ptid_t
3974 remote_target::get_ada_task_ptid (long lwp, long thread)
3975 {
3976   return ptid_build (ptid_get_pid (inferior_ptid), lwp, 0);
3977 }
3978 \f
3979
3980 /* Restart the remote side; this is an extended protocol operation.  */
3981
3982 void
3983 remote_target::extended_remote_restart ()
3984 {
3985   struct remote_state *rs = get_remote_state ();
3986
3987   /* Send the restart command; for reasons I don't understand the
3988      remote side really expects a number after the "R".  */
3989   xsnprintf (rs->buf, get_remote_packet_size (), "R%x", 0);
3990   putpkt (rs->buf);
3991
3992   remote_fileio_reset ();
3993 }
3994 \f
3995 /* Clean up connection to a remote debugger.  */
3996
3997 void
3998 remote_target::close ()
3999 {
4000   /* Make sure we leave stdin registered in the event loop.  */
4001   terminal_ours ();
4002
4003   /* We don't have a connection to the remote stub anymore.  Get rid
4004      of all the inferiors and their threads we were controlling.
4005      Reset inferior_ptid to null_ptid first, as otherwise has_stack_frame
4006      will be unable to find the thread corresponding to (pid, 0, 0).  */
4007   inferior_ptid = null_ptid;
4008   discard_all_inferiors ();
4009
4010   trace_reset_local_state ();
4011
4012   delete this;
4013 }
4014
4015 remote_target::~remote_target ()
4016 {
4017   struct remote_state *rs = get_remote_state ();
4018
4019   /* Check for NULL because we may get here with a partially
4020      constructed target/connection.  */
4021   if (rs->remote_desc == nullptr)
4022     return;
4023
4024   serial_close (rs->remote_desc);
4025
4026   /* We are destroying the remote target, so we should discard
4027      everything of this target.  */
4028   discard_pending_stop_replies_in_queue ();
4029
4030   if (rs->remote_async_inferior_event_token)
4031     delete_async_event_handler (&rs->remote_async_inferior_event_token);
4032
4033   remote_notif_state_xfree (rs->notif_state);
4034 }
4035
4036 /* Query the remote side for the text, data and bss offsets.  */
4037
4038 void
4039 remote_target::get_offsets ()
4040 {
4041   struct remote_state *rs = get_remote_state ();
4042   char *buf;
4043   char *ptr;
4044   int lose, num_segments = 0, do_sections, do_segments;
4045   CORE_ADDR text_addr, data_addr, bss_addr, segments[2];
4046   struct section_offsets *offs;
4047   struct symfile_segment_data *data;
4048
4049   if (symfile_objfile == NULL)
4050     return;
4051
4052   putpkt ("qOffsets");
4053   getpkt (&rs->buf, &rs->buf_size, 0);
4054   buf = rs->buf;
4055
4056   if (buf[0] == '\000')
4057     return;                     /* Return silently.  Stub doesn't support
4058                                    this command.  */
4059   if (buf[0] == 'E')
4060     {
4061       warning (_("Remote failure reply: %s"), buf);
4062       return;
4063     }
4064
4065   /* Pick up each field in turn.  This used to be done with scanf, but
4066      scanf will make trouble if CORE_ADDR size doesn't match
4067      conversion directives correctly.  The following code will work
4068      with any size of CORE_ADDR.  */
4069   text_addr = data_addr = bss_addr = 0;
4070   ptr = buf;
4071   lose = 0;
4072
4073   if (startswith (ptr, "Text="))
4074     {
4075       ptr += 5;
4076       /* Don't use strtol, could lose on big values.  */
4077       while (*ptr && *ptr != ';')
4078         text_addr = (text_addr << 4) + fromhex (*ptr++);
4079
4080       if (startswith (ptr, ";Data="))
4081         {
4082           ptr += 6;
4083           while (*ptr && *ptr != ';')
4084             data_addr = (data_addr << 4) + fromhex (*ptr++);
4085         }
4086       else
4087         lose = 1;
4088
4089       if (!lose && startswith (ptr, ";Bss="))
4090         {
4091           ptr += 5;
4092           while (*ptr && *ptr != ';')
4093             bss_addr = (bss_addr << 4) + fromhex (*ptr++);
4094
4095           if (bss_addr != data_addr)
4096             warning (_("Target reported unsupported offsets: %s"), buf);
4097         }
4098       else
4099         lose = 1;
4100     }
4101   else if (startswith (ptr, "TextSeg="))
4102     {
4103       ptr += 8;
4104       /* Don't use strtol, could lose on big values.  */
4105       while (*ptr && *ptr != ';')
4106         text_addr = (text_addr << 4) + fromhex (*ptr++);
4107       num_segments = 1;
4108
4109       if (startswith (ptr, ";DataSeg="))
4110         {
4111           ptr += 9;
4112           while (*ptr && *ptr != ';')
4113             data_addr = (data_addr << 4) + fromhex (*ptr++);
4114           num_segments++;
4115         }
4116     }
4117   else
4118     lose = 1;
4119
4120   if (lose)
4121     error (_("Malformed response to offset query, %s"), buf);
4122   else if (*ptr != '\0')
4123     warning (_("Target reported unsupported offsets: %s"), buf);
4124
4125   offs = ((struct section_offsets *)
4126           alloca (SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections)));
4127   memcpy (offs, symfile_objfile->section_offsets,
4128           SIZEOF_N_SECTION_OFFSETS (symfile_objfile->num_sections));
4129
4130   data = get_symfile_segment_data (symfile_objfile->obfd);
4131   do_segments = (data != NULL);
4132   do_sections = num_segments == 0;
4133
4134   if (num_segments > 0)
4135     {
4136       segments[0] = text_addr;
4137       segments[1] = data_addr;
4138     }
4139   /* If we have two segments, we can still try to relocate everything
4140      by assuming that the .text and .data offsets apply to the whole
4141      text and data segments.  Convert the offsets given in the packet
4142      to base addresses for symfile_map_offsets_to_segments.  */
4143   else if (data && data->num_segments == 2)
4144     {
4145       segments[0] = data->segment_bases[0] + text_addr;
4146       segments[1] = data->segment_bases[1] + data_addr;
4147       num_segments = 2;
4148     }
4149   /* If the object file has only one segment, assume that it is text
4150      rather than data; main programs with no writable data are rare,
4151      but programs with no code are useless.  Of course the code might
4152      have ended up in the data segment... to detect that we would need
4153      the permissions here.  */
4154   else if (data && data->num_segments == 1)
4155     {
4156       segments[0] = data->segment_bases[0] + text_addr;
4157       num_segments = 1;
4158     }
4159   /* There's no way to relocate by segment.  */
4160   else
4161     do_segments = 0;
4162
4163   if (do_segments)
4164     {
4165       int ret = symfile_map_offsets_to_segments (symfile_objfile->obfd, data,
4166                                                  offs, num_segments, segments);
4167
4168       if (ret == 0 && !do_sections)
4169         error (_("Can not handle qOffsets TextSeg "
4170                  "response with this symbol file"));
4171
4172       if (ret > 0)
4173         do_sections = 0;
4174     }
4175
4176   if (data)
4177     free_symfile_segment_data (data);
4178
4179   if (do_sections)
4180     {
4181       offs->offsets[SECT_OFF_TEXT (symfile_objfile)] = text_addr;
4182
4183       /* This is a temporary kludge to force data and bss to use the
4184          same offsets because that's what nlmconv does now.  The real
4185          solution requires changes to the stub and remote.c that I
4186          don't have time to do right now.  */
4187
4188       offs->offsets[SECT_OFF_DATA (symfile_objfile)] = data_addr;
4189       offs->offsets[SECT_OFF_BSS (symfile_objfile)] = data_addr;
4190     }
4191
4192   objfile_relocate (symfile_objfile, offs);
4193 }
4194
4195 /* Send interrupt_sequence to remote target.  */
4196
4197 void
4198 remote_target::send_interrupt_sequence ()
4199 {
4200   struct remote_state *rs = get_remote_state ();
4201
4202   if (interrupt_sequence_mode == interrupt_sequence_control_c)
4203     remote_serial_write ("\x03", 1);
4204   else if (interrupt_sequence_mode == interrupt_sequence_break)
4205     serial_send_break (rs->remote_desc);
4206   else if (interrupt_sequence_mode == interrupt_sequence_break_g)
4207     {
4208       serial_send_break (rs->remote_desc);
4209       remote_serial_write ("g", 1);
4210     }
4211   else
4212     internal_error (__FILE__, __LINE__,
4213                     _("Invalid value for interrupt_sequence_mode: %s."),
4214                     interrupt_sequence_mode);
4215 }
4216
4217
4218 /* If STOP_REPLY is a T stop reply, look for the "thread" register,
4219    and extract the PTID.  Returns NULL_PTID if not found.  */
4220
4221 static ptid_t
4222 stop_reply_extract_thread (char *stop_reply)
4223 {
4224   if (stop_reply[0] == 'T' && strlen (stop_reply) > 3)
4225     {
4226       const char *p;
4227
4228       /* Txx r:val ; r:val (...)  */
4229       p = &stop_reply[3];
4230
4231       /* Look for "register" named "thread".  */
4232       while (*p != '\0')
4233         {
4234           const char *p1;
4235
4236           p1 = strchr (p, ':');
4237           if (p1 == NULL)
4238             return null_ptid;
4239
4240           if (strncmp (p, "thread", p1 - p) == 0)
4241             return read_ptid (++p1, &p);
4242
4243           p1 = strchr (p, ';');
4244           if (p1 == NULL)
4245             return null_ptid;
4246           p1++;
4247
4248           p = p1;
4249         }
4250     }
4251
4252   return null_ptid;
4253 }
4254
4255 /* Determine the remote side's current thread.  If we have a stop
4256    reply handy (in WAIT_STATUS), maybe it's a T stop reply with a
4257    "thread" register we can extract the current thread from.  If not,
4258    ask the remote which is the current thread with qC.  The former
4259    method avoids a roundtrip.  */
4260
4261 ptid_t
4262 remote_target::get_current_thread (char *wait_status)
4263 {
4264   ptid_t ptid = null_ptid;
4265
4266   /* Note we don't use remote_parse_stop_reply as that makes use of
4267      the target architecture, which we haven't yet fully determined at
4268      this point.  */
4269   if (wait_status != NULL)
4270     ptid = stop_reply_extract_thread (wait_status);
4271   if (ptid_equal (ptid, null_ptid))
4272     ptid = remote_current_thread (inferior_ptid);
4273
4274   return ptid;
4275 }
4276
4277 /* Query the remote target for which is the current thread/process,
4278    add it to our tables, and update INFERIOR_PTID.  The caller is
4279    responsible for setting the state such that the remote end is ready
4280    to return the current thread.
4281
4282    This function is called after handling the '?' or 'vRun' packets,
4283    whose response is a stop reply from which we can also try
4284    extracting the thread.  If the target doesn't support the explicit
4285    qC query, we infer the current thread from that stop reply, passed
4286    in in WAIT_STATUS, which may be NULL.  */
4287
4288 void
4289 remote_target::add_current_inferior_and_thread (char *wait_status)
4290 {
4291   struct remote_state *rs = get_remote_state ();
4292   int fake_pid_p = 0;
4293
4294   inferior_ptid = null_ptid;
4295
4296   /* Now, if we have thread information, update inferior_ptid.  */
4297   ptid_t curr_ptid = get_current_thread (wait_status);
4298
4299   if (curr_ptid != null_ptid)
4300     {
4301       if (!remote_multi_process_p (rs))
4302         fake_pid_p = 1;
4303     }
4304   else
4305     {
4306       /* Without this, some commands which require an active target
4307          (such as kill) won't work.  This variable serves (at least)
4308          double duty as both the pid of the target process (if it has
4309          such), and as a flag indicating that a target is active.  */
4310       curr_ptid = magic_null_ptid;
4311       fake_pid_p = 1;
4312     }
4313
4314   remote_add_inferior (fake_pid_p, ptid_get_pid (curr_ptid), -1, 1);
4315
4316   /* Add the main thread and switch to it.  Don't try reading
4317      registers yet, since we haven't fetched the target description
4318      yet.  */
4319   thread_info *tp = add_thread_silent (curr_ptid);
4320   switch_to_thread_no_regs (tp);
4321 }
4322
4323 /* Print info about a thread that was found already stopped on
4324    connection.  */
4325
4326 static void
4327 print_one_stopped_thread (struct thread_info *thread)
4328 {
4329   struct target_waitstatus *ws = &thread->suspend.waitstatus;
4330
4331   switch_to_thread (thread->ptid);
4332   stop_pc = get_frame_pc (get_current_frame ());
4333   set_current_sal_from_frame (get_current_frame ());
4334
4335   thread->suspend.waitstatus_pending_p = 0;
4336
4337   if (ws->kind == TARGET_WAITKIND_STOPPED)
4338     {
4339       enum gdb_signal sig = ws->value.sig;
4340
4341       if (signal_print_state (sig))
4342         gdb::observers::signal_received.notify (sig);
4343     }
4344   gdb::observers::normal_stop.notify (NULL, 1);
4345 }
4346
4347 /* Process all initial stop replies the remote side sent in response
4348    to the ? packet.  These indicate threads that were already stopped
4349    on initial connection.  We mark these threads as stopped and print
4350    their current frame before giving the user the prompt.  */
4351
4352 void
4353 remote_target::process_initial_stop_replies (int from_tty)
4354 {
4355   int pending_stop_replies = stop_reply_queue_length ();
4356   struct inferior *inf;
4357   struct thread_info *thread;
4358   struct thread_info *selected = NULL;
4359   struct thread_info *lowest_stopped = NULL;
4360   struct thread_info *first = NULL;
4361
4362   /* Consume the initial pending events.  */
4363   while (pending_stop_replies-- > 0)
4364     {
4365       ptid_t waiton_ptid = minus_one_ptid;
4366       ptid_t event_ptid;
4367       struct target_waitstatus ws;
4368       int ignore_event = 0;
4369       struct thread_info *thread;
4370
4371       memset (&ws, 0, sizeof (ws));
4372       event_ptid = target_wait (waiton_ptid, &ws, TARGET_WNOHANG);
4373       if (remote_debug)
4374         print_target_wait_results (waiton_ptid, event_ptid, &ws);
4375
4376       switch (ws.kind)
4377         {
4378         case TARGET_WAITKIND_IGNORE:
4379         case TARGET_WAITKIND_NO_RESUMED:
4380         case TARGET_WAITKIND_SIGNALLED:
4381         case TARGET_WAITKIND_EXITED:
4382           /* We shouldn't see these, but if we do, just ignore.  */
4383           if (remote_debug)
4384             fprintf_unfiltered (gdb_stdlog, "remote: event ignored\n");
4385           ignore_event = 1;
4386           break;
4387
4388         case TARGET_WAITKIND_EXECD:
4389           xfree (ws.value.execd_pathname);
4390           break;
4391         default:
4392           break;
4393         }
4394
4395       if (ignore_event)
4396         continue;
4397
4398       thread = find_thread_ptid (event_ptid);
4399
4400       if (ws.kind == TARGET_WAITKIND_STOPPED)
4401         {
4402           enum gdb_signal sig = ws.value.sig;
4403
4404           /* Stubs traditionally report SIGTRAP as initial signal,
4405              instead of signal 0.  Suppress it.  */
4406           if (sig == GDB_SIGNAL_TRAP)
4407             sig = GDB_SIGNAL_0;
4408           thread->suspend.stop_signal = sig;
4409           ws.value.sig = sig;
4410         }
4411
4412       thread->suspend.waitstatus = ws;
4413
4414       if (ws.kind != TARGET_WAITKIND_STOPPED
4415           || ws.value.sig != GDB_SIGNAL_0)
4416         thread->suspend.waitstatus_pending_p = 1;
4417
4418       set_executing (event_ptid, 0);
4419       set_running (event_ptid, 0);
4420       get_remote_thread_info (thread)->vcont_resumed = 0;
4421     }
4422
4423   /* "Notice" the new inferiors before anything related to
4424      registers/memory.  */
4425   ALL_INFERIORS (inf)
4426     {
4427       if (inf->pid == 0)
4428         continue;
4429
4430       inf->needs_setup = 1;
4431
4432       if (non_stop)
4433         {
4434           thread = any_live_thread_of_process (inf->pid);
4435           notice_new_inferior (thread->ptid,
4436                                thread->state == THREAD_RUNNING,
4437                                from_tty);
4438         }
4439     }
4440
4441   /* If all-stop on top of non-stop, pause all threads.  Note this
4442      records the threads' stop pc, so must be done after "noticing"
4443      the inferiors.  */
4444   if (!non_stop)
4445     {
4446       stop_all_threads ();
4447
4448       /* If all threads of an inferior were already stopped, we
4449          haven't setup the inferior yet.  */
4450       ALL_INFERIORS (inf)
4451         {
4452           if (inf->pid == 0)
4453             continue;
4454
4455           if (inf->needs_setup)
4456             {
4457               thread = any_live_thread_of_process (inf->pid);
4458               switch_to_thread_no_regs (thread);
4459               setup_inferior (0);
4460             }
4461         }
4462     }
4463
4464   /* Now go over all threads that are stopped, and print their current
4465      frame.  If all-stop, then if there's a signalled thread, pick
4466      that as current.  */
4467   ALL_NON_EXITED_THREADS (thread)
4468     {
4469       if (first == NULL)
4470         first = thread;
4471
4472       if (!non_stop)
4473         set_running (thread->ptid, 0);
4474       else if (thread->state != THREAD_STOPPED)
4475         continue;
4476
4477       if (selected == NULL
4478           && thread->suspend.waitstatus_pending_p)
4479         selected = thread;
4480
4481       if (lowest_stopped == NULL
4482           || thread->inf->num < lowest_stopped->inf->num
4483           || thread->per_inf_num < lowest_stopped->per_inf_num)
4484         lowest_stopped = thread;
4485
4486       if (non_stop)
4487         print_one_stopped_thread (thread);
4488     }
4489
4490   /* In all-stop, we only print the status of one thread, and leave
4491      others with their status pending.  */
4492   if (!non_stop)
4493     {
4494       thread = selected;
4495       if (thread == NULL)
4496         thread = lowest_stopped;
4497       if (thread == NULL)
4498         thread = first;
4499
4500       print_one_stopped_thread (thread);
4501     }
4502
4503   /* For "info program".  */
4504   thread = inferior_thread ();
4505   if (thread->state == THREAD_STOPPED)
4506     set_last_target_status (inferior_ptid, thread->suspend.waitstatus);
4507 }
4508
4509 /* Start the remote connection and sync state.  */
4510
4511 void
4512 remote_target::start_remote (int from_tty, int extended_p)
4513 {
4514   struct remote_state *rs = get_remote_state ();
4515   struct packet_config *noack_config;
4516   char *wait_status = NULL;
4517
4518   /* Signal other parts that we're going through the initial setup,
4519      and so things may not be stable yet.  E.g., we don't try to
4520      install tracepoints until we've relocated symbols.  Also, a
4521      Ctrl-C before we're connected and synced up can't interrupt the
4522      target.  Instead, it offers to drop the (potentially wedged)
4523      connection.  */
4524   rs->starting_up = 1;
4525
4526   QUIT;
4527
4528   if (interrupt_on_connect)
4529     send_interrupt_sequence ();
4530
4531   /* Ack any packet which the remote side has already sent.  */
4532   remote_serial_write ("+", 1);
4533
4534   /* The first packet we send to the target is the optional "supported
4535      packets" request.  If the target can answer this, it will tell us
4536      which later probes to skip.  */
4537   remote_query_supported ();
4538
4539   /* If the stub wants to get a QAllow, compose one and send it.  */
4540   if (packet_support (PACKET_QAllow) != PACKET_DISABLE)
4541     set_permissions ();
4542
4543   /* gdbserver < 7.7 (before its fix from 2013-12-11) did reply to any
4544      unknown 'v' packet with string "OK".  "OK" gets interpreted by GDB
4545      as a reply to known packet.  For packet "vFile:setfs:" it is an
4546      invalid reply and GDB would return error in
4547      remote_hostio_set_filesystem, making remote files access impossible.
4548      Disable "vFile:setfs:" in such case.  Do not disable other 'v' packets as
4549      other "vFile" packets get correctly detected even on gdbserver < 7.7.  */
4550   {
4551     const char v_mustreplyempty[] = "vMustReplyEmpty";
4552
4553     putpkt (v_mustreplyempty);
4554     getpkt (&rs->buf, &rs->buf_size, 0);
4555     if (strcmp (rs->buf, "OK") == 0)
4556       remote_protocol_packets[PACKET_vFile_setfs].support = PACKET_DISABLE;
4557     else if (strcmp (rs->buf, "") != 0)
4558       error (_("Remote replied unexpectedly to '%s': %s"), v_mustreplyempty,
4559              rs->buf);
4560   }
4561
4562   /* Next, we possibly activate noack mode.
4563
4564      If the QStartNoAckMode packet configuration is set to AUTO,
4565      enable noack mode if the stub reported a wish for it with
4566      qSupported.
4567
4568      If set to TRUE, then enable noack mode even if the stub didn't
4569      report it in qSupported.  If the stub doesn't reply OK, the
4570      session ends with an error.
4571
4572      If FALSE, then don't activate noack mode, regardless of what the
4573      stub claimed should be the default with qSupported.  */
4574
4575   noack_config = &remote_protocol_packets[PACKET_QStartNoAckMode];
4576   if (packet_config_support (noack_config) != PACKET_DISABLE)
4577     {
4578       putpkt ("QStartNoAckMode");
4579       getpkt (&rs->buf, &rs->buf_size, 0);
4580       if (packet_ok (rs->buf, noack_config) == PACKET_OK)
4581         rs->noack_mode = 1;
4582     }
4583
4584   if (extended_p)
4585     {
4586       /* Tell the remote that we are using the extended protocol.  */
4587       putpkt ("!");
4588       getpkt (&rs->buf, &rs->buf_size, 0);
4589     }
4590
4591   /* Let the target know which signals it is allowed to pass down to
4592      the program.  */
4593   update_signals_program_target ();
4594
4595   /* Next, if the target can specify a description, read it.  We do
4596      this before anything involving memory or registers.  */
4597   target_find_description ();
4598
4599   /* Next, now that we know something about the target, update the
4600      address spaces in the program spaces.  */
4601   update_address_spaces ();
4602
4603   /* On OSs where the list of libraries is global to all
4604      processes, we fetch them early.  */
4605   if (gdbarch_has_global_solist (target_gdbarch ()))
4606     solib_add (NULL, from_tty, auto_solib_add);
4607
4608   if (target_is_non_stop_p ())
4609     {
4610       if (packet_support (PACKET_QNonStop) != PACKET_ENABLE)
4611         error (_("Non-stop mode requested, but remote "
4612                  "does not support non-stop"));
4613
4614       putpkt ("QNonStop:1");
4615       getpkt (&rs->buf, &rs->buf_size, 0);
4616
4617       if (strcmp (rs->buf, "OK") != 0)
4618         error (_("Remote refused setting non-stop mode with: %s"), rs->buf);
4619
4620       /* Find about threads and processes the stub is already
4621          controlling.  We default to adding them in the running state.
4622          The '?' query below will then tell us about which threads are
4623          stopped.  */
4624       this->update_thread_list ();
4625     }
4626   else if (packet_support (PACKET_QNonStop) == PACKET_ENABLE)
4627     {
4628       /* Don't assume that the stub can operate in all-stop mode.
4629          Request it explicitly.  */
4630       putpkt ("QNonStop:0");
4631       getpkt (&rs->buf, &rs->buf_size, 0);
4632
4633       if (strcmp (rs->buf, "OK") != 0)
4634         error (_("Remote refused setting all-stop mode with: %s"), rs->buf);
4635     }
4636
4637   /* Upload TSVs regardless of whether the target is running or not.  The
4638      remote stub, such as GDBserver, may have some predefined or builtin
4639      TSVs, even if the target is not running.  */
4640   if (get_trace_status (current_trace_status ()) != -1)
4641     {
4642       struct uploaded_tsv *uploaded_tsvs = NULL;
4643
4644       upload_trace_state_variables (&uploaded_tsvs);
4645       merge_uploaded_trace_state_variables (&uploaded_tsvs);
4646     }
4647
4648   /* Check whether the target is running now.  */
4649   putpkt ("?");
4650   getpkt (&rs->buf, &rs->buf_size, 0);
4651
4652   if (!target_is_non_stop_p ())
4653     {
4654       if (rs->buf[0] == 'W' || rs->buf[0] == 'X')
4655         {
4656           if (!extended_p)
4657             error (_("The target is not running (try extended-remote?)"));
4658
4659           /* We're connected, but not running.  Drop out before we
4660              call start_remote.  */
4661           rs->starting_up = 0;
4662           return;
4663         }
4664       else
4665         {
4666           /* Save the reply for later.  */
4667           wait_status = (char *) alloca (strlen (rs->buf) + 1);
4668           strcpy (wait_status, rs->buf);
4669         }
4670
4671       /* Fetch thread list.  */
4672       target_update_thread_list ();
4673
4674       /* Let the stub know that we want it to return the thread.  */
4675       set_continue_thread (minus_one_ptid);
4676
4677       if (thread_count () == 0)
4678         {
4679           /* Target has no concept of threads at all.  GDB treats
4680              non-threaded target as single-threaded; add a main
4681              thread.  */
4682           add_current_inferior_and_thread (wait_status);
4683         }
4684       else
4685         {
4686           /* We have thread information; select the thread the target
4687              says should be current.  If we're reconnecting to a
4688              multi-threaded program, this will ideally be the thread
4689              that last reported an event before GDB disconnected.  */
4690           inferior_ptid = get_current_thread (wait_status);
4691           if (ptid_equal (inferior_ptid, null_ptid))
4692             {
4693               /* Odd... The target was able to list threads, but not
4694                  tell us which thread was current (no "thread"
4695                  register in T stop reply?).  Just pick the first
4696                  thread in the thread list then.  */
4697               
4698               if (remote_debug)
4699                 fprintf_unfiltered (gdb_stdlog,
4700                                     "warning: couldn't determine remote "
4701                                     "current thread; picking first in list.\n");
4702
4703               inferior_ptid = thread_list->ptid;
4704             }
4705         }
4706
4707       /* init_wait_for_inferior should be called before get_offsets in order
4708          to manage `inserted' flag in bp loc in a correct state.
4709          breakpoint_init_inferior, called from init_wait_for_inferior, set
4710          `inserted' flag to 0, while before breakpoint_re_set, called from
4711          start_remote, set `inserted' flag to 1.  In the initialization of
4712          inferior, breakpoint_init_inferior should be called first, and then
4713          breakpoint_re_set can be called.  If this order is broken, state of
4714          `inserted' flag is wrong, and cause some problems on breakpoint
4715          manipulation.  */
4716       init_wait_for_inferior ();
4717
4718       get_offsets ();           /* Get text, data & bss offsets.  */
4719
4720       /* If we could not find a description using qXfer, and we know
4721          how to do it some other way, try again.  This is not
4722          supported for non-stop; it could be, but it is tricky if
4723          there are no stopped threads when we connect.  */
4724       if (remote_read_description_p (this)
4725           && gdbarch_target_desc (target_gdbarch ()) == NULL)
4726         {
4727           target_clear_description ();
4728           target_find_description ();
4729         }
4730
4731       /* Use the previously fetched status.  */
4732       gdb_assert (wait_status != NULL);
4733       strcpy (rs->buf, wait_status);
4734       rs->cached_wait_status = 1;
4735
4736       ::start_remote (from_tty); /* Initialize gdb process mechanisms.  */
4737     }
4738   else
4739     {
4740       /* Clear WFI global state.  Do this before finding about new
4741          threads and inferiors, and setting the current inferior.
4742          Otherwise we would clear the proceed status of the current
4743          inferior when we want its stop_soon state to be preserved
4744          (see notice_new_inferior).  */
4745       init_wait_for_inferior ();
4746
4747       /* In non-stop, we will either get an "OK", meaning that there
4748          are no stopped threads at this time; or, a regular stop
4749          reply.  In the latter case, there may be more than one thread
4750          stopped --- we pull them all out using the vStopped
4751          mechanism.  */
4752       if (strcmp (rs->buf, "OK") != 0)
4753         {
4754           struct notif_client *notif = &notif_client_stop;
4755
4756           /* remote_notif_get_pending_replies acks this one, and gets
4757              the rest out.  */
4758           rs->notif_state->pending_event[notif_client_stop.id]
4759             = remote_notif_parse (this, notif, rs->buf);
4760           remote_notif_get_pending_events (notif);
4761         }
4762
4763       if (thread_count () == 0)
4764         {
4765           if (!extended_p)
4766             error (_("The target is not running (try extended-remote?)"));
4767
4768           /* We're connected, but not running.  Drop out before we
4769              call start_remote.  */
4770           rs->starting_up = 0;
4771           return;
4772         }
4773
4774       /* In non-stop mode, any cached wait status will be stored in
4775          the stop reply queue.  */
4776       gdb_assert (wait_status == NULL);
4777
4778       /* Report all signals during attach/startup.  */
4779       pass_signals (0, NULL);
4780
4781       /* If there are already stopped threads, mark them stopped and
4782          report their stops before giving the prompt to the user.  */
4783       process_initial_stop_replies (from_tty);
4784
4785       if (target_can_async_p ())
4786         target_async (1);
4787     }
4788
4789   /* If we connected to a live target, do some additional setup.  */
4790   if (target_has_execution)
4791     {
4792       if (symfile_objfile)      /* No use without a symbol-file.  */
4793         remote_check_symbols ();
4794     }
4795
4796   /* Possibly the target has been engaged in a trace run started
4797      previously; find out where things are at.  */
4798   if (get_trace_status (current_trace_status ()) != -1)
4799     {
4800       struct uploaded_tp *uploaded_tps = NULL;
4801
4802       if (current_trace_status ()->running)
4803         printf_filtered (_("Trace is already running on the target.\n"));
4804
4805       upload_tracepoints (&uploaded_tps);
4806
4807       merge_uploaded_tracepoints (&uploaded_tps);
4808     }
4809
4810   /* Possibly the target has been engaged in a btrace record started
4811      previously; find out where things are at.  */
4812   remote_btrace_maybe_reopen ();
4813
4814   /* The thread and inferior lists are now synchronized with the
4815      target, our symbols have been relocated, and we're merged the
4816      target's tracepoints with ours.  We're done with basic start
4817      up.  */
4818   rs->starting_up = 0;
4819
4820   /* Maybe breakpoints are global and need to be inserted now.  */
4821   if (breakpoints_should_be_inserted_now ())
4822     insert_breakpoints ();
4823 }
4824
4825 /* Open a connection to a remote debugger.
4826    NAME is the filename used for communication.  */
4827
4828 void
4829 remote_target::open (const char *name, int from_tty)
4830 {
4831   open_1 (name, from_tty, 0);
4832 }
4833
4834 /* Open a connection to a remote debugger using the extended
4835    remote gdb protocol.  NAME is the filename used for communication.  */
4836
4837 void
4838 extended_remote_target::open (const char *name, int from_tty)
4839 {
4840   open_1 (name, from_tty, 1 /*extended_p */);
4841 }
4842
4843 /* Reset all packets back to "unknown support".  Called when opening a
4844    new connection to a remote target.  */
4845
4846 static void
4847 reset_all_packet_configs_support (void)
4848 {
4849   int i;
4850
4851   for (i = 0; i < PACKET_MAX; i++)
4852     remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4853 }
4854
4855 /* Initialize all packet configs.  */
4856
4857 static void
4858 init_all_packet_configs (void)
4859 {
4860   int i;
4861
4862   for (i = 0; i < PACKET_MAX; i++)
4863     {
4864       remote_protocol_packets[i].detect = AUTO_BOOLEAN_AUTO;
4865       remote_protocol_packets[i].support = PACKET_SUPPORT_UNKNOWN;
4866     }
4867 }
4868
4869 /* Symbol look-up.  */
4870
4871 void
4872 remote_target::remote_check_symbols ()
4873 {
4874   char *msg, *reply, *tmp;
4875   int end;
4876   long reply_size;
4877   struct cleanup *old_chain;
4878
4879   /* The remote side has no concept of inferiors that aren't running
4880      yet, it only knows about running processes.  If we're connected
4881      but our current inferior is not running, we should not invite the
4882      remote target to request symbol lookups related to its
4883      (unrelated) current process.  */
4884   if (!target_has_execution)
4885     return;
4886
4887   if (packet_support (PACKET_qSymbol) == PACKET_DISABLE)
4888     return;
4889
4890   /* Make sure the remote is pointing at the right process.  Note
4891      there's no way to select "no process".  */
4892   set_general_process ();
4893
4894   /* Allocate a message buffer.  We can't reuse the input buffer in RS,
4895      because we need both at the same time.  */
4896   msg = (char *) xmalloc (get_remote_packet_size ());
4897   old_chain = make_cleanup (xfree, msg);
4898   reply = (char *) xmalloc (get_remote_packet_size ());
4899   make_cleanup (free_current_contents, &reply);
4900   reply_size = get_remote_packet_size ();
4901
4902   /* Invite target to request symbol lookups.  */
4903
4904   putpkt ("qSymbol::");
4905   getpkt (&reply, &reply_size, 0);
4906   packet_ok (reply, &remote_protocol_packets[PACKET_qSymbol]);
4907
4908   while (startswith (reply, "qSymbol:"))
4909     {
4910       struct bound_minimal_symbol sym;
4911
4912       tmp = &reply[8];
4913       end = hex2bin (tmp, (gdb_byte *) msg, strlen (tmp) / 2);
4914       msg[end] = '\0';
4915       sym = lookup_minimal_symbol (msg, NULL, NULL);
4916       if (sym.minsym == NULL)
4917         xsnprintf (msg, get_remote_packet_size (), "qSymbol::%s", &reply[8]);
4918       else
4919         {
4920           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
4921           CORE_ADDR sym_addr = BMSYMBOL_VALUE_ADDRESS (sym);
4922
4923           /* If this is a function address, return the start of code
4924              instead of any data function descriptor.  */
4925           sym_addr = gdbarch_convert_from_func_ptr_addr (target_gdbarch (),
4926                                                          sym_addr,
4927                                                          current_top_target ());
4928
4929           xsnprintf (msg, get_remote_packet_size (), "qSymbol:%s:%s",
4930                      phex_nz (sym_addr, addr_size), &reply[8]);
4931         }
4932   
4933       putpkt (msg);
4934       getpkt (&reply, &reply_size, 0);
4935     }
4936
4937   do_cleanups (old_chain);
4938 }
4939
4940 static struct serial *
4941 remote_serial_open (const char *name)
4942 {
4943   static int udp_warning = 0;
4944
4945   /* FIXME: Parsing NAME here is a hack.  But we want to warn here instead
4946      of in ser-tcp.c, because it is the remote protocol assuming that the
4947      serial connection is reliable and not the serial connection promising
4948      to be.  */
4949   if (!udp_warning && startswith (name, "udp:"))
4950     {
4951       warning (_("The remote protocol may be unreliable over UDP.\n"
4952                  "Some events may be lost, rendering further debugging "
4953                  "impossible."));
4954       udp_warning = 1;
4955     }
4956
4957   return serial_open (name);
4958 }
4959
4960 /* Inform the target of our permission settings.  The permission flags
4961    work without this, but if the target knows the settings, it can do
4962    a couple things.  First, it can add its own check, to catch cases
4963    that somehow manage to get by the permissions checks in target
4964    methods.  Second, if the target is wired to disallow particular
4965    settings (for instance, a system in the field that is not set up to
4966    be able to stop at a breakpoint), it can object to any unavailable
4967    permissions.  */
4968
4969 void
4970 remote_target::set_permissions ()
4971 {
4972   struct remote_state *rs = get_remote_state ();
4973
4974   xsnprintf (rs->buf, get_remote_packet_size (), "QAllow:"
4975              "WriteReg:%x;WriteMem:%x;"
4976              "InsertBreak:%x;InsertTrace:%x;"
4977              "InsertFastTrace:%x;Stop:%x",
4978              may_write_registers, may_write_memory,
4979              may_insert_breakpoints, may_insert_tracepoints,
4980              may_insert_fast_tracepoints, may_stop);
4981   putpkt (rs->buf);
4982   getpkt (&rs->buf, &rs->buf_size, 0);
4983
4984   /* If the target didn't like the packet, warn the user.  Do not try
4985      to undo the user's settings, that would just be maddening.  */
4986   if (strcmp (rs->buf, "OK") != 0)
4987     warning (_("Remote refused setting permissions with: %s"), rs->buf);
4988 }
4989
4990 /* This type describes each known response to the qSupported
4991    packet.  */
4992 struct protocol_feature
4993 {
4994   /* The name of this protocol feature.  */
4995   const char *name;
4996
4997   /* The default for this protocol feature.  */
4998   enum packet_support default_support;
4999
5000   /* The function to call when this feature is reported, or after
5001      qSupported processing if the feature is not supported.
5002      The first argument points to this structure.  The second
5003      argument indicates whether the packet requested support be
5004      enabled, disabled, or probed (or the default, if this function
5005      is being called at the end of processing and this feature was
5006      not reported).  The third argument may be NULL; if not NULL, it
5007      is a NUL-terminated string taken from the packet following
5008      this feature's name and an equals sign.  */
5009   void (*func) (remote_target *remote, const struct protocol_feature *,
5010                 enum packet_support, const char *);
5011
5012   /* The corresponding packet for this feature.  Only used if
5013      FUNC is remote_supported_packet.  */
5014   int packet;
5015 };
5016
5017 static void
5018 remote_supported_packet (remote_target *remote,
5019                          const struct protocol_feature *feature,
5020                          enum packet_support support,
5021                          const char *argument)
5022 {
5023   if (argument)
5024     {
5025       warning (_("Remote qSupported response supplied an unexpected value for"
5026                  " \"%s\"."), feature->name);
5027       return;
5028     }
5029
5030   remote_protocol_packets[feature->packet].support = support;
5031 }
5032
5033 void
5034 remote_target::remote_packet_size (const protocol_feature *feature,
5035                                    enum packet_support support, const char *value)
5036 {
5037   struct remote_state *rs = get_remote_state ();
5038
5039   int packet_size;
5040   char *value_end;
5041
5042   if (support != PACKET_ENABLE)
5043     return;
5044
5045   if (value == NULL || *value == '\0')
5046     {
5047       warning (_("Remote target reported \"%s\" without a size."),
5048                feature->name);
5049       return;
5050     }
5051
5052   errno = 0;
5053   packet_size = strtol (value, &value_end, 16);
5054   if (errno != 0 || *value_end != '\0' || packet_size < 0)
5055     {
5056       warning (_("Remote target reported \"%s\" with a bad size: \"%s\"."),
5057                feature->name, value);
5058       return;
5059     }
5060
5061   /* Record the new maximum packet size.  */
5062   rs->explicit_packet_size = packet_size;
5063 }
5064
5065 void
5066 remote_packet_size (remote_target *remote, const protocol_feature *feature,
5067                     enum packet_support support, const char *value)
5068 {
5069   remote->remote_packet_size (feature, support, value);
5070 }
5071
5072 static const struct protocol_feature remote_protocol_features[] = {
5073   { "PacketSize", PACKET_DISABLE, remote_packet_size, -1 },
5074   { "qXfer:auxv:read", PACKET_DISABLE, remote_supported_packet,
5075     PACKET_qXfer_auxv },
5076   { "qXfer:exec-file:read", PACKET_DISABLE, remote_supported_packet,
5077     PACKET_qXfer_exec_file },
5078   { "qXfer:features:read", PACKET_DISABLE, remote_supported_packet,
5079     PACKET_qXfer_features },
5080   { "qXfer:libraries:read", PACKET_DISABLE, remote_supported_packet,
5081     PACKET_qXfer_libraries },
5082   { "qXfer:libraries-svr4:read", PACKET_DISABLE, remote_supported_packet,
5083     PACKET_qXfer_libraries_svr4 },
5084   { "augmented-libraries-svr4-read", PACKET_DISABLE,
5085     remote_supported_packet, PACKET_augmented_libraries_svr4_read_feature },
5086   { "qXfer:memory-map:read", PACKET_DISABLE, remote_supported_packet,
5087     PACKET_qXfer_memory_map },
5088   { "qXfer:spu:read", PACKET_DISABLE, remote_supported_packet,
5089     PACKET_qXfer_spu_read },
5090   { "qXfer:spu:write", PACKET_DISABLE, remote_supported_packet,
5091     PACKET_qXfer_spu_write },
5092   { "qXfer:osdata:read", PACKET_DISABLE, remote_supported_packet,
5093     PACKET_qXfer_osdata },
5094   { "qXfer:threads:read", PACKET_DISABLE, remote_supported_packet,
5095     PACKET_qXfer_threads },
5096   { "qXfer:traceframe-info:read", PACKET_DISABLE, remote_supported_packet,
5097     PACKET_qXfer_traceframe_info },
5098   { "QPassSignals", PACKET_DISABLE, remote_supported_packet,
5099     PACKET_QPassSignals },
5100   { "QCatchSyscalls", PACKET_DISABLE, remote_supported_packet,
5101     PACKET_QCatchSyscalls },
5102   { "QProgramSignals", PACKET_DISABLE, remote_supported_packet,
5103     PACKET_QProgramSignals },
5104   { "QSetWorkingDir", PACKET_DISABLE, remote_supported_packet,
5105     PACKET_QSetWorkingDir },
5106   { "QStartupWithShell", PACKET_DISABLE, remote_supported_packet,
5107     PACKET_QStartupWithShell },
5108   { "QEnvironmentHexEncoded", PACKET_DISABLE, remote_supported_packet,
5109     PACKET_QEnvironmentHexEncoded },
5110   { "QEnvironmentReset", PACKET_DISABLE, remote_supported_packet,
5111     PACKET_QEnvironmentReset },
5112   { "QEnvironmentUnset", PACKET_DISABLE, remote_supported_packet,
5113     PACKET_QEnvironmentUnset },
5114   { "QStartNoAckMode", PACKET_DISABLE, remote_supported_packet,
5115     PACKET_QStartNoAckMode },
5116   { "multiprocess", PACKET_DISABLE, remote_supported_packet,
5117     PACKET_multiprocess_feature },
5118   { "QNonStop", PACKET_DISABLE, remote_supported_packet, PACKET_QNonStop },
5119   { "qXfer:siginfo:read", PACKET_DISABLE, remote_supported_packet,
5120     PACKET_qXfer_siginfo_read },
5121   { "qXfer:siginfo:write", PACKET_DISABLE, remote_supported_packet,
5122     PACKET_qXfer_siginfo_write },
5123   { "ConditionalTracepoints", PACKET_DISABLE, remote_supported_packet,
5124     PACKET_ConditionalTracepoints },
5125   { "ConditionalBreakpoints", PACKET_DISABLE, remote_supported_packet,
5126     PACKET_ConditionalBreakpoints },
5127   { "BreakpointCommands", PACKET_DISABLE, remote_supported_packet,
5128     PACKET_BreakpointCommands },
5129   { "FastTracepoints", PACKET_DISABLE, remote_supported_packet,
5130     PACKET_FastTracepoints },
5131   { "StaticTracepoints", PACKET_DISABLE, remote_supported_packet,
5132     PACKET_StaticTracepoints },
5133   {"InstallInTrace", PACKET_DISABLE, remote_supported_packet,
5134    PACKET_InstallInTrace},
5135   { "DisconnectedTracing", PACKET_DISABLE, remote_supported_packet,
5136     PACKET_DisconnectedTracing_feature },
5137   { "ReverseContinue", PACKET_DISABLE, remote_supported_packet,
5138     PACKET_bc },
5139   { "ReverseStep", PACKET_DISABLE, remote_supported_packet,
5140     PACKET_bs },
5141   { "TracepointSource", PACKET_DISABLE, remote_supported_packet,
5142     PACKET_TracepointSource },
5143   { "QAllow", PACKET_DISABLE, remote_supported_packet,
5144     PACKET_QAllow },
5145   { "EnableDisableTracepoints", PACKET_DISABLE, remote_supported_packet,
5146     PACKET_EnableDisableTracepoints_feature },
5147   { "qXfer:fdpic:read", PACKET_DISABLE, remote_supported_packet,
5148     PACKET_qXfer_fdpic },
5149   { "qXfer:uib:read", PACKET_DISABLE, remote_supported_packet,
5150     PACKET_qXfer_uib },
5151   { "QDisableRandomization", PACKET_DISABLE, remote_supported_packet,
5152     PACKET_QDisableRandomization },
5153   { "QAgent", PACKET_DISABLE, remote_supported_packet, PACKET_QAgent},
5154   { "QTBuffer:size", PACKET_DISABLE,
5155     remote_supported_packet, PACKET_QTBuffer_size},
5156   { "tracenz", PACKET_DISABLE, remote_supported_packet, PACKET_tracenz_feature },
5157   { "Qbtrace:off", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_off },
5158   { "Qbtrace:bts", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_bts },
5159   { "Qbtrace:pt", PACKET_DISABLE, remote_supported_packet, PACKET_Qbtrace_pt },
5160   { "qXfer:btrace:read", PACKET_DISABLE, remote_supported_packet,
5161     PACKET_qXfer_btrace },
5162   { "qXfer:btrace-conf:read", PACKET_DISABLE, remote_supported_packet,
5163     PACKET_qXfer_btrace_conf },
5164   { "Qbtrace-conf:bts:size", PACKET_DISABLE, remote_supported_packet,
5165     PACKET_Qbtrace_conf_bts_size },
5166   { "swbreak", PACKET_DISABLE, remote_supported_packet, PACKET_swbreak_feature },
5167   { "hwbreak", PACKET_DISABLE, remote_supported_packet, PACKET_hwbreak_feature },
5168   { "fork-events", PACKET_DISABLE, remote_supported_packet,
5169     PACKET_fork_event_feature },
5170   { "vfork-events", PACKET_DISABLE, remote_supported_packet,
5171     PACKET_vfork_event_feature },
5172   { "exec-events", PACKET_DISABLE, remote_supported_packet,
5173     PACKET_exec_event_feature },
5174   { "Qbtrace-conf:pt:size", PACKET_DISABLE, remote_supported_packet,
5175     PACKET_Qbtrace_conf_pt_size },
5176   { "vContSupported", PACKET_DISABLE, remote_supported_packet, PACKET_vContSupported },
5177   { "QThreadEvents", PACKET_DISABLE, remote_supported_packet, PACKET_QThreadEvents },
5178   { "no-resumed", PACKET_DISABLE, remote_supported_packet, PACKET_no_resumed },
5179 };
5180
5181 static char *remote_support_xml;
5182
5183 /* Register string appended to "xmlRegisters=" in qSupported query.  */
5184
5185 void
5186 register_remote_support_xml (const char *xml)
5187 {
5188 #if defined(HAVE_LIBEXPAT)
5189   if (remote_support_xml == NULL)
5190     remote_support_xml = concat ("xmlRegisters=", xml, (char *) NULL);
5191   else
5192     {
5193       char *copy = xstrdup (remote_support_xml + 13);
5194       char *p = strtok (copy, ",");
5195
5196       do
5197         {
5198           if (strcmp (p, xml) == 0)
5199             {
5200               /* already there */
5201               xfree (copy);
5202               return;
5203             }
5204         }
5205       while ((p = strtok (NULL, ",")) != NULL);
5206       xfree (copy);
5207
5208       remote_support_xml = reconcat (remote_support_xml,
5209                                      remote_support_xml, ",", xml,
5210                                      (char *) NULL);
5211     }
5212 #endif
5213 }
5214
5215 static void
5216 remote_query_supported_append (std::string *msg, const char *append)
5217 {
5218   if (!msg->empty ())
5219     msg->append (";");
5220   msg->append (append);
5221 }
5222
5223 void
5224 remote_target::remote_query_supported ()
5225 {
5226   struct remote_state *rs = get_remote_state ();
5227   char *next;
5228   int i;
5229   unsigned char seen [ARRAY_SIZE (remote_protocol_features)];
5230
5231   /* The packet support flags are handled differently for this packet
5232      than for most others.  We treat an error, a disabled packet, and
5233      an empty response identically: any features which must be reported
5234      to be used will be automatically disabled.  An empty buffer
5235      accomplishes this, since that is also the representation for a list
5236      containing no features.  */
5237
5238   rs->buf[0] = 0;
5239   if (packet_support (PACKET_qSupported) != PACKET_DISABLE)
5240     {
5241       std::string q;
5242
5243       if (packet_set_cmd_state (PACKET_multiprocess_feature) != AUTO_BOOLEAN_FALSE)
5244         remote_query_supported_append (&q, "multiprocess+");
5245
5246       if (packet_set_cmd_state (PACKET_swbreak_feature) != AUTO_BOOLEAN_FALSE)
5247         remote_query_supported_append (&q, "swbreak+");
5248       if (packet_set_cmd_state (PACKET_hwbreak_feature) != AUTO_BOOLEAN_FALSE)
5249         remote_query_supported_append (&q, "hwbreak+");
5250
5251       remote_query_supported_append (&q, "qRelocInsn+");
5252
5253       if (packet_set_cmd_state (PACKET_fork_event_feature)
5254           != AUTO_BOOLEAN_FALSE)
5255         remote_query_supported_append (&q, "fork-events+");
5256       if (packet_set_cmd_state (PACKET_vfork_event_feature)
5257           != AUTO_BOOLEAN_FALSE)
5258         remote_query_supported_append (&q, "vfork-events+");
5259       if (packet_set_cmd_state (PACKET_exec_event_feature)
5260           != AUTO_BOOLEAN_FALSE)
5261         remote_query_supported_append (&q, "exec-events+");
5262
5263       if (packet_set_cmd_state (PACKET_vContSupported) != AUTO_BOOLEAN_FALSE)
5264         remote_query_supported_append (&q, "vContSupported+");
5265
5266       if (packet_set_cmd_state (PACKET_QThreadEvents) != AUTO_BOOLEAN_FALSE)
5267         remote_query_supported_append (&q, "QThreadEvents+");
5268
5269       if (packet_set_cmd_state (PACKET_no_resumed) != AUTO_BOOLEAN_FALSE)
5270         remote_query_supported_append (&q, "no-resumed+");
5271
5272       /* Keep this one last to work around a gdbserver <= 7.10 bug in
5273          the qSupported:xmlRegisters=i386 handling.  */
5274       if (remote_support_xml != NULL
5275           && packet_support (PACKET_qXfer_features) != PACKET_DISABLE)
5276         remote_query_supported_append (&q, remote_support_xml);
5277
5278       q = "qSupported:" + q;
5279       putpkt (q.c_str ());
5280
5281       getpkt (&rs->buf, &rs->buf_size, 0);
5282
5283       /* If an error occured, warn, but do not return - just reset the
5284          buffer to empty and go on to disable features.  */
5285       if (packet_ok (rs->buf, &remote_protocol_packets[PACKET_qSupported])
5286           == PACKET_ERROR)
5287         {
5288           warning (_("Remote failure reply: %s"), rs->buf);
5289           rs->buf[0] = 0;
5290         }
5291     }
5292
5293   memset (seen, 0, sizeof (seen));
5294
5295   next = rs->buf;
5296   while (*next)
5297     {
5298       enum packet_support is_supported;
5299       char *p, *end, *name_end, *value;
5300
5301       /* First separate out this item from the rest of the packet.  If
5302          there's another item after this, we overwrite the separator
5303          (terminated strings are much easier to work with).  */
5304       p = next;
5305       end = strchr (p, ';');
5306       if (end == NULL)
5307         {
5308           end = p + strlen (p);
5309           next = end;
5310         }
5311       else
5312         {
5313           *end = '\0';
5314           next = end + 1;
5315
5316           if (end == p)
5317             {
5318               warning (_("empty item in \"qSupported\" response"));
5319               continue;
5320             }
5321         }
5322
5323       name_end = strchr (p, '=');
5324       if (name_end)
5325         {
5326           /* This is a name=value entry.  */
5327           is_supported = PACKET_ENABLE;
5328           value = name_end + 1;
5329           *name_end = '\0';
5330         }
5331       else
5332         {
5333           value = NULL;
5334           switch (end[-1])
5335             {
5336             case '+':
5337               is_supported = PACKET_ENABLE;
5338               break;
5339
5340             case '-':
5341               is_supported = PACKET_DISABLE;
5342               break;
5343
5344             case '?':
5345               is_supported = PACKET_SUPPORT_UNKNOWN;
5346               break;
5347
5348             default:
5349               warning (_("unrecognized item \"%s\" "
5350                          "in \"qSupported\" response"), p);
5351               continue;
5352             }
5353           end[-1] = '\0';
5354         }
5355
5356       for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5357         if (strcmp (remote_protocol_features[i].name, p) == 0)
5358           {
5359             const struct protocol_feature *feature;
5360
5361             seen[i] = 1;
5362             feature = &remote_protocol_features[i];
5363             feature->func (this, feature, is_supported, value);
5364             break;
5365           }
5366     }
5367
5368   /* If we increased the packet size, make sure to increase the global
5369      buffer size also.  We delay this until after parsing the entire
5370      qSupported packet, because this is the same buffer we were
5371      parsing.  */
5372   if (rs->buf_size < rs->explicit_packet_size)
5373     {
5374       rs->buf_size = rs->explicit_packet_size;
5375       rs->buf = (char *) xrealloc (rs->buf, rs->buf_size);
5376     }
5377
5378   /* Handle the defaults for unmentioned features.  */
5379   for (i = 0; i < ARRAY_SIZE (remote_protocol_features); i++)
5380     if (!seen[i])
5381       {
5382         const struct protocol_feature *feature;
5383
5384         feature = &remote_protocol_features[i];
5385         feature->func (this, feature, feature->default_support, NULL);
5386       }
5387 }
5388
5389 /* Serial QUIT handler for the remote serial descriptor.
5390
5391    Defers handling a Ctrl-C until we're done with the current
5392    command/response packet sequence, unless:
5393
5394    - We're setting up the connection.  Don't send a remote interrupt
5395      request, as we're not fully synced yet.  Quit immediately
5396      instead.
5397
5398    - The target has been resumed in the foreground
5399      (target_terminal::is_ours is false) with a synchronous resume
5400      packet, and we're blocked waiting for the stop reply, thus a
5401      Ctrl-C should be immediately sent to the target.
5402
5403    - We get a second Ctrl-C while still within the same serial read or
5404      write.  In that case the serial is seemingly wedged --- offer to
5405      quit/disconnect.
5406
5407    - We see a second Ctrl-C without target response, after having
5408      previously interrupted the target.  In that case the target/stub
5409      is probably wedged --- offer to quit/disconnect.
5410 */
5411
5412 void
5413 remote_target::remote_serial_quit_handler ()
5414 {
5415   struct remote_state *rs = get_remote_state ();
5416
5417   if (check_quit_flag ())
5418     {
5419       /* If we're starting up, we're not fully synced yet.  Quit
5420          immediately.  */
5421       if (rs->starting_up)
5422         quit ();
5423       else if (rs->got_ctrlc_during_io)
5424         {
5425           if (query (_("The target is not responding to GDB commands.\n"
5426                        "Stop debugging it? ")))
5427             remote_unpush_and_throw ();
5428         }
5429       /* If ^C has already been sent once, offer to disconnect.  */
5430       else if (!target_terminal::is_ours () && rs->ctrlc_pending_p)
5431         interrupt_query ();
5432       /* All-stop protocol, and blocked waiting for stop reply.  Send
5433          an interrupt request.  */
5434       else if (!target_terminal::is_ours () && rs->waiting_for_stop_reply)
5435         target_interrupt ();
5436       else
5437         rs->got_ctrlc_during_io = 1;
5438     }
5439 }
5440
5441 /* The remote_target that is current while the quit handler is
5442    overridden with remote_serial_quit_handler.  */
5443 static remote_target *curr_quit_handler_target;
5444
5445 static void
5446 remote_serial_quit_handler ()
5447 {
5448   curr_quit_handler_target->remote_serial_quit_handler ();
5449 }
5450
5451 /* Remove any of the remote.c targets from target stack.  Upper targets depend
5452    on it so remove them first.  */
5453
5454 static void
5455 remote_unpush_target (void)
5456 {
5457   pop_all_targets_at_and_above (process_stratum);
5458 }
5459
5460 static void
5461 remote_unpush_and_throw (void)
5462 {
5463   remote_unpush_target ();
5464   throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
5465 }
5466
5467 void
5468 remote_target::open_1 (const char *name, int from_tty, int extended_p)
5469 {
5470   remote_target *curr_remote = get_current_remote_target ();
5471
5472   if (name == 0)
5473     error (_("To open a remote debug connection, you need to specify what\n"
5474            "serial device is attached to the remote system\n"
5475            "(e.g. /dev/ttyS0, /dev/ttya, COM1, etc.)."));
5476
5477   /* If we're connected to a running target, target_preopen will kill it.
5478      Ask this question first, before target_preopen has a chance to kill
5479      anything.  */
5480   if (curr_remote != NULL && !have_inferiors ())
5481     {
5482       if (from_tty
5483           && !query (_("Already connected to a remote target.  Disconnect? ")))
5484         error (_("Still connected."));
5485     }
5486
5487   /* Here the possibly existing remote target gets unpushed.  */
5488   target_preopen (from_tty);
5489
5490   remote_fileio_reset ();
5491   reopen_exec_file ();
5492   reread_symbols ();
5493
5494   remote_target *remote
5495     = (extended_p ? new extended_remote_target () : new remote_target ());
5496   target_ops_up target_holder (remote);
5497
5498   remote_state *rs = remote->get_remote_state ();
5499
5500   /* See FIXME above.  */
5501   if (!target_async_permitted)
5502     rs->wait_forever_enabled_p = 1;
5503
5504   rs->remote_desc = remote_serial_open (name);
5505   if (!rs->remote_desc)
5506     perror_with_name (name);
5507
5508   if (baud_rate != -1)
5509     {
5510       if (serial_setbaudrate (rs->remote_desc, baud_rate))
5511         {
5512           /* The requested speed could not be set.  Error out to
5513              top level after closing remote_desc.  Take care to
5514              set remote_desc to NULL to avoid closing remote_desc
5515              more than once.  */
5516           serial_close (rs->remote_desc);
5517           rs->remote_desc = NULL;
5518           perror_with_name (name);
5519         }
5520     }
5521
5522   serial_setparity (rs->remote_desc, serial_parity);
5523   serial_raw (rs->remote_desc);
5524
5525   /* If there is something sitting in the buffer we might take it as a
5526      response to a command, which would be bad.  */
5527   serial_flush_input (rs->remote_desc);
5528
5529   if (from_tty)
5530     {
5531       puts_filtered ("Remote debugging using ");
5532       puts_filtered (name);
5533       puts_filtered ("\n");
5534     }
5535
5536   /* Switch to using the remote target now.  */
5537   push_target (remote);
5538   /* The target stack owns the target now.  */
5539   target_holder.release ();
5540
5541   /* Register extra event sources in the event loop.  */
5542   rs->remote_async_inferior_event_token
5543     = create_async_event_handler (remote_async_inferior_event_handler,
5544                                   remote);
5545   rs->notif_state = remote_notif_state_allocate (remote);
5546
5547   /* Reset the target state; these things will be queried either by
5548      remote_query_supported or as they are needed.  */
5549   reset_all_packet_configs_support ();
5550   rs->cached_wait_status = 0;
5551   rs->explicit_packet_size = 0;
5552   rs->noack_mode = 0;
5553   rs->extended = extended_p;
5554   rs->waiting_for_stop_reply = 0;
5555   rs->ctrlc_pending_p = 0;
5556   rs->got_ctrlc_during_io = 0;
5557
5558   rs->general_thread = not_sent_ptid;
5559   rs->continue_thread = not_sent_ptid;
5560   rs->remote_traceframe_number = -1;
5561
5562   rs->last_resume_exec_dir = EXEC_FORWARD;
5563
5564   /* Probe for ability to use "ThreadInfo" query, as required.  */
5565   rs->use_threadinfo_query = 1;
5566   rs->use_threadextra_query = 1;
5567
5568   rs->readahead_cache.invalidate ();
5569
5570   if (target_async_permitted)
5571     {
5572       /* FIXME: cagney/1999-09-23: During the initial connection it is
5573          assumed that the target is already ready and able to respond to
5574          requests.  Unfortunately remote_start_remote() eventually calls
5575          wait_for_inferior() with no timeout.  wait_forever_enabled_p gets
5576          around this.  Eventually a mechanism that allows
5577          wait_for_inferior() to expect/get timeouts will be
5578          implemented.  */
5579       rs->wait_forever_enabled_p = 0;
5580     }
5581
5582   /* First delete any symbols previously loaded from shared libraries.  */
5583   no_shared_libraries (NULL, 0);
5584
5585   /* Start afresh.  */
5586   init_thread_list ();
5587
5588   /* Start the remote connection.  If error() or QUIT, discard this
5589      target (we'd otherwise be in an inconsistent state) and then
5590      propogate the error on up the exception chain.  This ensures that
5591      the caller doesn't stumble along blindly assuming that the
5592      function succeeded.  The CLI doesn't have this problem but other
5593      UI's, such as MI do.
5594
5595      FIXME: cagney/2002-05-19: Instead of re-throwing the exception,
5596      this function should return an error indication letting the
5597      caller restore the previous state.  Unfortunately the command
5598      ``target remote'' is directly wired to this function making that
5599      impossible.  On a positive note, the CLI side of this problem has
5600      been fixed - the function set_cmd_context() makes it possible for
5601      all the ``target ....'' commands to share a common callback
5602      function.  See cli-dump.c.  */
5603   {
5604
5605     TRY
5606       {
5607         remote->start_remote (from_tty, extended_p);
5608       }
5609     CATCH (ex, RETURN_MASK_ALL)
5610       {
5611         /* Pop the partially set up target - unless something else did
5612            already before throwing the exception.  */
5613         if (ex.error != TARGET_CLOSE_ERROR)
5614           remote_unpush_target ();
5615         throw_exception (ex);
5616       }
5617     END_CATCH
5618   }
5619
5620   remote_btrace_reset (rs);
5621
5622   if (target_async_permitted)
5623     rs->wait_forever_enabled_p = 1;
5624 }
5625
5626 /* Detach the specified process.  */
5627
5628 void
5629 remote_target::remote_detach_pid (int pid)
5630 {
5631   struct remote_state *rs = get_remote_state ();
5632
5633   if (remote_multi_process_p (rs))
5634     xsnprintf (rs->buf, get_remote_packet_size (), "D;%x", pid);
5635   else
5636     strcpy (rs->buf, "D");
5637
5638   putpkt (rs->buf);
5639   getpkt (&rs->buf, &rs->buf_size, 0);
5640
5641   if (rs->buf[0] == 'O' && rs->buf[1] == 'K')
5642     ;
5643   else if (rs->buf[0] == '\0')
5644     error (_("Remote doesn't know how to detach"));
5645   else
5646     error (_("Can't detach process."));
5647 }
5648
5649 /* This detaches a program to which we previously attached, using
5650    inferior_ptid to identify the process.  After this is done, GDB
5651    can be used to debug some other program.  We better not have left
5652    any breakpoints in the target program or it'll die when it hits
5653    one.  */
5654
5655 void
5656 remote_target::remote_detach_1 (int from_tty, inferior *inf)
5657 {
5658   int pid = ptid_get_pid (inferior_ptid);
5659   struct remote_state *rs = get_remote_state ();
5660   struct thread_info *tp = find_thread_ptid (inferior_ptid);
5661   int is_fork_parent;
5662
5663   if (!target_has_execution)
5664     error (_("No process to detach from."));
5665
5666   target_announce_detach (from_tty);
5667
5668   /* Tell the remote target to detach.  */
5669   remote_detach_pid (pid);
5670
5671   /* Exit only if this is the only active inferior.  */
5672   if (from_tty && !rs->extended && number_of_live_inferiors () == 1)
5673     puts_filtered (_("Ending remote debugging.\n"));
5674
5675   /* Check to see if we are detaching a fork parent.  Note that if we
5676      are detaching a fork child, tp == NULL.  */
5677   is_fork_parent = (tp != NULL
5678                     && tp->pending_follow.kind == TARGET_WAITKIND_FORKED);
5679
5680   /* If doing detach-on-fork, we don't mourn, because that will delete
5681      breakpoints that should be available for the followed inferior.  */
5682   if (!is_fork_parent)
5683     {
5684       /* Save the pid as a string before mourning, since that will
5685          unpush the remote target, and we need the string after.  */
5686       std::string infpid = target_pid_to_str (pid_to_ptid (pid));
5687
5688       target_mourn_inferior (inferior_ptid);
5689       if (print_inferior_events)
5690         printf_unfiltered (_("[Inferior %d (%s) detached]\n"),
5691                            inf->num, infpid.c_str ());
5692     }
5693   else
5694     {
5695       inferior_ptid = null_ptid;
5696       detach_inferior (pid);
5697     }
5698 }
5699
5700 void
5701 remote_target::detach (inferior *inf, int from_tty)
5702 {
5703   remote_detach_1 (from_tty, inf);
5704 }
5705
5706 void
5707 extended_remote_target::detach (inferior *inf, int from_tty)
5708 {
5709   remote_detach_1 (from_tty, inf);
5710 }
5711
5712 /* Target follow-fork function for remote targets.  On entry, and
5713    at return, the current inferior is the fork parent.
5714
5715    Note that although this is currently only used for extended-remote,
5716    it is named remote_follow_fork in anticipation of using it for the
5717    remote target as well.  */
5718
5719 int
5720 remote_target::follow_fork (int follow_child, int detach_fork)
5721 {
5722   struct remote_state *rs = get_remote_state ();
5723   enum target_waitkind kind = inferior_thread ()->pending_follow.kind;
5724
5725   if ((kind == TARGET_WAITKIND_FORKED && remote_fork_event_p (rs))
5726       || (kind == TARGET_WAITKIND_VFORKED && remote_vfork_event_p (rs)))
5727     {
5728       /* When following the parent and detaching the child, we detach
5729          the child here.  For the case of following the child and
5730          detaching the parent, the detach is done in the target-
5731          independent follow fork code in infrun.c.  We can't use
5732          target_detach when detaching an unfollowed child because
5733          the client side doesn't know anything about the child.  */
5734       if (detach_fork && !follow_child)
5735         {
5736           /* Detach the fork child.  */
5737           ptid_t child_ptid;
5738           pid_t child_pid;
5739
5740           child_ptid = inferior_thread ()->pending_follow.value.related_pid;
5741           child_pid = ptid_get_pid (child_ptid);
5742
5743           remote_detach_pid (child_pid);
5744         }
5745     }
5746   return 0;
5747 }
5748
5749 /* Target follow-exec function for remote targets.  Save EXECD_PATHNAME
5750    in the program space of the new inferior.  On entry and at return the
5751    current inferior is the exec'ing inferior.  INF is the new exec'd
5752    inferior, which may be the same as the exec'ing inferior unless
5753    follow-exec-mode is "new".  */
5754
5755 void
5756 remote_target::follow_exec (struct inferior *inf, char *execd_pathname)
5757 {
5758   /* We know that this is a target file name, so if it has the "target:"
5759      prefix we strip it off before saving it in the program space.  */
5760   if (is_target_filename (execd_pathname))
5761     execd_pathname += strlen (TARGET_SYSROOT_PREFIX);
5762
5763   set_pspace_remote_exec_file (inf->pspace, execd_pathname);
5764 }
5765
5766 /* Same as remote_detach, but don't send the "D" packet; just disconnect.  */
5767
5768 void
5769 remote_target::disconnect (const char *args, int from_tty)
5770 {
5771   if (args)
5772     error (_("Argument given to \"disconnect\" when remotely debugging."));
5773
5774   /* Make sure we unpush even the extended remote targets.  Calling
5775      target_mourn_inferior won't unpush, and remote_mourn won't
5776      unpush if there is more than one inferior left.  */
5777   unpush_target (this);
5778   generic_mourn_inferior ();
5779
5780   if (from_tty)
5781     puts_filtered ("Ending remote debugging.\n");
5782 }
5783
5784 /* Attach to the process specified by ARGS.  If FROM_TTY is non-zero,
5785    be chatty about it.  */
5786
5787 void
5788 extended_remote_target::attach (const char *args, int from_tty)
5789 {
5790   struct remote_state *rs = get_remote_state ();
5791   int pid;
5792   char *wait_status = NULL;
5793
5794   pid = parse_pid_to_attach (args);
5795
5796   /* Remote PID can be freely equal to getpid, do not check it here the same
5797      way as in other targets.  */
5798
5799   if (packet_support (PACKET_vAttach) == PACKET_DISABLE)
5800     error (_("This target does not support attaching to a process"));
5801
5802   if (from_tty)
5803     {
5804       char *exec_file = get_exec_file (0);
5805
5806       if (exec_file)
5807         printf_unfiltered (_("Attaching to program: %s, %s\n"), exec_file,
5808                            target_pid_to_str (pid_to_ptid (pid)));
5809       else
5810         printf_unfiltered (_("Attaching to %s\n"),
5811                            target_pid_to_str (pid_to_ptid (pid)));
5812
5813       gdb_flush (gdb_stdout);
5814     }
5815
5816   xsnprintf (rs->buf, get_remote_packet_size (), "vAttach;%x", pid);
5817   putpkt (rs->buf);
5818   getpkt (&rs->buf, &rs->buf_size, 0);
5819
5820   switch (packet_ok (rs->buf,
5821                      &remote_protocol_packets[PACKET_vAttach]))
5822     {
5823     case PACKET_OK:
5824       if (!target_is_non_stop_p ())
5825         {
5826           /* Save the reply for later.  */
5827           wait_status = (char *) alloca (strlen (rs->buf) + 1);
5828           strcpy (wait_status, rs->buf);
5829         }
5830       else if (strcmp (rs->buf, "OK") != 0)
5831         error (_("Attaching to %s failed with: %s"),
5832                target_pid_to_str (pid_to_ptid (pid)),
5833                rs->buf);
5834       break;
5835     case PACKET_UNKNOWN:
5836       error (_("This target does not support attaching to a process"));
5837     default:
5838       error (_("Attaching to %s failed"),
5839              target_pid_to_str (pid_to_ptid (pid)));
5840     }
5841
5842   set_current_inferior (remote_add_inferior (0, pid, 1, 0));
5843
5844   inferior_ptid = pid_to_ptid (pid);
5845
5846   if (target_is_non_stop_p ())
5847     {
5848       struct thread_info *thread;
5849
5850       /* Get list of threads.  */
5851       update_thread_list ();
5852
5853       thread = first_thread_of_process (pid);
5854       if (thread)
5855         inferior_ptid = thread->ptid;
5856       else
5857         inferior_ptid = pid_to_ptid (pid);
5858
5859       /* Invalidate our notion of the remote current thread.  */
5860       record_currthread (rs, minus_one_ptid);
5861     }
5862   else
5863     {
5864       /* Now, if we have thread information, update inferior_ptid.  */
5865       inferior_ptid = remote_current_thread (inferior_ptid);
5866
5867       /* Add the main thread to the thread list.  */
5868       thread_info *thr = add_thread_silent (inferior_ptid);
5869       /* Don't consider the thread stopped until we've processed the
5870          saved stop reply.  */
5871       set_executing (thr->ptid, true);
5872     }
5873
5874   /* Next, if the target can specify a description, read it.  We do
5875      this before anything involving memory or registers.  */
5876   target_find_description ();
5877
5878   if (!target_is_non_stop_p ())
5879     {
5880       /* Use the previously fetched status.  */
5881       gdb_assert (wait_status != NULL);
5882
5883       if (target_can_async_p ())
5884         {
5885           struct notif_event *reply
5886             =  remote_notif_parse (this, &notif_client_stop, wait_status);
5887
5888           push_stop_reply ((struct stop_reply *) reply);
5889
5890           target_async (1);
5891         }
5892       else
5893         {
5894           gdb_assert (wait_status != NULL);
5895           strcpy (rs->buf, wait_status);
5896           rs->cached_wait_status = 1;
5897         }
5898     }
5899   else
5900     gdb_assert (wait_status == NULL);
5901 }
5902
5903 /* Implementation of the to_post_attach method.  */
5904
5905 void
5906 extended_remote_target::post_attach (int pid)
5907 {
5908   /* Get text, data & bss offsets.  */
5909   get_offsets ();
5910
5911   /* In certain cases GDB might not have had the chance to start
5912      symbol lookup up until now.  This could happen if the debugged
5913      binary is not using shared libraries, the vsyscall page is not
5914      present (on Linux) and the binary itself hadn't changed since the
5915      debugging process was started.  */
5916   if (symfile_objfile != NULL)
5917     remote_check_symbols();
5918 }
5919
5920 \f
5921 /* Check for the availability of vCont.  This function should also check
5922    the response.  */
5923
5924 void
5925 remote_target::remote_vcont_probe ()
5926 {
5927   remote_state *rs = get_remote_state ();
5928   char *buf;
5929
5930   strcpy (rs->buf, "vCont?");
5931   putpkt (rs->buf);
5932   getpkt (&rs->buf, &rs->buf_size, 0);
5933   buf = rs->buf;
5934
5935   /* Make sure that the features we assume are supported.  */
5936   if (startswith (buf, "vCont"))
5937     {
5938       char *p = &buf[5];
5939       int support_c, support_C;
5940
5941       rs->supports_vCont.s = 0;
5942       rs->supports_vCont.S = 0;
5943       support_c = 0;
5944       support_C = 0;
5945       rs->supports_vCont.t = 0;
5946       rs->supports_vCont.r = 0;
5947       while (p && *p == ';')
5948         {
5949           p++;
5950           if (*p == 's' && (*(p + 1) == ';' || *(p + 1) == 0))
5951             rs->supports_vCont.s = 1;
5952           else if (*p == 'S' && (*(p + 1) == ';' || *(p + 1) == 0))
5953             rs->supports_vCont.S = 1;
5954           else if (*p == 'c' && (*(p + 1) == ';' || *(p + 1) == 0))
5955             support_c = 1;
5956           else if (*p == 'C' && (*(p + 1) == ';' || *(p + 1) == 0))
5957             support_C = 1;
5958           else if (*p == 't' && (*(p + 1) == ';' || *(p + 1) == 0))
5959             rs->supports_vCont.t = 1;
5960           else if (*p == 'r' && (*(p + 1) == ';' || *(p + 1) == 0))
5961             rs->supports_vCont.r = 1;
5962
5963           p = strchr (p, ';');
5964         }
5965
5966       /* If c, and C are not all supported, we can't use vCont.  Clearing
5967          BUF will make packet_ok disable the packet.  */
5968       if (!support_c || !support_C)
5969         buf[0] = 0;
5970     }
5971
5972   packet_ok (buf, &remote_protocol_packets[PACKET_vCont]);
5973 }
5974
5975 /* Helper function for building "vCont" resumptions.  Write a
5976    resumption to P.  ENDP points to one-passed-the-end of the buffer
5977    we're allowed to write to.  Returns BUF+CHARACTERS_WRITTEN.  The
5978    thread to be resumed is PTID; STEP and SIGGNAL indicate whether the
5979    resumed thread should be single-stepped and/or signalled.  If PTID
5980    equals minus_one_ptid, then all threads are resumed; if PTID
5981    represents a process, then all threads of the process are resumed;
5982    the thread to be stepped and/or signalled is given in the global
5983    INFERIOR_PTID.  */
5984
5985 char *
5986 remote_target::append_resumption (char *p, char *endp,
5987                                   ptid_t ptid, int step, gdb_signal siggnal)
5988 {
5989   struct remote_state *rs = get_remote_state ();
5990
5991   if (step && siggnal != GDB_SIGNAL_0)
5992     p += xsnprintf (p, endp - p, ";S%02x", siggnal);
5993   else if (step
5994            /* GDB is willing to range step.  */
5995            && use_range_stepping
5996            /* Target supports range stepping.  */
5997            && rs->supports_vCont.r
5998            /* We don't currently support range stepping multiple
5999               threads with a wildcard (though the protocol allows it,
6000               so stubs shouldn't make an active effort to forbid
6001               it).  */
6002            && !(remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6003     {
6004       struct thread_info *tp;
6005
6006       if (ptid_equal (ptid, minus_one_ptid))
6007         {
6008           /* If we don't know about the target thread's tid, then
6009              we're resuming magic_null_ptid (see caller).  */
6010           tp = find_thread_ptid (magic_null_ptid);
6011         }
6012       else
6013         tp = find_thread_ptid (ptid);
6014       gdb_assert (tp != NULL);
6015
6016       if (tp->control.may_range_step)
6017         {
6018           int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
6019
6020           p += xsnprintf (p, endp - p, ";r%s,%s",
6021                           phex_nz (tp->control.step_range_start,
6022                                    addr_size),
6023                           phex_nz (tp->control.step_range_end,
6024                                    addr_size));
6025         }
6026       else
6027         p += xsnprintf (p, endp - p, ";s");
6028     }
6029   else if (step)
6030     p += xsnprintf (p, endp - p, ";s");
6031   else if (siggnal != GDB_SIGNAL_0)
6032     p += xsnprintf (p, endp - p, ";C%02x", siggnal);
6033   else
6034     p += xsnprintf (p, endp - p, ";c");
6035
6036   if (remote_multi_process_p (rs) && ptid_is_pid (ptid))
6037     {
6038       ptid_t nptid;
6039
6040       /* All (-1) threads of process.  */
6041       nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6042
6043       p += xsnprintf (p, endp - p, ":");
6044       p = write_ptid (p, endp, nptid);
6045     }
6046   else if (!ptid_equal (ptid, minus_one_ptid))
6047     {
6048       p += xsnprintf (p, endp - p, ":");
6049       p = write_ptid (p, endp, ptid);
6050     }
6051
6052   return p;
6053 }
6054
6055 /* Clear the thread's private info on resume.  */
6056
6057 static void
6058 resume_clear_thread_private_info (struct thread_info *thread)
6059 {
6060   if (thread->priv != NULL)
6061     {
6062       remote_thread_info *priv = get_remote_thread_info (thread);
6063
6064       priv->stop_reason = TARGET_STOPPED_BY_NO_REASON;
6065       priv->watch_data_address = 0;
6066     }
6067 }
6068
6069 /* Append a vCont continue-with-signal action for threads that have a
6070    non-zero stop signal.  */
6071
6072 char *
6073 remote_target::append_pending_thread_resumptions (char *p, char *endp,
6074                                                   ptid_t ptid)
6075 {
6076   struct thread_info *thread;
6077
6078   ALL_NON_EXITED_THREADS (thread)
6079     if (ptid_match (thread->ptid, ptid)
6080         && !ptid_equal (inferior_ptid, thread->ptid)
6081         && thread->suspend.stop_signal != GDB_SIGNAL_0)
6082       {
6083         p = append_resumption (p, endp, thread->ptid,
6084                                0, thread->suspend.stop_signal);
6085         thread->suspend.stop_signal = GDB_SIGNAL_0;
6086         resume_clear_thread_private_info (thread);
6087       }
6088
6089   return p;
6090 }
6091
6092 /* Set the target running, using the packets that use Hc
6093    (c/s/C/S).  */
6094
6095 void
6096 remote_target::remote_resume_with_hc (ptid_t ptid, int step,
6097                                       gdb_signal siggnal)
6098 {
6099   struct remote_state *rs = get_remote_state ();
6100   struct thread_info *thread;
6101   char *buf;
6102
6103   rs->last_sent_signal = siggnal;
6104   rs->last_sent_step = step;
6105
6106   /* The c/s/C/S resume packets use Hc, so set the continue
6107      thread.  */
6108   if (ptid_equal (ptid, minus_one_ptid))
6109     set_continue_thread (any_thread_ptid);
6110   else
6111     set_continue_thread (ptid);
6112
6113   ALL_NON_EXITED_THREADS (thread)
6114     resume_clear_thread_private_info (thread);
6115
6116   buf = rs->buf;
6117   if (::execution_direction == EXEC_REVERSE)
6118     {
6119       /* We don't pass signals to the target in reverse exec mode.  */
6120       if (info_verbose && siggnal != GDB_SIGNAL_0)
6121         warning (_(" - Can't pass signal %d to target in reverse: ignored."),
6122                  siggnal);
6123
6124       if (step && packet_support (PACKET_bs) == PACKET_DISABLE)
6125         error (_("Remote reverse-step not supported."));
6126       if (!step && packet_support (PACKET_bc) == PACKET_DISABLE)
6127         error (_("Remote reverse-continue not supported."));
6128
6129       strcpy (buf, step ? "bs" : "bc");
6130     }
6131   else if (siggnal != GDB_SIGNAL_0)
6132     {
6133       buf[0] = step ? 'S' : 'C';
6134       buf[1] = tohex (((int) siggnal >> 4) & 0xf);
6135       buf[2] = tohex (((int) siggnal) & 0xf);
6136       buf[3] = '\0';
6137     }
6138   else
6139     strcpy (buf, step ? "s" : "c");
6140
6141   putpkt (buf);
6142 }
6143
6144 /* Resume the remote inferior by using a "vCont" packet.  The thread
6145    to be resumed is PTID; STEP and SIGGNAL indicate whether the
6146    resumed thread should be single-stepped and/or signalled.  If PTID
6147    equals minus_one_ptid, then all threads are resumed; the thread to
6148    be stepped and/or signalled is given in the global INFERIOR_PTID.
6149    This function returns non-zero iff it resumes the inferior.
6150
6151    This function issues a strict subset of all possible vCont commands
6152    at the moment.  */
6153
6154 int
6155 remote_target::remote_resume_with_vcont (ptid_t ptid, int step,
6156                                          enum gdb_signal siggnal)
6157 {
6158   struct remote_state *rs = get_remote_state ();
6159   char *p;
6160   char *endp;
6161
6162   /* No reverse execution actions defined for vCont.  */
6163   if (::execution_direction == EXEC_REVERSE)
6164     return 0;
6165
6166   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6167     remote_vcont_probe ();
6168
6169   if (packet_support (PACKET_vCont) == PACKET_DISABLE)
6170     return 0;
6171
6172   p = rs->buf;
6173   endp = rs->buf + get_remote_packet_size ();
6174
6175   /* If we could generate a wider range of packets, we'd have to worry
6176      about overflowing BUF.  Should there be a generic
6177      "multi-part-packet" packet?  */
6178
6179   p += xsnprintf (p, endp - p, "vCont");
6180
6181   if (ptid_equal (ptid, magic_null_ptid))
6182     {
6183       /* MAGIC_NULL_PTID means that we don't have any active threads,
6184          so we don't have any TID numbers the inferior will
6185          understand.  Make sure to only send forms that do not specify
6186          a TID.  */
6187       append_resumption (p, endp, minus_one_ptid, step, siggnal);
6188     }
6189   else if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
6190     {
6191       /* Resume all threads (of all processes, or of a single
6192          process), with preference for INFERIOR_PTID.  This assumes
6193          inferior_ptid belongs to the set of all threads we are about
6194          to resume.  */
6195       if (step || siggnal != GDB_SIGNAL_0)
6196         {
6197           /* Step inferior_ptid, with or without signal.  */
6198           p = append_resumption (p, endp, inferior_ptid, step, siggnal);
6199         }
6200
6201       /* Also pass down any pending signaled resumption for other
6202          threads not the current.  */
6203       p = append_pending_thread_resumptions (p, endp, ptid);
6204
6205       /* And continue others without a signal.  */
6206       append_resumption (p, endp, ptid, /*step=*/ 0, GDB_SIGNAL_0);
6207     }
6208   else
6209     {
6210       /* Scheduler locking; resume only PTID.  */
6211       append_resumption (p, endp, ptid, step, siggnal);
6212     }
6213
6214   gdb_assert (strlen (rs->buf) < get_remote_packet_size ());
6215   putpkt (rs->buf);
6216
6217   if (target_is_non_stop_p ())
6218     {
6219       /* In non-stop, the stub replies to vCont with "OK".  The stop
6220          reply will be reported asynchronously by means of a `%Stop'
6221          notification.  */
6222       getpkt (&rs->buf, &rs->buf_size, 0);
6223       if (strcmp (rs->buf, "OK") != 0)
6224         error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6225     }
6226
6227   return 1;
6228 }
6229
6230 /* Tell the remote machine to resume.  */
6231
6232 void
6233 remote_target::resume (ptid_t ptid, int step, enum gdb_signal siggnal)
6234 {
6235   struct remote_state *rs = get_remote_state ();
6236
6237   /* When connected in non-stop mode, the core resumes threads
6238      individually.  Resuming remote threads directly in target_resume
6239      would thus result in sending one packet per thread.  Instead, to
6240      minimize roundtrip latency, here we just store the resume
6241      request; the actual remote resumption will be done in
6242      target_commit_resume / remote_commit_resume, where we'll be able
6243      to do vCont action coalescing.  */
6244   if (target_is_non_stop_p () && ::execution_direction != EXEC_REVERSE)
6245     {
6246       remote_thread_info *remote_thr;
6247
6248       if (ptid_equal (minus_one_ptid, ptid) || ptid_is_pid (ptid))
6249         remote_thr = get_remote_thread_info (inferior_ptid);
6250       else
6251         remote_thr = get_remote_thread_info (ptid);
6252
6253       remote_thr->last_resume_step = step;
6254       remote_thr->last_resume_sig = siggnal;
6255       return;
6256     }
6257
6258   /* In all-stop, we can't mark REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN
6259      (explained in remote-notif.c:handle_notification) so
6260      remote_notif_process is not called.  We need find a place where
6261      it is safe to start a 'vNotif' sequence.  It is good to do it
6262      before resuming inferior, because inferior was stopped and no RSP
6263      traffic at that moment.  */
6264   if (!target_is_non_stop_p ())
6265     remote_notif_process (rs->notif_state, &notif_client_stop);
6266
6267   rs->last_resume_exec_dir = ::execution_direction;
6268
6269   /* Prefer vCont, and fallback to s/c/S/C, which use Hc.  */
6270   if (!remote_resume_with_vcont (ptid, step, siggnal))
6271     remote_resume_with_hc (ptid, step, siggnal);
6272
6273   /* We are about to start executing the inferior, let's register it
6274      with the event loop.  NOTE: this is the one place where all the
6275      execution commands end up.  We could alternatively do this in each
6276      of the execution commands in infcmd.c.  */
6277   /* FIXME: ezannoni 1999-09-28: We may need to move this out of here
6278      into infcmd.c in order to allow inferior function calls to work
6279      NOT asynchronously.  */
6280   if (target_can_async_p ())
6281     target_async (1);
6282
6283   /* We've just told the target to resume.  The remote server will
6284      wait for the inferior to stop, and then send a stop reply.  In
6285      the mean time, we can't start another command/query ourselves
6286      because the stub wouldn't be ready to process it.  This applies
6287      only to the base all-stop protocol, however.  In non-stop (which
6288      only supports vCont), the stub replies with an "OK", and is
6289      immediate able to process further serial input.  */
6290   if (!target_is_non_stop_p ())
6291     rs->waiting_for_stop_reply = 1;
6292 }
6293
6294 static int is_pending_fork_parent_thread (struct thread_info *thread);
6295
6296 /* Private per-inferior info for target remote processes.  */
6297
6298 struct remote_inferior : public private_inferior
6299 {
6300   /* Whether we can send a wildcard vCont for this process.  */
6301   bool may_wildcard_vcont = true;
6302 };
6303
6304 /* Get the remote private inferior data associated to INF.  */
6305
6306 static remote_inferior *
6307 get_remote_inferior (inferior *inf)
6308 {
6309   if (inf->priv == NULL)
6310     inf->priv.reset (new remote_inferior);
6311
6312   return static_cast<remote_inferior *> (inf->priv.get ());
6313 }
6314
6315 /* Class used to track the construction of a vCont packet in the
6316    outgoing packet buffer.  This is used to send multiple vCont
6317    packets if we have more actions than would fit a single packet.  */
6318
6319 class vcont_builder
6320 {
6321 public:
6322   explicit vcont_builder (remote_target *remote)
6323     : m_remote (remote)
6324   {
6325     restart ();
6326   }
6327
6328   void flush ();
6329   void push_action (ptid_t ptid, bool step, gdb_signal siggnal);
6330
6331 private:
6332   void restart ();
6333
6334   /* The remote target.  */
6335   remote_target *m_remote;
6336
6337   /* Pointer to the first action.  P points here if no action has been
6338      appended yet.  */
6339   char *m_first_action;
6340
6341   /* Where the next action will be appended.  */
6342   char *m_p;
6343
6344   /* The end of the buffer.  Must never write past this.  */
6345   char *m_endp;
6346 };
6347
6348 /* Prepare the outgoing buffer for a new vCont packet.  */
6349
6350 void
6351 vcont_builder::restart ()
6352 {
6353   struct remote_state *rs = m_remote->get_remote_state ();
6354
6355   m_p = rs->buf;
6356   m_endp = rs->buf + m_remote->get_remote_packet_size ();
6357   m_p += xsnprintf (m_p, m_endp - m_p, "vCont");
6358   m_first_action = m_p;
6359 }
6360
6361 /* If the vCont packet being built has any action, send it to the
6362    remote end.  */
6363
6364 void
6365 vcont_builder::flush ()
6366 {
6367   struct remote_state *rs;
6368
6369   if (m_p == m_first_action)
6370     return;
6371
6372   rs = m_remote->get_remote_state ();
6373   m_remote->putpkt (rs->buf);
6374   m_remote->getpkt (&rs->buf, &rs->buf_size, 0);
6375   if (strcmp (rs->buf, "OK") != 0)
6376     error (_("Unexpected vCont reply in non-stop mode: %s"), rs->buf);
6377 }
6378
6379 /* The largest action is range-stepping, with its two addresses.  This
6380    is more than sufficient.  If a new, bigger action is created, it'll
6381    quickly trigger a failed assertion in append_resumption (and we'll
6382    just bump this).  */
6383 #define MAX_ACTION_SIZE 200
6384
6385 /* Append a new vCont action in the outgoing packet being built.  If
6386    the action doesn't fit the packet along with previous actions, push
6387    what we've got so far to the remote end and start over a new vCont
6388    packet (with the new action).  */
6389
6390 void
6391 vcont_builder::push_action (ptid_t ptid, bool step, gdb_signal siggnal)
6392 {
6393   char buf[MAX_ACTION_SIZE + 1];
6394
6395   char *endp = m_remote->append_resumption (buf, buf + sizeof (buf),
6396                                             ptid, step, siggnal);
6397
6398   /* Check whether this new action would fit in the vCont packet along
6399      with previous actions.  If not, send what we've got so far and
6400      start a new vCont packet.  */
6401   size_t rsize = endp - buf;
6402   if (rsize > m_endp - m_p)
6403     {
6404       flush ();
6405       restart ();
6406
6407       /* Should now fit.  */
6408       gdb_assert (rsize <= m_endp - m_p);
6409     }
6410
6411   memcpy (m_p, buf, rsize);
6412   m_p += rsize;
6413   *m_p = '\0';
6414 }
6415
6416 /* to_commit_resume implementation.  */
6417
6418 void
6419 remote_target::commit_resume ()
6420 {
6421   struct inferior *inf;
6422   struct thread_info *tp;
6423   int any_process_wildcard;
6424   int may_global_wildcard_vcont;
6425
6426   /* If connected in all-stop mode, we'd send the remote resume
6427      request directly from remote_resume.  Likewise if
6428      reverse-debugging, as there are no defined vCont actions for
6429      reverse execution.  */
6430   if (!target_is_non_stop_p () || ::execution_direction == EXEC_REVERSE)
6431     return;
6432
6433   /* Try to send wildcard actions ("vCont;c" or "vCont;c:pPID.-1")
6434      instead of resuming all threads of each process individually.
6435      However, if any thread of a process must remain halted, we can't
6436      send wildcard resumes and must send one action per thread.
6437
6438      Care must be taken to not resume threads/processes the server
6439      side already told us are stopped, but the core doesn't know about
6440      yet, because the events are still in the vStopped notification
6441      queue.  For example:
6442
6443        #1 => vCont s:p1.1;c
6444        #2 <= OK
6445        #3 <= %Stopped T05 p1.1
6446        #4 => vStopped
6447        #5 <= T05 p1.2
6448        #6 => vStopped
6449        #7 <= OK
6450        #8 (infrun handles the stop for p1.1 and continues stepping)
6451        #9 => vCont s:p1.1;c
6452
6453      The last vCont above would resume thread p1.2 by mistake, because
6454      the server has no idea that the event for p1.2 had not been
6455      handled yet.
6456
6457      The server side must similarly ignore resume actions for the
6458      thread that has a pending %Stopped notification (and any other
6459      threads with events pending), until GDB acks the notification
6460      with vStopped.  Otherwise, e.g., the following case is
6461      mishandled:
6462
6463        #1 => g  (or any other packet)
6464        #2 <= [registers]
6465        #3 <= %Stopped T05 p1.2
6466        #4 => vCont s:p1.1;c
6467        #5 <= OK
6468
6469      Above, the server must not resume thread p1.2.  GDB can't know
6470      that p1.2 stopped until it acks the %Stopped notification, and
6471      since from GDB's perspective all threads should be running, it
6472      sends a "c" action.
6473
6474      Finally, special care must also be given to handling fork/vfork
6475      events.  A (v)fork event actually tells us that two processes
6476      stopped -- the parent and the child.  Until we follow the fork,
6477      we must not resume the child.  Therefore, if we have a pending
6478      fork follow, we must not send a global wildcard resume action
6479      (vCont;c).  We can still send process-wide wildcards though.  */
6480
6481   /* Start by assuming a global wildcard (vCont;c) is possible.  */
6482   may_global_wildcard_vcont = 1;
6483
6484   /* And assume every process is individually wildcard-able too.  */
6485   ALL_NON_EXITED_INFERIORS (inf)
6486     {
6487       remote_inferior *priv = get_remote_inferior (inf);
6488
6489       priv->may_wildcard_vcont = true;
6490     }
6491
6492   /* Check for any pending events (not reported or processed yet) and
6493      disable process and global wildcard resumes appropriately.  */
6494   check_pending_events_prevent_wildcard_vcont (&may_global_wildcard_vcont);
6495
6496   ALL_NON_EXITED_THREADS (tp)
6497     {
6498       /* If a thread of a process is not meant to be resumed, then we
6499          can't wildcard that process.  */
6500       if (!tp->executing)
6501         {
6502           get_remote_inferior (tp->inf)->may_wildcard_vcont = false;
6503
6504           /* And if we can't wildcard a process, we can't wildcard
6505              everything either.  */
6506           may_global_wildcard_vcont = 0;
6507           continue;
6508         }
6509
6510       /* If a thread is the parent of an unfollowed fork, then we
6511          can't do a global wildcard, as that would resume the fork
6512          child.  */
6513       if (is_pending_fork_parent_thread (tp))
6514         may_global_wildcard_vcont = 0;
6515     }
6516
6517   /* Now let's build the vCont packet(s).  Actions must be appended
6518      from narrower to wider scopes (thread -> process -> global).  If
6519      we end up with too many actions for a single packet vcont_builder
6520      flushes the current vCont packet to the remote side and starts a
6521      new one.  */
6522   struct vcont_builder vcont_builder (this);
6523
6524   /* Threads first.  */
6525   ALL_NON_EXITED_THREADS (tp)
6526     {
6527       remote_thread_info *remote_thr = get_remote_thread_info (tp);
6528
6529       if (!tp->executing || remote_thr->vcont_resumed)
6530         continue;
6531
6532       gdb_assert (!thread_is_in_step_over_chain (tp));
6533
6534       if (!remote_thr->last_resume_step
6535           && remote_thr->last_resume_sig == GDB_SIGNAL_0
6536           && get_remote_inferior (tp->inf)->may_wildcard_vcont)
6537         {
6538           /* We'll send a wildcard resume instead.  */
6539           remote_thr->vcont_resumed = 1;
6540           continue;
6541         }
6542
6543       vcont_builder.push_action (tp->ptid,
6544                                  remote_thr->last_resume_step,
6545                                  remote_thr->last_resume_sig);
6546       remote_thr->vcont_resumed = 1;
6547     }
6548
6549   /* Now check whether we can send any process-wide wildcard.  This is
6550      to avoid sending a global wildcard in the case nothing is
6551      supposed to be resumed.  */
6552   any_process_wildcard = 0;
6553
6554   ALL_NON_EXITED_INFERIORS (inf)
6555     {
6556       if (get_remote_inferior (inf)->may_wildcard_vcont)
6557         {
6558           any_process_wildcard = 1;
6559           break;
6560         }
6561     }
6562
6563   if (any_process_wildcard)
6564     {
6565       /* If all processes are wildcard-able, then send a single "c"
6566          action, otherwise, send an "all (-1) threads of process"
6567          continue action for each running process, if any.  */
6568       if (may_global_wildcard_vcont)
6569         {
6570           vcont_builder.push_action (minus_one_ptid,
6571                                      false, GDB_SIGNAL_0);
6572         }
6573       else
6574         {
6575           ALL_NON_EXITED_INFERIORS (inf)
6576             {
6577               if (get_remote_inferior (inf)->may_wildcard_vcont)
6578                 {
6579                   vcont_builder.push_action (pid_to_ptid (inf->pid),
6580                                              false, GDB_SIGNAL_0);
6581                 }
6582             }
6583         }
6584     }
6585
6586   vcont_builder.flush ();
6587 }
6588
6589 \f
6590
6591 /* Non-stop version of target_stop.  Uses `vCont;t' to stop a remote
6592    thread, all threads of a remote process, or all threads of all
6593    processes.  */
6594
6595 void
6596 remote_target::remote_stop_ns (ptid_t ptid)
6597 {
6598   struct remote_state *rs = get_remote_state ();
6599   char *p = rs->buf;
6600   char *endp = rs->buf + get_remote_packet_size ();
6601
6602   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
6603     remote_vcont_probe ();
6604
6605   if (!rs->supports_vCont.t)
6606     error (_("Remote server does not support stopping threads"));
6607
6608   if (ptid_equal (ptid, minus_one_ptid)
6609       || (!remote_multi_process_p (rs) && ptid_is_pid (ptid)))
6610     p += xsnprintf (p, endp - p, "vCont;t");
6611   else
6612     {
6613       ptid_t nptid;
6614
6615       p += xsnprintf (p, endp - p, "vCont;t:");
6616
6617       if (ptid_is_pid (ptid))
6618           /* All (-1) threads of process.  */
6619         nptid = ptid_build (ptid_get_pid (ptid), -1, 0);
6620       else
6621         {
6622           /* Small optimization: if we already have a stop reply for
6623              this thread, no use in telling the stub we want this
6624              stopped.  */
6625           if (peek_stop_reply (ptid))
6626             return;
6627
6628           nptid = ptid;
6629         }
6630
6631       write_ptid (p, endp, nptid);
6632     }
6633
6634   /* In non-stop, we get an immediate OK reply.  The stop reply will
6635      come in asynchronously by notification.  */
6636   putpkt (rs->buf);
6637   getpkt (&rs->buf, &rs->buf_size, 0);
6638   if (strcmp (rs->buf, "OK") != 0)
6639     error (_("Stopping %s failed: %s"), target_pid_to_str (ptid), rs->buf);
6640 }
6641
6642 /* All-stop version of target_interrupt.  Sends a break or a ^C to
6643    interrupt the remote target.  It is undefined which thread of which
6644    process reports the interrupt.  */
6645
6646 void
6647 remote_target::remote_interrupt_as ()
6648 {
6649   struct remote_state *rs = get_remote_state ();
6650
6651   rs->ctrlc_pending_p = 1;
6652
6653   /* If the inferior is stopped already, but the core didn't know
6654      about it yet, just ignore the request.  The cached wait status
6655      will be collected in remote_wait.  */
6656   if (rs->cached_wait_status)
6657     return;
6658
6659   /* Send interrupt_sequence to remote target.  */
6660   send_interrupt_sequence ();
6661 }
6662
6663 /* Non-stop version of target_interrupt.  Uses `vCtrlC' to interrupt
6664    the remote target.  It is undefined which thread of which process
6665    reports the interrupt.  Throws an error if the packet is not
6666    supported by the server.  */
6667
6668 void
6669 remote_target::remote_interrupt_ns ()
6670 {
6671   struct remote_state *rs = get_remote_state ();
6672   char *p = rs->buf;
6673   char *endp = rs->buf + get_remote_packet_size ();
6674
6675   xsnprintf (p, endp - p, "vCtrlC");
6676
6677   /* In non-stop, we get an immediate OK reply.  The stop reply will
6678      come in asynchronously by notification.  */
6679   putpkt (rs->buf);
6680   getpkt (&rs->buf, &rs->buf_size, 0);
6681
6682   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vCtrlC]))
6683     {
6684     case PACKET_OK:
6685       break;
6686     case PACKET_UNKNOWN:
6687       error (_("No support for interrupting the remote target."));
6688     case PACKET_ERROR:
6689       error (_("Interrupting target failed: %s"), rs->buf);
6690     }
6691 }
6692
6693 /* Implement the to_stop function for the remote targets.  */
6694
6695 void
6696 remote_target::stop (ptid_t ptid)
6697 {
6698   if (remote_debug)
6699     fprintf_unfiltered (gdb_stdlog, "remote_stop called\n");
6700
6701   if (target_is_non_stop_p ())
6702     remote_stop_ns (ptid);
6703   else
6704     {
6705       /* We don't currently have a way to transparently pause the
6706          remote target in all-stop mode.  Interrupt it instead.  */
6707       remote_interrupt_as ();
6708     }
6709 }
6710
6711 /* Implement the to_interrupt function for the remote targets.  */
6712
6713 void
6714 remote_target::interrupt ()
6715 {
6716   if (remote_debug)
6717     fprintf_unfiltered (gdb_stdlog, "remote_interrupt called\n");
6718
6719   if (target_is_non_stop_p ())
6720     remote_interrupt_ns ();
6721   else
6722     remote_interrupt_as ();
6723 }
6724
6725 /* Implement the to_pass_ctrlc function for the remote targets.  */
6726
6727 void
6728 remote_target::pass_ctrlc ()
6729 {
6730   struct remote_state *rs = get_remote_state ();
6731
6732   if (remote_debug)
6733     fprintf_unfiltered (gdb_stdlog, "remote_pass_ctrlc called\n");
6734
6735   /* If we're starting up, we're not fully synced yet.  Quit
6736      immediately.  */
6737   if (rs->starting_up)
6738     quit ();
6739   /* If ^C has already been sent once, offer to disconnect.  */
6740   else if (rs->ctrlc_pending_p)
6741     interrupt_query ();
6742   else
6743     target_interrupt ();
6744 }
6745
6746 /* Ask the user what to do when an interrupt is received.  */
6747
6748 void
6749 remote_target::interrupt_query ()
6750 {
6751   struct remote_state *rs = get_remote_state ();
6752
6753   if (rs->waiting_for_stop_reply && rs->ctrlc_pending_p)
6754     {
6755       if (query (_("The target is not responding to interrupt requests.\n"
6756                    "Stop debugging it? ")))
6757         {
6758           remote_unpush_target ();
6759           throw_error (TARGET_CLOSE_ERROR, _("Disconnected from target."));
6760         }
6761     }
6762   else
6763     {
6764       if (query (_("Interrupted while waiting for the program.\n"
6765                    "Give up waiting? ")))
6766         quit ();
6767     }
6768 }
6769
6770 /* Enable/disable target terminal ownership.  Most targets can use
6771    terminal groups to control terminal ownership.  Remote targets are
6772    different in that explicit transfer of ownership to/from GDB/target
6773    is required.  */
6774
6775 void
6776 remote_target::terminal_inferior ()
6777 {
6778   /* NOTE: At this point we could also register our selves as the
6779      recipient of all input.  Any characters typed could then be
6780      passed on down to the target.  */
6781 }
6782
6783 void
6784 remote_target::terminal_ours ()
6785 {
6786 }
6787
6788 static void
6789 remote_console_output (char *msg)
6790 {
6791   char *p;
6792
6793   for (p = msg; p[0] && p[1]; p += 2)
6794     {
6795       char tb[2];
6796       char c = fromhex (p[0]) * 16 + fromhex (p[1]);
6797
6798       tb[0] = c;
6799       tb[1] = 0;
6800       fputs_unfiltered (tb, gdb_stdtarg);
6801     }
6802   gdb_flush (gdb_stdtarg);
6803 }
6804
6805 DEF_VEC_O(cached_reg_t);
6806
6807 typedef struct stop_reply
6808 {
6809   struct notif_event base;
6810
6811   /* The identifier of the thread about this event  */
6812   ptid_t ptid;
6813
6814   /* The remote state this event is associated with.  When the remote
6815      connection, represented by a remote_state object, is closed,
6816      all the associated stop_reply events should be released.  */
6817   struct remote_state *rs;
6818
6819   struct target_waitstatus ws;
6820
6821   /* The architecture associated with the expedited registers.  */
6822   gdbarch *arch;
6823
6824   /* Expedited registers.  This makes remote debugging a bit more
6825      efficient for those targets that provide critical registers as
6826      part of their normal status mechanism (as another roundtrip to
6827      fetch them is avoided).  */
6828   VEC(cached_reg_t) *regcache;
6829
6830   enum target_stop_reason stop_reason;
6831
6832   CORE_ADDR watch_data_address;
6833
6834   int core;
6835 } *stop_reply_p;
6836
6837 static void
6838 stop_reply_xfree (struct stop_reply *r)
6839 {
6840   notif_event_xfree ((struct notif_event *) r);
6841 }
6842
6843 /* Return the length of the stop reply queue.  */
6844
6845 int
6846 remote_target::stop_reply_queue_length ()
6847 {
6848   remote_state *rs = get_remote_state ();
6849   return QUEUE_length (stop_reply_p, rs->stop_reply_queue);
6850 }
6851
6852 void
6853 remote_notif_stop_parse (remote_target *remote,
6854                          struct notif_client *self, char *buf,
6855                          struct notif_event *event)
6856 {
6857   remote->remote_parse_stop_reply (buf, (struct stop_reply *) event);
6858 }
6859
6860 static void
6861 remote_notif_stop_ack (remote_target *remote,
6862                        struct notif_client *self, char *buf,
6863                        struct notif_event *event)
6864 {
6865   struct stop_reply *stop_reply = (struct stop_reply *) event;
6866
6867   /* acknowledge */
6868   putpkt (remote, self->ack_command);
6869
6870   if (stop_reply->ws.kind == TARGET_WAITKIND_IGNORE)
6871     {
6872       /* We got an unknown stop reply.  */
6873       error (_("Unknown stop reply"));
6874     }
6875
6876   remote->push_stop_reply (stop_reply);
6877 }
6878
6879 static int
6880 remote_notif_stop_can_get_pending_events (remote_target *remote,
6881                                           struct notif_client *self)
6882 {
6883   /* We can't get pending events in remote_notif_process for
6884      notification stop, and we have to do this in remote_wait_ns
6885      instead.  If we fetch all queued events from stub, remote stub
6886      may exit and we have no chance to process them back in
6887      remote_wait_ns.  */
6888   remote_state *rs = remote->get_remote_state ();
6889   mark_async_event_handler (rs->remote_async_inferior_event_token);
6890   return 0;
6891 }
6892
6893 static void
6894 stop_reply_dtr (struct notif_event *event)
6895 {
6896   struct stop_reply *r = (struct stop_reply *) event;
6897   cached_reg_t *reg;
6898   int ix;
6899
6900   for (ix = 0;
6901        VEC_iterate (cached_reg_t, r->regcache, ix, reg);
6902        ix++)
6903     xfree (reg->data);
6904
6905   VEC_free (cached_reg_t, r->regcache);
6906 }
6907
6908 static struct notif_event *
6909 remote_notif_stop_alloc_reply (void)
6910 {
6911   /* We cast to a pointer to the "base class".  */
6912   struct notif_event *r = (struct notif_event *) XNEW (struct stop_reply);
6913
6914   r->dtr = stop_reply_dtr;
6915
6916   return r;
6917 }
6918
6919 /* A client of notification Stop.  */
6920
6921 struct notif_client notif_client_stop =
6922 {
6923   "Stop",
6924   "vStopped",
6925   remote_notif_stop_parse,
6926   remote_notif_stop_ack,
6927   remote_notif_stop_can_get_pending_events,
6928   remote_notif_stop_alloc_reply,
6929   REMOTE_NOTIF_STOP,
6930 };
6931
6932 /* A parameter to pass data in and out.  */
6933
6934 struct queue_iter_param
6935 {
6936   remote_target *remote;
6937   void *input;
6938   struct stop_reply *output;
6939 };
6940
6941 /* Determine if THREAD_PTID is a pending fork parent thread.  ARG contains
6942    the pid of the process that owns the threads we want to check, or
6943    -1 if we want to check all threads.  */
6944
6945 static int
6946 is_pending_fork_parent (struct target_waitstatus *ws, int event_pid,
6947                         ptid_t thread_ptid)
6948 {
6949   if (ws->kind == TARGET_WAITKIND_FORKED
6950       || ws->kind == TARGET_WAITKIND_VFORKED)
6951     {
6952       if (event_pid == -1 || event_pid == ptid_get_pid (thread_ptid))
6953         return 1;
6954     }
6955
6956   return 0;
6957 }
6958
6959 /* Return the thread's pending status used to determine whether the
6960    thread is a fork parent stopped at a fork event.  */
6961
6962 static struct target_waitstatus *
6963 thread_pending_fork_status (struct thread_info *thread)
6964 {
6965   if (thread->suspend.waitstatus_pending_p)
6966     return &thread->suspend.waitstatus;
6967   else
6968     return &thread->pending_follow;
6969 }
6970
6971 /* Determine if THREAD is a pending fork parent thread.  */
6972
6973 static int
6974 is_pending_fork_parent_thread (struct thread_info *thread)
6975 {
6976   struct target_waitstatus *ws = thread_pending_fork_status (thread);
6977   int pid = -1;
6978
6979   return is_pending_fork_parent (ws, pid, thread->ptid);
6980 }
6981
6982 /* Check whether EVENT is a fork event, and if it is, remove the
6983    fork child from the context list passed in DATA.  */
6984
6985 static int
6986 remove_child_of_pending_fork (QUEUE (stop_reply_p) *q,
6987                               QUEUE_ITER (stop_reply_p) *iter,
6988                               stop_reply_p event,
6989                               void *data)
6990 {
6991   struct queue_iter_param *param = (struct queue_iter_param *) data;
6992   struct threads_listing_context *context
6993     = (struct threads_listing_context *) param->input;
6994
6995   if (event->ws.kind == TARGET_WAITKIND_FORKED
6996       || event->ws.kind == TARGET_WAITKIND_VFORKED
6997       || event->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
6998     context->remove_thread (event->ws.value.related_pid);
6999
7000   return 1;
7001 }
7002
7003 /* If CONTEXT contains any fork child threads that have not been
7004    reported yet, remove them from the CONTEXT list.  If such a
7005    thread exists it is because we are stopped at a fork catchpoint
7006    and have not yet called follow_fork, which will set up the
7007    host-side data structures for the new process.  */
7008
7009 void
7010 remote_target::remove_new_fork_children (threads_listing_context *context)
7011 {
7012   struct thread_info * thread;
7013   int pid = -1;
7014   struct notif_client *notif = &notif_client_stop;
7015   struct queue_iter_param param;
7016
7017   /* For any threads stopped at a fork event, remove the corresponding
7018      fork child threads from the CONTEXT list.  */
7019   ALL_NON_EXITED_THREADS (thread)
7020     {
7021       struct target_waitstatus *ws = thread_pending_fork_status (thread);
7022
7023       if (is_pending_fork_parent (ws, pid, thread->ptid))
7024         context->remove_thread (ws->value.related_pid);
7025     }
7026
7027   /* Check for any pending fork events (not reported or processed yet)
7028      in process PID and remove those fork child threads from the
7029      CONTEXT list as well.  */
7030   remote_notif_get_pending_events (notif);
7031   param.remote = this;
7032   param.input = context;
7033   param.output = NULL;
7034   QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
7035                  remove_child_of_pending_fork, &param);
7036 }
7037
7038 /* Callback data for
7039    check_pending_event_prevents_wildcard_vcont_callback.  */
7040 struct check_pending_event_prevents_wildcard_vcont_callback_data
7041 {
7042   /* The remote target.  */
7043   remote_target *remote;
7044
7045   /* Whether we can do a global wildcard (vCont;c)  */
7046   int *may_global_wildcard_vcont;
7047 };
7048
7049 /* Check whether EVENT would prevent a global or process wildcard
7050    vCont action.  */
7051
7052 static int
7053 check_pending_event_prevents_wildcard_vcont_callback
7054   (QUEUE (stop_reply_p) *q,
7055    QUEUE_ITER (stop_reply_p) *iter,
7056    stop_reply_p event,
7057    void *data)
7058 {
7059   struct inferior *inf;
7060   auto *cb_data = (check_pending_event_prevents_wildcard_vcont_callback_data *) data;
7061
7062   if (event->ws.kind == TARGET_WAITKIND_NO_RESUMED
7063       || event->ws.kind == TARGET_WAITKIND_NO_HISTORY)
7064     return 1;
7065
7066   if (event->ws.kind == TARGET_WAITKIND_FORKED
7067       || event->ws.kind == TARGET_WAITKIND_VFORKED)
7068     *cb_data->may_global_wildcard_vcont = 0;
7069
7070   inf = find_inferior_ptid (event->ptid);
7071
7072   /* This may be the first time we heard about this process.
7073      Regardless, we must not do a global wildcard resume, otherwise
7074      we'd resume this process too.  */
7075   *cb_data->may_global_wildcard_vcont = 0;
7076   if (inf != NULL)
7077     get_remote_inferior (inf)->may_wildcard_vcont = false;
7078
7079   return 1;
7080 }
7081
7082 /* Check whether any event pending in the vStopped queue would prevent
7083    a global or process wildcard vCont action.  Clear
7084    *may_global_wildcard if we can't do a global wildcard (vCont;c),
7085    and clear the event inferior's may_wildcard_vcont flag if we can't
7086    do a process-wide wildcard resume (vCont;c:pPID.-1).  */
7087
7088 void
7089 remote_target::check_pending_events_prevent_wildcard_vcont
7090   (int *may_global_wildcard)
7091 {
7092   struct notif_client *notif = &notif_client_stop;
7093   check_pending_event_prevents_wildcard_vcont_callback_data cb_data
7094     {this, may_global_wildcard};
7095
7096   remote_notif_get_pending_events (notif);
7097   QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
7098                  check_pending_event_prevents_wildcard_vcont_callback,
7099                  &cb_data);
7100 }
7101
7102 /* Remove stop replies in the queue if its pid is equal to the given
7103    inferior's pid.  */
7104
7105 static int
7106 remove_stop_reply_for_inferior (QUEUE (stop_reply_p) *q,
7107                                 QUEUE_ITER (stop_reply_p) *iter,
7108                                 stop_reply_p event,
7109                                 void *data)
7110 {
7111   struct queue_iter_param *param = (struct queue_iter_param *) data;
7112   struct inferior *inf = (struct inferior *) param->input;
7113
7114   if (ptid_get_pid (event->ptid) == inf->pid)
7115     {
7116       stop_reply_xfree (event);
7117       QUEUE_remove_elem (stop_reply_p, q, iter);
7118     }
7119
7120   return 1;
7121 }
7122
7123 /* Discard all pending stop replies of inferior INF.  */
7124
7125 void
7126 remote_target::discard_pending_stop_replies (struct inferior *inf)
7127 {
7128   struct queue_iter_param param;
7129   struct stop_reply *reply;
7130   struct remote_state *rs = get_remote_state ();
7131   struct remote_notif_state *rns = rs->notif_state;
7132
7133   /* This function can be notified when an inferior exists.  When the
7134      target is not remote, the notification state is NULL.  */
7135   if (rs->remote_desc == NULL)
7136     return;
7137
7138   reply = (struct stop_reply *) rns->pending_event[notif_client_stop.id];
7139
7140   /* Discard the in-flight notification.  */
7141   if (reply != NULL && ptid_get_pid (reply->ptid) == inf->pid)
7142     {
7143       stop_reply_xfree (reply);
7144       rns->pending_event[notif_client_stop.id] = NULL;
7145     }
7146
7147   param.remote = this;
7148   param.input = inf;
7149   param.output = NULL;
7150   /* Discard the stop replies we have already pulled with
7151      vStopped.  */
7152   QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
7153                  remove_stop_reply_for_inferior, &param);
7154 }
7155
7156 /* If its remote state is equal to the given remote state,
7157    remove EVENT from the stop reply queue.  */
7158
7159 static int
7160 remove_stop_reply_of_remote_state (QUEUE (stop_reply_p) *q,
7161                                    QUEUE_ITER (stop_reply_p) *iter,
7162                                    stop_reply_p event,
7163                                    void *data)
7164 {
7165   struct queue_iter_param *param = (struct queue_iter_param *) data;
7166   struct remote_state *rs = (struct remote_state *) param->input;
7167
7168   if (event->rs == rs)
7169     {
7170       stop_reply_xfree (event);
7171       QUEUE_remove_elem (stop_reply_p, q, iter);
7172     }
7173
7174   return 1;
7175 }
7176
7177 /* Discard the stop replies for RS in stop_reply_queue.  */
7178
7179 void
7180 remote_target::discard_pending_stop_replies_in_queue ()
7181 {
7182   remote_state *rs = get_remote_state ();
7183   struct queue_iter_param param;
7184
7185   param.remote = this;
7186   param.input = rs;
7187   param.output = NULL;
7188   /* Discard the stop replies we have already pulled with
7189      vStopped.  */
7190   QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
7191                  remove_stop_reply_of_remote_state, &param);
7192 }
7193
7194 /* A parameter to pass data in and out.  */
7195
7196 static int
7197 remote_notif_remove_once_on_match (QUEUE (stop_reply_p) *q,
7198                                    QUEUE_ITER (stop_reply_p) *iter,
7199                                    stop_reply_p event,
7200                                    void *data)
7201 {
7202   struct queue_iter_param *param = (struct queue_iter_param *) data;
7203   ptid_t *ptid = (ptid_t *) param->input;
7204
7205   if (ptid_match (event->ptid, *ptid))
7206     {
7207       param->output = event;
7208       QUEUE_remove_elem (stop_reply_p, q, iter);
7209       return 0;
7210     }
7211
7212   return 1;
7213 }
7214
7215 /* Remove the first reply in 'stop_reply_queue' which matches
7216    PTID.  */
7217
7218 struct stop_reply *
7219 remote_target::remote_notif_remove_queued_reply (ptid_t ptid)
7220 {
7221   struct queue_iter_param param;
7222
7223   param.remote = this;
7224   param.input = &ptid;
7225   param.output = NULL;
7226
7227   QUEUE_iterate (stop_reply_p, get_remote_state ()->stop_reply_queue,
7228                  remote_notif_remove_once_on_match, &param);
7229   if (notif_debug)
7230     fprintf_unfiltered (gdb_stdlog,
7231                         "notif: discard queued event: 'Stop' in %s\n",
7232                         target_pid_to_str (ptid));
7233
7234   return param.output;
7235 }
7236
7237 /* Look for a queued stop reply belonging to PTID.  If one is found,
7238    remove it from the queue, and return it.  Returns NULL if none is
7239    found.  If there are still queued events left to process, tell the
7240    event loop to get back to target_wait soon.  */
7241
7242 struct stop_reply *
7243 remote_target::queued_stop_reply (ptid_t ptid)
7244 {
7245   struct stop_reply *r = remote_notif_remove_queued_reply (ptid);
7246
7247   if (!QUEUE_is_empty (stop_reply_p, get_remote_state ()->stop_reply_queue))
7248     {
7249       remote_state *rs = get_remote_state ();
7250       /* There's still at least an event left.  */
7251       mark_async_event_handler (rs->remote_async_inferior_event_token);
7252     }
7253
7254   return r;
7255 }
7256
7257 /* Push a fully parsed stop reply in the stop reply queue.  Since we
7258    know that we now have at least one queued event left to pass to the
7259    core side, tell the event loop to get back to target_wait soon.  */
7260
7261 void
7262 remote_target::push_stop_reply (struct stop_reply *new_event)
7263 {
7264   remote_state *rs = get_remote_state ();
7265   QUEUE_enque (stop_reply_p, rs->stop_reply_queue, new_event);
7266
7267   if (notif_debug)
7268     fprintf_unfiltered (gdb_stdlog,
7269                         "notif: push 'Stop' %s to queue %d\n",
7270                         target_pid_to_str (new_event->ptid),
7271                         QUEUE_length (stop_reply_p,
7272                                       rs->stop_reply_queue));
7273
7274   mark_async_event_handler (rs->remote_async_inferior_event_token);
7275 }
7276
7277 static int
7278 stop_reply_match_ptid_and_ws (QUEUE (stop_reply_p) *q,
7279                               QUEUE_ITER (stop_reply_p) *iter,
7280                               struct stop_reply *event,
7281                               void *data)
7282 {
7283   ptid_t *ptid = (ptid_t *) data;
7284
7285   return !(ptid_equal (*ptid, event->ptid)
7286            && event->ws.kind == TARGET_WAITKIND_STOPPED);
7287 }
7288
7289 /* Returns true if we have a stop reply for PTID.  */
7290
7291 int
7292 remote_target::peek_stop_reply (ptid_t ptid)
7293 {
7294   remote_state *rs = get_remote_state ();
7295   return !QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
7296                          stop_reply_match_ptid_and_ws, &ptid);
7297 }
7298
7299 /* Helper for remote_parse_stop_reply.  Return nonzero if the substring
7300    starting with P and ending with PEND matches PREFIX.  */
7301
7302 static int
7303 strprefix (const char *p, const char *pend, const char *prefix)
7304 {
7305   for ( ; p < pend; p++, prefix++)
7306     if (*p != *prefix)
7307       return 0;
7308   return *prefix == '\0';
7309 }
7310
7311 /* Parse the stop reply in BUF.  Either the function succeeds, and the
7312    result is stored in EVENT, or throws an error.  */
7313
7314 void
7315 remote_target::remote_parse_stop_reply (char *buf, stop_reply *event)
7316 {
7317   remote_arch_state *rsa = NULL;
7318   ULONGEST addr;
7319   const char *p;
7320   int skipregs = 0;
7321
7322   event->ptid = null_ptid;
7323   event->rs = get_remote_state ();
7324   event->ws.kind = TARGET_WAITKIND_IGNORE;
7325   event->ws.value.integer = 0;
7326   event->stop_reason = TARGET_STOPPED_BY_NO_REASON;
7327   event->regcache = NULL;
7328   event->core = -1;
7329
7330   switch (buf[0])
7331     {
7332     case 'T':           /* Status with PC, SP, FP, ...  */
7333       /* Expedited reply, containing Signal, {regno, reg} repeat.  */
7334       /*  format is:  'Tssn...:r...;n...:r...;n...:r...;#cc', where
7335             ss = signal number
7336             n... = register number
7337             r... = register contents
7338       */
7339
7340       p = &buf[3];      /* after Txx */
7341       while (*p)
7342         {
7343           const char *p1;
7344           int fieldsize;
7345
7346           p1 = strchr (p, ':');
7347           if (p1 == NULL)
7348             error (_("Malformed packet(a) (missing colon): %s\n\
7349 Packet: '%s'\n"),
7350                    p, buf);
7351           if (p == p1)
7352             error (_("Malformed packet(a) (missing register number): %s\n\
7353 Packet: '%s'\n"),
7354                    p, buf);
7355
7356           /* Some "registers" are actually extended stop information.
7357              Note if you're adding a new entry here: GDB 7.9 and
7358              earlier assume that all register "numbers" that start
7359              with an hex digit are real register numbers.  Make sure
7360              the server only sends such a packet if it knows the
7361              client understands it.  */
7362
7363           if (strprefix (p, p1, "thread"))
7364             event->ptid = read_ptid (++p1, &p);
7365           else if (strprefix (p, p1, "syscall_entry"))
7366             {
7367               ULONGEST sysno;
7368
7369               event->ws.kind = TARGET_WAITKIND_SYSCALL_ENTRY;
7370               p = unpack_varlen_hex (++p1, &sysno);
7371               event->ws.value.syscall_number = (int) sysno;
7372             }
7373           else if (strprefix (p, p1, "syscall_return"))
7374             {
7375               ULONGEST sysno;
7376
7377               event->ws.kind = TARGET_WAITKIND_SYSCALL_RETURN;
7378               p = unpack_varlen_hex (++p1, &sysno);
7379               event->ws.value.syscall_number = (int) sysno;
7380             }
7381           else if (strprefix (p, p1, "watch")
7382                    || strprefix (p, p1, "rwatch")
7383                    || strprefix (p, p1, "awatch"))
7384             {
7385               event->stop_reason = TARGET_STOPPED_BY_WATCHPOINT;
7386               p = unpack_varlen_hex (++p1, &addr);
7387               event->watch_data_address = (CORE_ADDR) addr;
7388             }
7389           else if (strprefix (p, p1, "swbreak"))
7390             {
7391               event->stop_reason = TARGET_STOPPED_BY_SW_BREAKPOINT;
7392
7393               /* Make sure the stub doesn't forget to indicate support
7394                  with qSupported.  */
7395               if (packet_support (PACKET_swbreak_feature) != PACKET_ENABLE)
7396                 error (_("Unexpected swbreak stop reason"));
7397
7398               /* The value part is documented as "must be empty",
7399                  though we ignore it, in case we ever decide to make
7400                  use of it in a backward compatible way.  */
7401               p = strchrnul (p1 + 1, ';');
7402             }
7403           else if (strprefix (p, p1, "hwbreak"))
7404             {
7405               event->stop_reason = TARGET_STOPPED_BY_HW_BREAKPOINT;
7406
7407               /* Make sure the stub doesn't forget to indicate support
7408                  with qSupported.  */
7409               if (packet_support (PACKET_hwbreak_feature) != PACKET_ENABLE)
7410                 error (_("Unexpected hwbreak stop reason"));
7411
7412               /* See above.  */
7413               p = strchrnul (p1 + 1, ';');
7414             }
7415           else if (strprefix (p, p1, "library"))
7416             {
7417               event->ws.kind = TARGET_WAITKIND_LOADED;
7418               p = strchrnul (p1 + 1, ';');
7419             }
7420           else if (strprefix (p, p1, "replaylog"))
7421             {
7422               event->ws.kind = TARGET_WAITKIND_NO_HISTORY;
7423               /* p1 will indicate "begin" or "end", but it makes
7424                  no difference for now, so ignore it.  */
7425               p = strchrnul (p1 + 1, ';');
7426             }
7427           else if (strprefix (p, p1, "core"))
7428             {
7429               ULONGEST c;
7430
7431               p = unpack_varlen_hex (++p1, &c);
7432               event->core = c;
7433             }
7434           else if (strprefix (p, p1, "fork"))
7435             {
7436               event->ws.value.related_pid = read_ptid (++p1, &p);
7437               event->ws.kind = TARGET_WAITKIND_FORKED;
7438             }
7439           else if (strprefix (p, p1, "vfork"))
7440             {
7441               event->ws.value.related_pid = read_ptid (++p1, &p);
7442               event->ws.kind = TARGET_WAITKIND_VFORKED;
7443             }
7444           else if (strprefix (p, p1, "vforkdone"))
7445             {
7446               event->ws.kind = TARGET_WAITKIND_VFORK_DONE;
7447               p = strchrnul (p1 + 1, ';');
7448             }
7449           else if (strprefix (p, p1, "exec"))
7450             {
7451               ULONGEST ignored;
7452               char pathname[PATH_MAX];
7453               int pathlen;
7454
7455               /* Determine the length of the execd pathname.  */
7456               p = unpack_varlen_hex (++p1, &ignored);
7457               pathlen = (p - p1) / 2;
7458
7459               /* Save the pathname for event reporting and for
7460                  the next run command.  */
7461               hex2bin (p1, (gdb_byte *) pathname, pathlen);
7462               pathname[pathlen] = '\0';
7463
7464               /* This is freed during event handling.  */
7465               event->ws.value.execd_pathname = xstrdup (pathname);
7466               event->ws.kind = TARGET_WAITKIND_EXECD;
7467
7468               /* Skip the registers included in this packet, since
7469                  they may be for an architecture different from the
7470                  one used by the original program.  */
7471               skipregs = 1;
7472             }
7473           else if (strprefix (p, p1, "create"))
7474             {
7475               event->ws.kind = TARGET_WAITKIND_THREAD_CREATED;
7476               p = strchrnul (p1 + 1, ';');
7477             }
7478           else
7479             {
7480               ULONGEST pnum;
7481               const char *p_temp;
7482
7483               if (skipregs)
7484                 {
7485                   p = strchrnul (p1 + 1, ';');
7486                   p++;
7487                   continue;
7488                 }
7489
7490               /* Maybe a real ``P'' register number.  */
7491               p_temp = unpack_varlen_hex (p, &pnum);
7492               /* If the first invalid character is the colon, we got a
7493                  register number.  Otherwise, it's an unknown stop
7494                  reason.  */
7495               if (p_temp == p1)
7496                 {
7497                   /* If we haven't parsed the event's thread yet, find
7498                      it now, in order to find the architecture of the
7499                      reported expedited registers.  */
7500                   if (event->ptid == null_ptid)
7501                     {
7502                       const char *thr = strstr (p1 + 1, ";thread:");
7503                       if (thr != NULL)
7504                         event->ptid = read_ptid (thr + strlen (";thread:"),
7505                                                  NULL);
7506                       else
7507                         {
7508                           /* Either the current thread hasn't changed,
7509                              or the inferior is not multi-threaded.
7510                              The event must be for the thread we last
7511                              set as (or learned as being) current.  */
7512                           event->ptid = event->rs->general_thread;
7513                         }
7514                     }
7515
7516                   if (rsa == NULL)
7517                     {
7518                       inferior *inf = (event->ptid == null_ptid
7519                                        ? NULL
7520                                        : find_inferior_ptid (event->ptid));
7521                       /* If this is the first time we learn anything
7522                          about this process, skip the registers
7523                          included in this packet, since we don't yet
7524                          know which architecture to use to parse them.
7525                          We'll determine the architecture later when
7526                          we process the stop reply and retrieve the
7527                          target description, via
7528                          remote_notice_new_inferior ->
7529                          post_create_inferior.  */
7530                       if (inf == NULL)
7531                         {
7532                           p = strchrnul (p1 + 1, ';');
7533                           p++;
7534                           continue;
7535                         }
7536
7537                       event->arch = inf->gdbarch;
7538                       rsa = event->rs->get_remote_arch_state (event->arch);
7539                     }
7540
7541                   packet_reg *reg
7542                     = packet_reg_from_pnum (event->arch, rsa, pnum);
7543                   cached_reg_t cached_reg;
7544
7545                   if (reg == NULL)
7546                     error (_("Remote sent bad register number %s: %s\n\
7547 Packet: '%s'\n"),
7548                            hex_string (pnum), p, buf);
7549
7550                   cached_reg.num = reg->regnum;
7551                   cached_reg.data = (gdb_byte *)
7552                     xmalloc (register_size (event->arch, reg->regnum));
7553
7554                   p = p1 + 1;
7555                   fieldsize = hex2bin (p, cached_reg.data,
7556                                        register_size (event->arch, reg->regnum));
7557                   p += 2 * fieldsize;
7558                   if (fieldsize < register_size (event->arch, reg->regnum))
7559                     warning (_("Remote reply is too short: %s"), buf);
7560
7561                   VEC_safe_push (cached_reg_t, event->regcache, &cached_reg);
7562                 }
7563               else
7564                 {
7565                   /* Not a number.  Silently skip unknown optional
7566                      info.  */
7567                   p = strchrnul (p1 + 1, ';');
7568                 }
7569             }
7570
7571           if (*p != ';')
7572             error (_("Remote register badly formatted: %s\nhere: %s"),
7573                    buf, p);
7574           ++p;
7575         }
7576
7577       if (event->ws.kind != TARGET_WAITKIND_IGNORE)
7578         break;
7579
7580       /* fall through */
7581     case 'S':           /* Old style status, just signal only.  */
7582       {
7583         int sig;
7584
7585         event->ws.kind = TARGET_WAITKIND_STOPPED;
7586         sig = (fromhex (buf[1]) << 4) + fromhex (buf[2]);
7587         if (GDB_SIGNAL_FIRST <= sig && sig < GDB_SIGNAL_LAST)
7588           event->ws.value.sig = (enum gdb_signal) sig;
7589         else
7590           event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7591       }
7592       break;
7593     case 'w':           /* Thread exited.  */
7594       {
7595         const char *p;
7596         ULONGEST value;
7597
7598         event->ws.kind = TARGET_WAITKIND_THREAD_EXITED;
7599         p = unpack_varlen_hex (&buf[1], &value);
7600         event->ws.value.integer = value;
7601         if (*p != ';')
7602           error (_("stop reply packet badly formatted: %s"), buf);
7603         event->ptid = read_ptid (++p, NULL);
7604         break;
7605       }
7606     case 'W':           /* Target exited.  */
7607     case 'X':
7608       {
7609         const char *p;
7610         int pid;
7611         ULONGEST value;
7612
7613         /* GDB used to accept only 2 hex chars here.  Stubs should
7614            only send more if they detect GDB supports multi-process
7615            support.  */
7616         p = unpack_varlen_hex (&buf[1], &value);
7617
7618         if (buf[0] == 'W')
7619           {
7620             /* The remote process exited.  */
7621             event->ws.kind = TARGET_WAITKIND_EXITED;
7622             event->ws.value.integer = value;
7623           }
7624         else
7625           {
7626             /* The remote process exited with a signal.  */
7627             event->ws.kind = TARGET_WAITKIND_SIGNALLED;
7628             if (GDB_SIGNAL_FIRST <= value && value < GDB_SIGNAL_LAST)
7629               event->ws.value.sig = (enum gdb_signal) value;
7630             else
7631               event->ws.value.sig = GDB_SIGNAL_UNKNOWN;
7632           }
7633
7634         /* If no process is specified, assume inferior_ptid.  */
7635         pid = ptid_get_pid (inferior_ptid);
7636         if (*p == '\0')
7637           ;
7638         else if (*p == ';')
7639           {
7640             p++;
7641
7642             if (*p == '\0')
7643               ;
7644             else if (startswith (p, "process:"))
7645               {
7646                 ULONGEST upid;
7647
7648                 p += sizeof ("process:") - 1;
7649                 unpack_varlen_hex (p, &upid);
7650                 pid = upid;
7651               }
7652             else
7653               error (_("unknown stop reply packet: %s"), buf);
7654           }
7655         else
7656           error (_("unknown stop reply packet: %s"), buf);
7657         event->ptid = pid_to_ptid (pid);
7658       }
7659       break;
7660     case 'N':
7661       event->ws.kind = TARGET_WAITKIND_NO_RESUMED;
7662       event->ptid = minus_one_ptid;
7663       break;
7664     }
7665
7666   if (target_is_non_stop_p () && ptid_equal (event->ptid, null_ptid))
7667     error (_("No process or thread specified in stop reply: %s"), buf);
7668 }
7669
7670 /* When the stub wants to tell GDB about a new notification reply, it
7671    sends a notification (%Stop, for example).  Those can come it at
7672    any time, hence, we have to make sure that any pending
7673    putpkt/getpkt sequence we're making is finished, before querying
7674    the stub for more events with the corresponding ack command
7675    (vStopped, for example).  E.g., if we started a vStopped sequence
7676    immediately upon receiving the notification, something like this
7677    could happen:
7678
7679     1.1) --> Hg 1
7680     1.2) <-- OK
7681     1.3) --> g
7682     1.4) <-- %Stop
7683     1.5) --> vStopped
7684     1.6) <-- (registers reply to step #1.3)
7685
7686    Obviously, the reply in step #1.6 would be unexpected to a vStopped
7687    query.
7688
7689    To solve this, whenever we parse a %Stop notification successfully,
7690    we mark the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN, and carry on
7691    doing whatever we were doing:
7692
7693     2.1) --> Hg 1
7694     2.2) <-- OK
7695     2.3) --> g
7696     2.4) <-- %Stop
7697       <GDB marks the REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN>
7698     2.5) <-- (registers reply to step #2.3)
7699
7700    Eventualy after step #2.5, we return to the event loop, which
7701    notices there's an event on the
7702    REMOTE_ASYNC_GET_PENDING_EVENTS_TOKEN event and calls the
7703    associated callback --- the function below.  At this point, we're
7704    always safe to start a vStopped sequence. :
7705
7706     2.6) --> vStopped
7707     2.7) <-- T05 thread:2
7708     2.8) --> vStopped
7709     2.9) --> OK
7710 */
7711
7712 void
7713 remote_target::remote_notif_get_pending_events (notif_client *nc)
7714 {
7715   struct remote_state *rs = get_remote_state ();
7716
7717   if (rs->notif_state->pending_event[nc->id] != NULL)
7718     {
7719       if (notif_debug)
7720         fprintf_unfiltered (gdb_stdlog,
7721                             "notif: process: '%s' ack pending event\n",
7722                             nc->name);
7723
7724       /* acknowledge */
7725       nc->ack (this, nc, rs->buf, rs->notif_state->pending_event[nc->id]);
7726       rs->notif_state->pending_event[nc->id] = NULL;
7727
7728       while (1)
7729         {
7730           getpkt (&rs->buf, &rs->buf_size, 0);
7731           if (strcmp (rs->buf, "OK") == 0)
7732             break;
7733           else
7734             remote_notif_ack (this, nc, rs->buf);
7735         }
7736     }
7737   else
7738     {
7739       if (notif_debug)
7740         fprintf_unfiltered (gdb_stdlog,
7741                             "notif: process: '%s' no pending reply\n",
7742                             nc->name);
7743     }
7744 }
7745
7746 /* Wrapper around remote_target::remote_notif_get_pending_events to
7747    avoid having to export the whole remote_target class.  */
7748
7749 void
7750 remote_notif_get_pending_events (remote_target *remote, notif_client *nc)
7751 {
7752   remote->remote_notif_get_pending_events (nc);
7753 }
7754
7755 /* Called when it is decided that STOP_REPLY holds the info of the
7756    event that is to be returned to the core.  This function always
7757    destroys STOP_REPLY.  */
7758
7759 ptid_t
7760 remote_target::process_stop_reply (struct stop_reply *stop_reply,
7761                                    struct target_waitstatus *status)
7762 {
7763   ptid_t ptid;
7764
7765   *status = stop_reply->ws;
7766   ptid = stop_reply->ptid;
7767
7768   /* If no thread/process was reported by the stub, assume the current
7769      inferior.  */
7770   if (ptid_equal (ptid, null_ptid))
7771     ptid = inferior_ptid;
7772
7773   if (status->kind != TARGET_WAITKIND_EXITED
7774       && status->kind != TARGET_WAITKIND_SIGNALLED
7775       && status->kind != TARGET_WAITKIND_NO_RESUMED)
7776     {
7777       /* Expedited registers.  */
7778       if (stop_reply->regcache)
7779         {
7780           struct regcache *regcache
7781             = get_thread_arch_regcache (ptid, stop_reply->arch);
7782           cached_reg_t *reg;
7783           int ix;
7784
7785           for (ix = 0;
7786                VEC_iterate (cached_reg_t, stop_reply->regcache, ix, reg);
7787                ix++)
7788           {
7789             regcache->raw_supply (reg->num, reg->data);
7790             xfree (reg->data);
7791           }
7792
7793           VEC_free (cached_reg_t, stop_reply->regcache);
7794         }
7795
7796       remote_notice_new_inferior (ptid, 0);
7797       remote_thread_info *remote_thr = get_remote_thread_info (ptid);
7798       remote_thr->core = stop_reply->core;
7799       remote_thr->stop_reason = stop_reply->stop_reason;
7800       remote_thr->watch_data_address = stop_reply->watch_data_address;
7801       remote_thr->vcont_resumed = 0;
7802     }
7803
7804   stop_reply_xfree (stop_reply);
7805   return ptid;
7806 }
7807
7808 /* The non-stop mode version of target_wait.  */
7809
7810 ptid_t
7811 remote_target::wait_ns (ptid_t ptid, struct target_waitstatus *status, int options)
7812 {
7813   struct remote_state *rs = get_remote_state ();
7814   struct stop_reply *stop_reply;
7815   int ret;
7816   int is_notif = 0;
7817
7818   /* If in non-stop mode, get out of getpkt even if a
7819      notification is received.  */
7820
7821   ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7822                               0 /* forever */, &is_notif);
7823   while (1)
7824     {
7825       if (ret != -1 && !is_notif)
7826         switch (rs->buf[0])
7827           {
7828           case 'E':             /* Error of some sort.  */
7829             /* We're out of sync with the target now.  Did it continue
7830                or not?  We can't tell which thread it was in non-stop,
7831                so just ignore this.  */
7832             warning (_("Remote failure reply: %s"), rs->buf);
7833             break;
7834           case 'O':             /* Console output.  */
7835             remote_console_output (rs->buf + 1);
7836             break;
7837           default:
7838             warning (_("Invalid remote reply: %s"), rs->buf);
7839             break;
7840           }
7841
7842       /* Acknowledge a pending stop reply that may have arrived in the
7843          mean time.  */
7844       if (rs->notif_state->pending_event[notif_client_stop.id] != NULL)
7845         remote_notif_get_pending_events (&notif_client_stop);
7846
7847       /* If indeed we noticed a stop reply, we're done.  */
7848       stop_reply = queued_stop_reply (ptid);
7849       if (stop_reply != NULL)
7850         return process_stop_reply (stop_reply, status);
7851
7852       /* Still no event.  If we're just polling for an event, then
7853          return to the event loop.  */
7854       if (options & TARGET_WNOHANG)
7855         {
7856           status->kind = TARGET_WAITKIND_IGNORE;
7857           return minus_one_ptid;
7858         }
7859
7860       /* Otherwise do a blocking wait.  */
7861       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7862                                   1 /* forever */, &is_notif);
7863     }
7864 }
7865
7866 /* Wait until the remote machine stops, then return, storing status in
7867    STATUS just as `wait' would.  */
7868
7869 ptid_t
7870 remote_target::wait_as (ptid_t ptid, target_waitstatus *status, int options)
7871 {
7872   struct remote_state *rs = get_remote_state ();
7873   ptid_t event_ptid = null_ptid;
7874   char *buf;
7875   struct stop_reply *stop_reply;
7876
7877  again:
7878
7879   status->kind = TARGET_WAITKIND_IGNORE;
7880   status->value.integer = 0;
7881
7882   stop_reply = queued_stop_reply (ptid);
7883   if (stop_reply != NULL)
7884     return process_stop_reply (stop_reply, status);
7885
7886   if (rs->cached_wait_status)
7887     /* Use the cached wait status, but only once.  */
7888     rs->cached_wait_status = 0;
7889   else
7890     {
7891       int ret;
7892       int is_notif;
7893       int forever = ((options & TARGET_WNOHANG) == 0
7894                      && rs->wait_forever_enabled_p);
7895
7896       if (!rs->waiting_for_stop_reply)
7897         {
7898           status->kind = TARGET_WAITKIND_NO_RESUMED;
7899           return minus_one_ptid;
7900         }
7901
7902       /* FIXME: cagney/1999-09-27: If we're in async mode we should
7903          _never_ wait for ever -> test on target_is_async_p().
7904          However, before we do that we need to ensure that the caller
7905          knows how to take the target into/out of async mode.  */
7906       ret = getpkt_or_notif_sane (&rs->buf, &rs->buf_size,
7907                                   forever, &is_notif);
7908
7909       /* GDB gets a notification.  Return to core as this event is
7910          not interesting.  */
7911       if (ret != -1 && is_notif)
7912         return minus_one_ptid;
7913
7914       if (ret == -1 && (options & TARGET_WNOHANG) != 0)
7915         return minus_one_ptid;
7916     }
7917
7918   buf = rs->buf;
7919
7920   /* Assume that the target has acknowledged Ctrl-C unless we receive
7921      an 'F' or 'O' packet.  */
7922   if (buf[0] != 'F' && buf[0] != 'O')
7923     rs->ctrlc_pending_p = 0;
7924
7925   switch (buf[0])
7926     {
7927     case 'E':           /* Error of some sort.  */
7928       /* We're out of sync with the target now.  Did it continue or
7929          not?  Not is more likely, so report a stop.  */
7930       rs->waiting_for_stop_reply = 0;
7931
7932       warning (_("Remote failure reply: %s"), buf);
7933       status->kind = TARGET_WAITKIND_STOPPED;
7934       status->value.sig = GDB_SIGNAL_0;
7935       break;
7936     case 'F':           /* File-I/O request.  */
7937       /* GDB may access the inferior memory while handling the File-I/O
7938          request, but we don't want GDB accessing memory while waiting
7939          for a stop reply.  See the comments in putpkt_binary.  Set
7940          waiting_for_stop_reply to 0 temporarily.  */
7941       rs->waiting_for_stop_reply = 0;
7942       remote_fileio_request (this, buf, rs->ctrlc_pending_p);
7943       rs->ctrlc_pending_p = 0;
7944       /* GDB handled the File-I/O request, and the target is running
7945          again.  Keep waiting for events.  */
7946       rs->waiting_for_stop_reply = 1;
7947       break;
7948     case 'N': case 'T': case 'S': case 'X': case 'W':
7949       {
7950         struct stop_reply *stop_reply;
7951
7952         /* There is a stop reply to handle.  */
7953         rs->waiting_for_stop_reply = 0;
7954
7955         stop_reply
7956           = (struct stop_reply *) remote_notif_parse (this,
7957                                                       &notif_client_stop,
7958                                                       rs->buf);
7959
7960         event_ptid = process_stop_reply (stop_reply, status);
7961         break;
7962       }
7963     case 'O':           /* Console output.  */
7964       remote_console_output (buf + 1);
7965       break;
7966     case '\0':
7967       if (rs->last_sent_signal != GDB_SIGNAL_0)
7968         {
7969           /* Zero length reply means that we tried 'S' or 'C' and the
7970              remote system doesn't support it.  */
7971           target_terminal::ours_for_output ();
7972           printf_filtered
7973             ("Can't send signals to this remote system.  %s not sent.\n",
7974              gdb_signal_to_name (rs->last_sent_signal));
7975           rs->last_sent_signal = GDB_SIGNAL_0;
7976           target_terminal::inferior ();
7977
7978           strcpy (buf, rs->last_sent_step ? "s" : "c");
7979           putpkt (buf);
7980           break;
7981         }
7982       /* fallthrough */
7983     default:
7984       warning (_("Invalid remote reply: %s"), buf);
7985       break;
7986     }
7987
7988   if (status->kind == TARGET_WAITKIND_NO_RESUMED)
7989     return minus_one_ptid;
7990   else if (status->kind == TARGET_WAITKIND_IGNORE)
7991     {
7992       /* Nothing interesting happened.  If we're doing a non-blocking
7993          poll, we're done.  Otherwise, go back to waiting.  */
7994       if (options & TARGET_WNOHANG)
7995         return minus_one_ptid;
7996       else
7997         goto again;
7998     }
7999   else if (status->kind != TARGET_WAITKIND_EXITED
8000            && status->kind != TARGET_WAITKIND_SIGNALLED)
8001     {
8002       if (!ptid_equal (event_ptid, null_ptid))
8003         record_currthread (rs, event_ptid);
8004       else
8005         event_ptid = inferior_ptid;
8006     }
8007   else
8008     /* A process exit.  Invalidate our notion of current thread.  */
8009     record_currthread (rs, minus_one_ptid);
8010
8011   return event_ptid;
8012 }
8013
8014 /* Wait until the remote machine stops, then return, storing status in
8015    STATUS just as `wait' would.  */
8016
8017 ptid_t
8018 remote_target::wait (ptid_t ptid, struct target_waitstatus *status, int options)
8019 {
8020   ptid_t event_ptid;
8021
8022   if (target_is_non_stop_p ())
8023     event_ptid = wait_ns (ptid, status, options);
8024   else
8025     event_ptid = wait_as (ptid, status, options);
8026
8027   if (target_is_async_p ())
8028     {
8029       remote_state *rs = get_remote_state ();
8030
8031       /* If there are are events left in the queue tell the event loop
8032          to return here.  */
8033       if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
8034         mark_async_event_handler (rs->remote_async_inferior_event_token);
8035     }
8036
8037   return event_ptid;
8038 }
8039
8040 /* Fetch a single register using a 'p' packet.  */
8041
8042 int
8043 remote_target::fetch_register_using_p (struct regcache *regcache,
8044                                        packet_reg *reg)
8045 {
8046   struct gdbarch *gdbarch = regcache->arch ();
8047   struct remote_state *rs = get_remote_state ();
8048   char *buf, *p;
8049   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8050   int i;
8051
8052   if (packet_support (PACKET_p) == PACKET_DISABLE)
8053     return 0;
8054
8055   if (reg->pnum == -1)
8056     return 0;
8057
8058   p = rs->buf;
8059   *p++ = 'p';
8060   p += hexnumstr (p, reg->pnum);
8061   *p++ = '\0';
8062   putpkt (rs->buf);
8063   getpkt (&rs->buf, &rs->buf_size, 0);
8064
8065   buf = rs->buf;
8066
8067   switch (packet_ok (buf, &remote_protocol_packets[PACKET_p]))
8068     {
8069     case PACKET_OK:
8070       break;
8071     case PACKET_UNKNOWN:
8072       return 0;
8073     case PACKET_ERROR:
8074       error (_("Could not fetch register \"%s\"; remote failure reply '%s'"),
8075              gdbarch_register_name (regcache->arch (), 
8076                                     reg->regnum), 
8077              buf);
8078     }
8079
8080   /* If this register is unfetchable, tell the regcache.  */
8081   if (buf[0] == 'x')
8082     {
8083       regcache->raw_supply (reg->regnum, NULL);
8084       return 1;
8085     }
8086
8087   /* Otherwise, parse and supply the value.  */
8088   p = buf;
8089   i = 0;
8090   while (p[0] != 0)
8091     {
8092       if (p[1] == 0)
8093         error (_("fetch_register_using_p: early buf termination"));
8094
8095       regp[i++] = fromhex (p[0]) * 16 + fromhex (p[1]);
8096       p += 2;
8097     }
8098   regcache->raw_supply (reg->regnum, regp);
8099   return 1;
8100 }
8101
8102 /* Fetch the registers included in the target's 'g' packet.  */
8103
8104 int
8105 remote_target::send_g_packet ()
8106 {
8107   struct remote_state *rs = get_remote_state ();
8108   int buf_len;
8109
8110   xsnprintf (rs->buf, get_remote_packet_size (), "g");
8111   putpkt (rs->buf);
8112   getpkt (&rs->buf, &rs->buf_size, 0);
8113   if (packet_check_result (rs->buf) == PACKET_ERROR)
8114     error (_("Could not read registers; remote failure reply '%s'"),
8115            rs->buf);
8116
8117   /* We can get out of synch in various cases.  If the first character
8118      in the buffer is not a hex character, assume that has happened
8119      and try to fetch another packet to read.  */
8120   while ((rs->buf[0] < '0' || rs->buf[0] > '9')
8121          && (rs->buf[0] < 'A' || rs->buf[0] > 'F')
8122          && (rs->buf[0] < 'a' || rs->buf[0] > 'f')
8123          && rs->buf[0] != 'x')  /* New: unavailable register value.  */
8124     {
8125       if (remote_debug)
8126         fprintf_unfiltered (gdb_stdlog,
8127                             "Bad register packet; fetching a new packet\n");
8128       getpkt (&rs->buf, &rs->buf_size, 0);
8129     }
8130
8131   buf_len = strlen (rs->buf);
8132
8133   /* Sanity check the received packet.  */
8134   if (buf_len % 2 != 0)
8135     error (_("Remote 'g' packet reply is of odd length: %s"), rs->buf);
8136
8137   return buf_len / 2;
8138 }
8139
8140 void
8141 remote_target::process_g_packet (struct regcache *regcache)
8142 {
8143   struct gdbarch *gdbarch = regcache->arch ();
8144   struct remote_state *rs = get_remote_state ();
8145   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8146   int i, buf_len;
8147   char *p;
8148   char *regs;
8149
8150   buf_len = strlen (rs->buf);
8151
8152   /* Further sanity checks, with knowledge of the architecture.  */
8153   if (buf_len > 2 * rsa->sizeof_g_packet)
8154     error (_("Remote 'g' packet reply is too long (expected %ld bytes, got %d "
8155              "bytes): %s"), rsa->sizeof_g_packet, buf_len / 2, rs->buf);
8156
8157   /* Save the size of the packet sent to us by the target.  It is used
8158      as a heuristic when determining the max size of packets that the
8159      target can safely receive.  */
8160   if (rsa->actual_register_packet_size == 0)
8161     rsa->actual_register_packet_size = buf_len;
8162
8163   /* If this is smaller than we guessed the 'g' packet would be,
8164      update our records.  A 'g' reply that doesn't include a register's
8165      value implies either that the register is not available, or that
8166      the 'p' packet must be used.  */
8167   if (buf_len < 2 * rsa->sizeof_g_packet)
8168     {
8169       long sizeof_g_packet = buf_len / 2;
8170
8171       for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8172         {
8173           long offset = rsa->regs[i].offset;
8174           long reg_size = register_size (gdbarch, i);
8175
8176           if (rsa->regs[i].pnum == -1)
8177             continue;
8178
8179           if (offset >= sizeof_g_packet)
8180             rsa->regs[i].in_g_packet = 0;
8181           else if (offset + reg_size > sizeof_g_packet)
8182             error (_("Truncated register %d in remote 'g' packet"), i);
8183           else
8184             rsa->regs[i].in_g_packet = 1;
8185         }
8186
8187       /* Looks valid enough, we can assume this is the correct length
8188          for a 'g' packet.  It's important not to adjust
8189          rsa->sizeof_g_packet if we have truncated registers otherwise
8190          this "if" won't be run the next time the method is called
8191          with a packet of the same size and one of the internal errors
8192          below will trigger instead.  */
8193       rsa->sizeof_g_packet = sizeof_g_packet;
8194     }
8195
8196   regs = (char *) alloca (rsa->sizeof_g_packet);
8197
8198   /* Unimplemented registers read as all bits zero.  */
8199   memset (regs, 0, rsa->sizeof_g_packet);
8200
8201   /* Reply describes registers byte by byte, each byte encoded as two
8202      hex characters.  Suck them all up, then supply them to the
8203      register cacheing/storage mechanism.  */
8204
8205   p = rs->buf;
8206   for (i = 0; i < rsa->sizeof_g_packet; i++)
8207     {
8208       if (p[0] == 0 || p[1] == 0)
8209         /* This shouldn't happen - we adjusted sizeof_g_packet above.  */
8210         internal_error (__FILE__, __LINE__,
8211                         _("unexpected end of 'g' packet reply"));
8212
8213       if (p[0] == 'x' && p[1] == 'x')
8214         regs[i] = 0;            /* 'x' */
8215       else
8216         regs[i] = fromhex (p[0]) * 16 + fromhex (p[1]);
8217       p += 2;
8218     }
8219
8220   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8221     {
8222       struct packet_reg *r = &rsa->regs[i];
8223       long reg_size = register_size (gdbarch, i);
8224
8225       if (r->in_g_packet)
8226         {
8227           if ((r->offset + reg_size) * 2 > strlen (rs->buf))
8228             /* This shouldn't happen - we adjusted in_g_packet above.  */
8229             internal_error (__FILE__, __LINE__,
8230                             _("unexpected end of 'g' packet reply"));
8231           else if (rs->buf[r->offset * 2] == 'x')
8232             {
8233               gdb_assert (r->offset * 2 < strlen (rs->buf));
8234               /* The register isn't available, mark it as such (at
8235                  the same time setting the value to zero).  */
8236               regcache->raw_supply (r->regnum, NULL);
8237             }
8238           else
8239             regcache->raw_supply (r->regnum, regs + r->offset);
8240         }
8241     }
8242 }
8243
8244 void
8245 remote_target::fetch_registers_using_g (struct regcache *regcache)
8246 {
8247   send_g_packet ();
8248   process_g_packet (regcache);
8249 }
8250
8251 /* Make the remote selected traceframe match GDB's selected
8252    traceframe.  */
8253
8254 void
8255 remote_target::set_remote_traceframe ()
8256 {
8257   int newnum;
8258   struct remote_state *rs = get_remote_state ();
8259
8260   if (rs->remote_traceframe_number == get_traceframe_number ())
8261     return;
8262
8263   /* Avoid recursion, remote_trace_find calls us again.  */
8264   rs->remote_traceframe_number = get_traceframe_number ();
8265
8266   newnum = target_trace_find (tfind_number,
8267                               get_traceframe_number (), 0, 0, NULL);
8268
8269   /* Should not happen.  If it does, all bets are off.  */
8270   if (newnum != get_traceframe_number ())
8271     warning (_("could not set remote traceframe"));
8272 }
8273
8274 void
8275 remote_target::fetch_registers (struct regcache *regcache, int regnum)
8276 {
8277   struct gdbarch *gdbarch = regcache->arch ();
8278   struct remote_state *rs = get_remote_state ();
8279   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8280   int i;
8281
8282   set_remote_traceframe ();
8283   set_general_thread (regcache->ptid ());
8284
8285   if (regnum >= 0)
8286     {
8287       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8288
8289       gdb_assert (reg != NULL);
8290
8291       /* If this register might be in the 'g' packet, try that first -
8292          we are likely to read more than one register.  If this is the
8293          first 'g' packet, we might be overly optimistic about its
8294          contents, so fall back to 'p'.  */
8295       if (reg->in_g_packet)
8296         {
8297           fetch_registers_using_g (regcache);
8298           if (reg->in_g_packet)
8299             return;
8300         }
8301
8302       if (fetch_register_using_p (regcache, reg))
8303         return;
8304
8305       /* This register is not available.  */
8306       regcache->raw_supply (reg->regnum, NULL);
8307
8308       return;
8309     }
8310
8311   fetch_registers_using_g (regcache);
8312
8313   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8314     if (!rsa->regs[i].in_g_packet)
8315       if (!fetch_register_using_p (regcache, &rsa->regs[i]))
8316         {
8317           /* This register is not available.  */
8318           regcache->raw_supply (i, NULL);
8319         }
8320 }
8321
8322 /* Prepare to store registers.  Since we may send them all (using a
8323    'G' request), we have to read out the ones we don't want to change
8324    first.  */
8325
8326 void
8327 remote_target::prepare_to_store (struct regcache *regcache)
8328 {
8329   struct remote_state *rs = get_remote_state ();
8330   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8331   int i;
8332
8333   /* Make sure the entire registers array is valid.  */
8334   switch (packet_support (PACKET_P))
8335     {
8336     case PACKET_DISABLE:
8337     case PACKET_SUPPORT_UNKNOWN:
8338       /* Make sure all the necessary registers are cached.  */
8339       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8340         if (rsa->regs[i].in_g_packet)
8341           regcache->raw_update (rsa->regs[i].regnum);
8342       break;
8343     case PACKET_ENABLE:
8344       break;
8345     }
8346 }
8347
8348 /* Helper: Attempt to store REGNUM using the P packet.  Return fail IFF
8349    packet was not recognized.  */
8350
8351 int
8352 remote_target::store_register_using_P (const struct regcache *regcache,
8353                                        packet_reg *reg)
8354 {
8355   struct gdbarch *gdbarch = regcache->arch ();
8356   struct remote_state *rs = get_remote_state ();
8357   /* Try storing a single register.  */
8358   char *buf = rs->buf;
8359   gdb_byte *regp = (gdb_byte *) alloca (register_size (gdbarch, reg->regnum));
8360   char *p;
8361
8362   if (packet_support (PACKET_P) == PACKET_DISABLE)
8363     return 0;
8364
8365   if (reg->pnum == -1)
8366     return 0;
8367
8368   xsnprintf (buf, get_remote_packet_size (), "P%s=", phex_nz (reg->pnum, 0));
8369   p = buf + strlen (buf);
8370   regcache->raw_collect (reg->regnum, regp);
8371   bin2hex (regp, p, register_size (gdbarch, reg->regnum));
8372   putpkt (rs->buf);
8373   getpkt (&rs->buf, &rs->buf_size, 0);
8374
8375   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_P]))
8376     {
8377     case PACKET_OK:
8378       return 1;
8379     case PACKET_ERROR:
8380       error (_("Could not write register \"%s\"; remote failure reply '%s'"),
8381              gdbarch_register_name (gdbarch, reg->regnum), rs->buf);
8382     case PACKET_UNKNOWN:
8383       return 0;
8384     default:
8385       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
8386     }
8387 }
8388
8389 /* Store register REGNUM, or all registers if REGNUM == -1, from the
8390    contents of the register cache buffer.  FIXME: ignores errors.  */
8391
8392 void
8393 remote_target::store_registers_using_G (const struct regcache *regcache)
8394 {
8395   struct remote_state *rs = get_remote_state ();
8396   remote_arch_state *rsa = rs->get_remote_arch_state (regcache->arch ());
8397   gdb_byte *regs;
8398   char *p;
8399
8400   /* Extract all the registers in the regcache copying them into a
8401      local buffer.  */
8402   {
8403     int i;
8404
8405     regs = (gdb_byte *) alloca (rsa->sizeof_g_packet);
8406     memset (regs, 0, rsa->sizeof_g_packet);
8407     for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
8408       {
8409         struct packet_reg *r = &rsa->regs[i];
8410
8411         if (r->in_g_packet)
8412           regcache->raw_collect (r->regnum, regs + r->offset);
8413       }
8414   }
8415
8416   /* Command describes registers byte by byte,
8417      each byte encoded as two hex characters.  */
8418   p = rs->buf;
8419   *p++ = 'G';
8420   bin2hex (regs, p, rsa->sizeof_g_packet);
8421   putpkt (rs->buf);
8422   getpkt (&rs->buf, &rs->buf_size, 0);
8423   if (packet_check_result (rs->buf) == PACKET_ERROR)
8424     error (_("Could not write registers; remote failure reply '%s'"), 
8425            rs->buf);
8426 }
8427
8428 /* Store register REGNUM, or all registers if REGNUM == -1, from the contents
8429    of the register cache buffer.  FIXME: ignores errors.  */
8430
8431 void
8432 remote_target::store_registers (struct regcache *regcache, int regnum)
8433 {
8434   struct gdbarch *gdbarch = regcache->arch ();
8435   struct remote_state *rs = get_remote_state ();
8436   remote_arch_state *rsa = rs->get_remote_arch_state (gdbarch);
8437   int i;
8438
8439   set_remote_traceframe ();
8440   set_general_thread (regcache->ptid ());
8441
8442   if (regnum >= 0)
8443     {
8444       packet_reg *reg = packet_reg_from_regnum (gdbarch, rsa, regnum);
8445
8446       gdb_assert (reg != NULL);
8447
8448       /* Always prefer to store registers using the 'P' packet if
8449          possible; we often change only a small number of registers.
8450          Sometimes we change a larger number; we'd need help from a
8451          higher layer to know to use 'G'.  */
8452       if (store_register_using_P (regcache, reg))
8453         return;
8454
8455       /* For now, don't complain if we have no way to write the
8456          register.  GDB loses track of unavailable registers too
8457          easily.  Some day, this may be an error.  We don't have
8458          any way to read the register, either...  */
8459       if (!reg->in_g_packet)
8460         return;
8461
8462       store_registers_using_G (regcache);
8463       return;
8464     }
8465
8466   store_registers_using_G (regcache);
8467
8468   for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
8469     if (!rsa->regs[i].in_g_packet)
8470       if (!store_register_using_P (regcache, &rsa->regs[i]))
8471         /* See above for why we do not issue an error here.  */
8472         continue;
8473 }
8474 \f
8475
8476 /* Return the number of hex digits in num.  */
8477
8478 static int
8479 hexnumlen (ULONGEST num)
8480 {
8481   int i;
8482
8483   for (i = 0; num != 0; i++)
8484     num >>= 4;
8485
8486   return std::max (i, 1);
8487 }
8488
8489 /* Set BUF to the minimum number of hex digits representing NUM.  */
8490
8491 static int
8492 hexnumstr (char *buf, ULONGEST num)
8493 {
8494   int len = hexnumlen (num);
8495
8496   return hexnumnstr (buf, num, len);
8497 }
8498
8499
8500 /* Set BUF to the hex digits representing NUM, padded to WIDTH characters.  */
8501
8502 static int
8503 hexnumnstr (char *buf, ULONGEST num, int width)
8504 {
8505   int i;
8506
8507   buf[width] = '\0';
8508
8509   for (i = width - 1; i >= 0; i--)
8510     {
8511       buf[i] = "0123456789abcdef"[(num & 0xf)];
8512       num >>= 4;
8513     }
8514
8515   return width;
8516 }
8517
8518 /* Mask all but the least significant REMOTE_ADDRESS_SIZE bits.  */
8519
8520 static CORE_ADDR
8521 remote_address_masked (CORE_ADDR addr)
8522 {
8523   unsigned int address_size = remote_address_size;
8524
8525   /* If "remoteaddresssize" was not set, default to target address size.  */
8526   if (!address_size)
8527     address_size = gdbarch_addr_bit (target_gdbarch ());
8528
8529   if (address_size > 0
8530       && address_size < (sizeof (ULONGEST) * 8))
8531     {
8532       /* Only create a mask when that mask can safely be constructed
8533          in a ULONGEST variable.  */
8534       ULONGEST mask = 1;
8535
8536       mask = (mask << address_size) - 1;
8537       addr &= mask;
8538     }
8539   return addr;
8540 }
8541
8542 /* Determine whether the remote target supports binary downloading.
8543    This is accomplished by sending a no-op memory write of zero length
8544    to the target at the specified address. It does not suffice to send
8545    the whole packet, since many stubs strip the eighth bit and
8546    subsequently compute a wrong checksum, which causes real havoc with
8547    remote_write_bytes.
8548
8549    NOTE: This can still lose if the serial line is not eight-bit
8550    clean.  In cases like this, the user should clear "remote
8551    X-packet".  */
8552
8553 void
8554 remote_target::check_binary_download (CORE_ADDR addr)
8555 {
8556   struct remote_state *rs = get_remote_state ();
8557
8558   switch (packet_support (PACKET_X))
8559     {
8560     case PACKET_DISABLE:
8561       break;
8562     case PACKET_ENABLE:
8563       break;
8564     case PACKET_SUPPORT_UNKNOWN:
8565       {
8566         char *p;
8567
8568         p = rs->buf;
8569         *p++ = 'X';
8570         p += hexnumstr (p, (ULONGEST) addr);
8571         *p++ = ',';
8572         p += hexnumstr (p, (ULONGEST) 0);
8573         *p++ = ':';
8574         *p = '\0';
8575
8576         putpkt_binary (rs->buf, (int) (p - rs->buf));
8577         getpkt (&rs->buf, &rs->buf_size, 0);
8578
8579         if (rs->buf[0] == '\0')
8580           {
8581             if (remote_debug)
8582               fprintf_unfiltered (gdb_stdlog,
8583                                   "binary downloading NOT "
8584                                   "supported by target\n");
8585             remote_protocol_packets[PACKET_X].support = PACKET_DISABLE;
8586           }
8587         else
8588           {
8589             if (remote_debug)
8590               fprintf_unfiltered (gdb_stdlog,
8591                                   "binary downloading supported by target\n");
8592             remote_protocol_packets[PACKET_X].support = PACKET_ENABLE;
8593           }
8594         break;
8595       }
8596     }
8597 }
8598
8599 /* Helper function to resize the payload in order to try to get a good
8600    alignment.  We try to write an amount of data such that the next write will
8601    start on an address aligned on REMOTE_ALIGN_WRITES.  */
8602
8603 static int
8604 align_for_efficient_write (int todo, CORE_ADDR memaddr)
8605 {
8606   return ((memaddr + todo) & ~(REMOTE_ALIGN_WRITES - 1)) - memaddr;
8607 }
8608
8609 /* Write memory data directly to the remote machine.
8610    This does not inform the data cache; the data cache uses this.
8611    HEADER is the starting part of the packet.
8612    MEMADDR is the address in the remote memory space.
8613    MYADDR is the address of the buffer in our space.
8614    LEN_UNITS is the number of addressable units to write.
8615    UNIT_SIZE is the length in bytes of an addressable unit.
8616    PACKET_FORMAT should be either 'X' or 'M', and indicates if we
8617    should send data as binary ('X'), or hex-encoded ('M').
8618
8619    The function creates packet of the form
8620        <HEADER><ADDRESS>,<LENGTH>:<DATA>
8621
8622    where encoding of <DATA> is terminated by PACKET_FORMAT.
8623
8624    If USE_LENGTH is 0, then the <LENGTH> field and the preceding comma
8625    are omitted.
8626
8627    Return the transferred status, error or OK (an
8628    'enum target_xfer_status' value).  Save the number of addressable units
8629    transferred in *XFERED_LEN_UNITS.  Only transfer a single packet.
8630
8631    On a platform with an addressable memory size of 2 bytes (UNIT_SIZE == 2), an
8632    exchange between gdb and the stub could look like (?? in place of the
8633    checksum):
8634
8635    -> $m1000,4#??
8636    <- aaaabbbbccccdddd
8637
8638    -> $M1000,3:eeeeffffeeee#??
8639    <- OK
8640
8641    -> $m1000,4#??
8642    <- eeeeffffeeeedddd  */
8643
8644 target_xfer_status
8645 remote_target::remote_write_bytes_aux (const char *header, CORE_ADDR memaddr,
8646                                        const gdb_byte *myaddr,
8647                                        ULONGEST len_units,
8648                                        int unit_size,
8649                                        ULONGEST *xfered_len_units,
8650                                        char packet_format, int use_length)
8651 {
8652   struct remote_state *rs = get_remote_state ();
8653   char *p;
8654   char *plen = NULL;
8655   int plenlen = 0;
8656   int todo_units;
8657   int units_written;
8658   int payload_capacity_bytes;
8659   int payload_length_bytes;
8660
8661   if (packet_format != 'X' && packet_format != 'M')
8662     internal_error (__FILE__, __LINE__,
8663                     _("remote_write_bytes_aux: bad packet format"));
8664
8665   if (len_units == 0)
8666     return TARGET_XFER_EOF;
8667
8668   payload_capacity_bytes = get_memory_write_packet_size ();
8669
8670   /* The packet buffer will be large enough for the payload;
8671      get_memory_packet_size ensures this.  */
8672   rs->buf[0] = '\0';
8673
8674   /* Compute the size of the actual payload by subtracting out the
8675      packet header and footer overhead: "$M<memaddr>,<len>:...#nn".  */
8676
8677   payload_capacity_bytes -= strlen ("$,:#NN");
8678   if (!use_length)
8679     /* The comma won't be used.  */
8680     payload_capacity_bytes += 1;
8681   payload_capacity_bytes -= strlen (header);
8682   payload_capacity_bytes -= hexnumlen (memaddr);
8683
8684   /* Construct the packet excluding the data: "<header><memaddr>,<len>:".  */
8685
8686   strcat (rs->buf, header);
8687   p = rs->buf + strlen (header);
8688
8689   /* Compute a best guess of the number of bytes actually transfered.  */
8690   if (packet_format == 'X')
8691     {
8692       /* Best guess at number of bytes that will fit.  */
8693       todo_units = std::min (len_units,
8694                              (ULONGEST) payload_capacity_bytes / unit_size);
8695       if (use_length)
8696         payload_capacity_bytes -= hexnumlen (todo_units);
8697       todo_units = std::min (todo_units, payload_capacity_bytes / unit_size);
8698     }
8699   else
8700     {
8701       /* Number of bytes that will fit.  */
8702       todo_units
8703         = std::min (len_units,
8704                     (ULONGEST) (payload_capacity_bytes / unit_size) / 2);
8705       if (use_length)
8706         payload_capacity_bytes -= hexnumlen (todo_units);
8707       todo_units = std::min (todo_units,
8708                              (payload_capacity_bytes / unit_size) / 2);
8709     }
8710
8711   if (todo_units <= 0)
8712     internal_error (__FILE__, __LINE__,
8713                     _("minimum packet size too small to write data"));
8714
8715   /* If we already need another packet, then try to align the end
8716      of this packet to a useful boundary.  */
8717   if (todo_units > 2 * REMOTE_ALIGN_WRITES && todo_units < len_units)
8718     todo_units = align_for_efficient_write (todo_units, memaddr);
8719
8720   /* Append "<memaddr>".  */
8721   memaddr = remote_address_masked (memaddr);
8722   p += hexnumstr (p, (ULONGEST) memaddr);
8723
8724   if (use_length)
8725     {
8726       /* Append ",".  */
8727       *p++ = ',';
8728
8729       /* Append the length and retain its location and size.  It may need to be
8730          adjusted once the packet body has been created.  */
8731       plen = p;
8732       plenlen = hexnumstr (p, (ULONGEST) todo_units);
8733       p += plenlen;
8734     }
8735
8736   /* Append ":".  */
8737   *p++ = ':';
8738   *p = '\0';
8739
8740   /* Append the packet body.  */
8741   if (packet_format == 'X')
8742     {
8743       /* Binary mode.  Send target system values byte by byte, in
8744          increasing byte addresses.  Only escape certain critical
8745          characters.  */
8746       payload_length_bytes =
8747           remote_escape_output (myaddr, todo_units, unit_size, (gdb_byte *) p,
8748                                 &units_written, payload_capacity_bytes);
8749
8750       /* If not all TODO units fit, then we'll need another packet.  Make
8751          a second try to keep the end of the packet aligned.  Don't do
8752          this if the packet is tiny.  */
8753       if (units_written < todo_units && units_written > 2 * REMOTE_ALIGN_WRITES)
8754         {
8755           int new_todo_units;
8756
8757           new_todo_units = align_for_efficient_write (units_written, memaddr);
8758
8759           if (new_todo_units != units_written)
8760             payload_length_bytes =
8761                 remote_escape_output (myaddr, new_todo_units, unit_size,
8762                                       (gdb_byte *) p, &units_written,
8763                                       payload_capacity_bytes);
8764         }
8765
8766       p += payload_length_bytes;
8767       if (use_length && units_written < todo_units)
8768         {
8769           /* Escape chars have filled up the buffer prematurely,
8770              and we have actually sent fewer units than planned.
8771              Fix-up the length field of the packet.  Use the same
8772              number of characters as before.  */
8773           plen += hexnumnstr (plen, (ULONGEST) units_written,
8774                               plenlen);
8775           *plen = ':';  /* overwrite \0 from hexnumnstr() */
8776         }
8777     }
8778   else
8779     {
8780       /* Normal mode: Send target system values byte by byte, in
8781          increasing byte addresses.  Each byte is encoded as a two hex
8782          value.  */
8783       p += 2 * bin2hex (myaddr, p, todo_units * unit_size);
8784       units_written = todo_units;
8785     }
8786
8787   putpkt_binary (rs->buf, (int) (p - rs->buf));
8788   getpkt (&rs->buf, &rs->buf_size, 0);
8789
8790   if (rs->buf[0] == 'E')
8791     return TARGET_XFER_E_IO;
8792
8793   /* Return UNITS_WRITTEN, not TODO_UNITS, in case escape chars caused us to
8794      send fewer units than we'd planned.  */
8795   *xfered_len_units = (ULONGEST) units_written;
8796   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8797 }
8798
8799 /* Write memory data directly to the remote machine.
8800    This does not inform the data cache; the data cache uses this.
8801    MEMADDR is the address in the remote memory space.
8802    MYADDR is the address of the buffer in our space.
8803    LEN is the number of bytes.
8804
8805    Return the transferred status, error or OK (an
8806    'enum target_xfer_status' value).  Save the number of bytes
8807    transferred in *XFERED_LEN.  Only transfer a single packet.  */
8808
8809 target_xfer_status
8810 remote_target::remote_write_bytes (CORE_ADDR memaddr, const gdb_byte *myaddr,
8811                                    ULONGEST len, int unit_size,
8812                                    ULONGEST *xfered_len)
8813 {
8814   const char *packet_format = NULL;
8815
8816   /* Check whether the target supports binary download.  */
8817   check_binary_download (memaddr);
8818
8819   switch (packet_support (PACKET_X))
8820     {
8821     case PACKET_ENABLE:
8822       packet_format = "X";
8823       break;
8824     case PACKET_DISABLE:
8825       packet_format = "M";
8826       break;
8827     case PACKET_SUPPORT_UNKNOWN:
8828       internal_error (__FILE__, __LINE__,
8829                       _("remote_write_bytes: bad internal state"));
8830     default:
8831       internal_error (__FILE__, __LINE__, _("bad switch"));
8832     }
8833
8834   return remote_write_bytes_aux (packet_format,
8835                                  memaddr, myaddr, len, unit_size, xfered_len,
8836                                  packet_format[0], 1);
8837 }
8838
8839 /* Read memory data directly from the remote machine.
8840    This does not use the data cache; the data cache uses this.
8841    MEMADDR is the address in the remote memory space.
8842    MYADDR is the address of the buffer in our space.
8843    LEN_UNITS is the number of addressable memory units to read..
8844    UNIT_SIZE is the length in bytes of an addressable unit.
8845
8846    Return the transferred status, error or OK (an
8847    'enum target_xfer_status' value).  Save the number of bytes
8848    transferred in *XFERED_LEN_UNITS.
8849
8850    See the comment of remote_write_bytes_aux for an example of
8851    memory read/write exchange between gdb and the stub.  */
8852
8853 target_xfer_status
8854 remote_target::remote_read_bytes_1 (CORE_ADDR memaddr, gdb_byte *myaddr,
8855                                     ULONGEST len_units,
8856                                     int unit_size, ULONGEST *xfered_len_units)
8857 {
8858   struct remote_state *rs = get_remote_state ();
8859   int buf_size_bytes;           /* Max size of packet output buffer.  */
8860   char *p;
8861   int todo_units;
8862   int decoded_bytes;
8863
8864   buf_size_bytes = get_memory_read_packet_size ();
8865   /* The packet buffer will be large enough for the payload;
8866      get_memory_packet_size ensures this.  */
8867
8868   /* Number of units that will fit.  */
8869   todo_units = std::min (len_units,
8870                          (ULONGEST) (buf_size_bytes / unit_size) / 2);
8871
8872   /* Construct "m"<memaddr>","<len>".  */
8873   memaddr = remote_address_masked (memaddr);
8874   p = rs->buf;
8875   *p++ = 'm';
8876   p += hexnumstr (p, (ULONGEST) memaddr);
8877   *p++ = ',';
8878   p += hexnumstr (p, (ULONGEST) todo_units);
8879   *p = '\0';
8880   putpkt (rs->buf);
8881   getpkt (&rs->buf, &rs->buf_size, 0);
8882   if (rs->buf[0] == 'E'
8883       && isxdigit (rs->buf[1]) && isxdigit (rs->buf[2])
8884       && rs->buf[3] == '\0')
8885     return TARGET_XFER_E_IO;
8886   /* Reply describes memory byte by byte, each byte encoded as two hex
8887      characters.  */
8888   p = rs->buf;
8889   decoded_bytes = hex2bin (p, myaddr, todo_units * unit_size);
8890   /* Return what we have.  Let higher layers handle partial reads.  */
8891   *xfered_len_units = (ULONGEST) (decoded_bytes / unit_size);
8892   return (*xfered_len_units != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
8893 }
8894
8895 /* Using the set of read-only target sections of remote, read live
8896    read-only memory.
8897
8898    For interface/parameters/return description see target.h,
8899    to_xfer_partial.  */
8900
8901 target_xfer_status
8902 remote_target::remote_xfer_live_readonly_partial (gdb_byte *readbuf,
8903                                                   ULONGEST memaddr,
8904                                                   ULONGEST len,
8905                                                   int unit_size,
8906                                                   ULONGEST *xfered_len)
8907 {
8908   struct target_section *secp;
8909   struct target_section_table *table;
8910
8911   secp = target_section_by_addr (this, memaddr);
8912   if (secp != NULL
8913       && (bfd_get_section_flags (secp->the_bfd_section->owner,
8914                                  secp->the_bfd_section)
8915           & SEC_READONLY))
8916     {
8917       struct target_section *p;
8918       ULONGEST memend = memaddr + len;
8919
8920       table = target_get_section_table (this);
8921
8922       for (p = table->sections; p < table->sections_end; p++)
8923         {
8924           if (memaddr >= p->addr)
8925             {
8926               if (memend <= p->endaddr)
8927                 {
8928                   /* Entire transfer is within this section.  */
8929                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8930                                               xfered_len);
8931                 }
8932               else if (memaddr >= p->endaddr)
8933                 {
8934                   /* This section ends before the transfer starts.  */
8935                   continue;
8936                 }
8937               else
8938                 {
8939                   /* This section overlaps the transfer.  Just do half.  */
8940                   len = p->endaddr - memaddr;
8941                   return remote_read_bytes_1 (memaddr, readbuf, len, unit_size,
8942                                               xfered_len);
8943                 }
8944             }
8945         }
8946     }
8947
8948   return TARGET_XFER_EOF;
8949 }
8950
8951 /* Similar to remote_read_bytes_1, but it reads from the remote stub
8952    first if the requested memory is unavailable in traceframe.
8953    Otherwise, fall back to remote_read_bytes_1.  */
8954
8955 target_xfer_status
8956 remote_target::remote_read_bytes (CORE_ADDR memaddr,
8957                                   gdb_byte *myaddr, ULONGEST len, int unit_size,
8958                                   ULONGEST *xfered_len)
8959 {
8960   if (len == 0)
8961     return TARGET_XFER_EOF;
8962
8963   if (get_traceframe_number () != -1)
8964     {
8965       std::vector<mem_range> available;
8966
8967       /* If we fail to get the set of available memory, then the
8968          target does not support querying traceframe info, and so we
8969          attempt reading from the traceframe anyway (assuming the
8970          target implements the old QTro packet then).  */
8971       if (traceframe_available_memory (&available, memaddr, len))
8972         {
8973           if (available.empty () || available[0].start != memaddr)
8974             {
8975               enum target_xfer_status res;
8976
8977               /* Don't read into the traceframe's available
8978                  memory.  */
8979               if (!available.empty ())
8980                 {
8981                   LONGEST oldlen = len;
8982
8983                   len = available[0].start - memaddr;
8984                   gdb_assert (len <= oldlen);
8985                 }
8986
8987               /* This goes through the topmost target again.  */
8988               res = remote_xfer_live_readonly_partial (myaddr, memaddr,
8989                                                        len, unit_size, xfered_len);
8990               if (res == TARGET_XFER_OK)
8991                 return TARGET_XFER_OK;
8992               else
8993                 {
8994                   /* No use trying further, we know some memory starting
8995                      at MEMADDR isn't available.  */
8996                   *xfered_len = len;
8997                   return (*xfered_len != 0) ?
8998                     TARGET_XFER_UNAVAILABLE : TARGET_XFER_EOF;
8999                 }
9000             }
9001
9002           /* Don't try to read more than how much is available, in
9003              case the target implements the deprecated QTro packet to
9004              cater for older GDBs (the target's knowledge of read-only
9005              sections may be outdated by now).  */
9006           len = available[0].length;
9007         }
9008     }
9009
9010   return remote_read_bytes_1 (memaddr, myaddr, len, unit_size, xfered_len);
9011 }
9012
9013 \f
9014
9015 /* Sends a packet with content determined by the printf format string
9016    FORMAT and the remaining arguments, then gets the reply.  Returns
9017    whether the packet was a success, a failure, or unknown.  */
9018
9019 packet_result
9020 remote_target::remote_send_printf (const char *format, ...)
9021 {
9022   struct remote_state *rs = get_remote_state ();
9023   int max_size = get_remote_packet_size ();
9024   va_list ap;
9025
9026   va_start (ap, format);
9027
9028   rs->buf[0] = '\0';
9029   if (vsnprintf (rs->buf, max_size, format, ap) >= max_size)
9030     internal_error (__FILE__, __LINE__, _("Too long remote packet."));
9031
9032   if (putpkt (rs->buf) < 0)
9033     error (_("Communication problem with target."));
9034
9035   rs->buf[0] = '\0';
9036   getpkt (&rs->buf, &rs->buf_size, 0);
9037
9038   return packet_check_result (rs->buf);
9039 }
9040
9041 /* Flash writing can take quite some time.  We'll set
9042    effectively infinite timeout for flash operations.
9043    In future, we'll need to decide on a better approach.  */
9044 static const int remote_flash_timeout = 1000;
9045
9046 void
9047 remote_target::flash_erase (ULONGEST address, LONGEST length)
9048 {
9049   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
9050   enum packet_result ret;
9051   scoped_restore restore_timeout
9052     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9053
9054   ret = remote_send_printf ("vFlashErase:%s,%s",
9055                             phex (address, addr_size),
9056                             phex (length, 4));
9057   switch (ret)
9058     {
9059     case PACKET_UNKNOWN:
9060       error (_("Remote target does not support flash erase"));
9061     case PACKET_ERROR:
9062       error (_("Error erasing flash with vFlashErase packet"));
9063     default:
9064       break;
9065     }
9066 }
9067
9068 target_xfer_status
9069 remote_target::remote_flash_write (ULONGEST address,
9070                                    ULONGEST length, ULONGEST *xfered_len,
9071                                    const gdb_byte *data)
9072 {
9073   scoped_restore restore_timeout
9074     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9075   return remote_write_bytes_aux ("vFlashWrite:", address, data, length, 1,
9076                                  xfered_len,'X', 0);
9077 }
9078
9079 void
9080 remote_target::flash_done ()
9081 {
9082   int ret;
9083
9084   scoped_restore restore_timeout
9085     = make_scoped_restore (&remote_timeout, remote_flash_timeout);
9086
9087   ret = remote_send_printf ("vFlashDone");
9088
9089   switch (ret)
9090     {
9091     case PACKET_UNKNOWN:
9092       error (_("Remote target does not support vFlashDone"));
9093     case PACKET_ERROR:
9094       error (_("Error finishing flash operation"));
9095     default:
9096       break;
9097     }
9098 }
9099
9100 void
9101 remote_target::files_info ()
9102 {
9103   puts_filtered ("Debugging a target over a serial line.\n");
9104 }
9105 \f
9106 /* Stuff for dealing with the packets which are part of this protocol.
9107    See comment at top of file for details.  */
9108
9109 /* Close/unpush the remote target, and throw a TARGET_CLOSE_ERROR
9110    error to higher layers.  Called when a serial error is detected.
9111    The exception message is STRING, followed by a colon and a blank,
9112    the system error message for errno at function entry and final dot
9113    for output compatibility with throw_perror_with_name.  */
9114
9115 static void
9116 unpush_and_perror (const char *string)
9117 {
9118   int saved_errno = errno;
9119
9120   remote_unpush_target ();
9121   throw_error (TARGET_CLOSE_ERROR, "%s: %s.", string,
9122                safe_strerror (saved_errno));
9123 }
9124
9125 /* Read a single character from the remote end.  The current quit
9126    handler is overridden to avoid quitting in the middle of packet
9127    sequence, as that would break communication with the remote server.
9128    See remote_serial_quit_handler for more detail.  */
9129
9130 int
9131 remote_target::readchar (int timeout)
9132 {
9133   int ch;
9134   struct remote_state *rs = get_remote_state ();
9135
9136   {
9137     scoped_restore restore_quit_target
9138       = make_scoped_restore (&curr_quit_handler_target, this);
9139     scoped_restore restore_quit
9140       = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9141
9142     rs->got_ctrlc_during_io = 0;
9143
9144     ch = serial_readchar (rs->remote_desc, timeout);
9145
9146     if (rs->got_ctrlc_during_io)
9147       set_quit_flag ();
9148   }
9149
9150   if (ch >= 0)
9151     return ch;
9152
9153   switch ((enum serial_rc) ch)
9154     {
9155     case SERIAL_EOF:
9156       remote_unpush_target ();
9157       throw_error (TARGET_CLOSE_ERROR, _("Remote connection closed"));
9158       /* no return */
9159     case SERIAL_ERROR:
9160       unpush_and_perror (_("Remote communication error.  "
9161                            "Target disconnected."));
9162       /* no return */
9163     case SERIAL_TIMEOUT:
9164       break;
9165     }
9166   return ch;
9167 }
9168
9169 /* Wrapper for serial_write that closes the target and throws if
9170    writing fails.  The current quit handler is overridden to avoid
9171    quitting in the middle of packet sequence, as that would break
9172    communication with the remote server.  See
9173    remote_serial_quit_handler for more detail.  */
9174
9175 void
9176 remote_target::remote_serial_write (const char *str, int len)
9177 {
9178   struct remote_state *rs = get_remote_state ();
9179
9180   scoped_restore restore_quit_target
9181     = make_scoped_restore (&curr_quit_handler_target, this);
9182   scoped_restore restore_quit
9183     = make_scoped_restore (&quit_handler, ::remote_serial_quit_handler);
9184
9185   rs->got_ctrlc_during_io = 0;
9186
9187   if (serial_write (rs->remote_desc, str, len))
9188     {
9189       unpush_and_perror (_("Remote communication error.  "
9190                            "Target disconnected."));
9191     }
9192
9193   if (rs->got_ctrlc_during_io)
9194     set_quit_flag ();
9195 }
9196
9197 /* Return a string representing an escaped version of BUF, of len N.
9198    E.g. \n is converted to \\n, \t to \\t, etc.  */
9199
9200 static std::string
9201 escape_buffer (const char *buf, int n)
9202 {
9203   string_file stb;
9204
9205   stb.putstrn (buf, n, '\\');
9206   return std::move (stb.string ());
9207 }
9208
9209 /* Display a null-terminated packet on stdout, for debugging, using C
9210    string notation.  */
9211
9212 static void
9213 print_packet (const char *buf)
9214 {
9215   puts_filtered ("\"");
9216   fputstr_filtered (buf, '"', gdb_stdout);
9217   puts_filtered ("\"");
9218 }
9219
9220 int
9221 remote_target::putpkt (const char *buf)
9222 {
9223   return putpkt_binary (buf, strlen (buf));
9224 }
9225
9226 /* Wrapper around remote_target::putpkt to avoid exporting
9227    remote_target.  */
9228
9229 int
9230 putpkt (remote_target *remote, const char *buf)
9231 {
9232   return remote->putpkt (buf);
9233 }
9234
9235 /* Send a packet to the remote machine, with error checking.  The data
9236    of the packet is in BUF.  The string in BUF can be at most
9237    get_remote_packet_size () - 5 to account for the $, # and checksum,
9238    and for a possible /0 if we are debugging (remote_debug) and want
9239    to print the sent packet as a string.  */
9240
9241 int
9242 remote_target::putpkt_binary (const char *buf, int cnt)
9243 {
9244   struct remote_state *rs = get_remote_state ();
9245   int i;
9246   unsigned char csum = 0;
9247   gdb::def_vector<char> data (cnt + 6);
9248   char *buf2 = data.data ();
9249
9250   int ch;
9251   int tcount = 0;
9252   char *p;
9253
9254   /* Catch cases like trying to read memory or listing threads while
9255      we're waiting for a stop reply.  The remote server wouldn't be
9256      ready to handle this request, so we'd hang and timeout.  We don't
9257      have to worry about this in synchronous mode, because in that
9258      case it's not possible to issue a command while the target is
9259      running.  This is not a problem in non-stop mode, because in that
9260      case, the stub is always ready to process serial input.  */
9261   if (!target_is_non_stop_p ()
9262       && target_is_async_p ()
9263       && rs->waiting_for_stop_reply)
9264     {
9265       error (_("Cannot execute this command while the target is running.\n"
9266                "Use the \"interrupt\" command to stop the target\n"
9267                "and then try again."));
9268     }
9269
9270   /* We're sending out a new packet.  Make sure we don't look at a
9271      stale cached response.  */
9272   rs->cached_wait_status = 0;
9273
9274   /* Copy the packet into buffer BUF2, encapsulating it
9275      and giving it a checksum.  */
9276
9277   p = buf2;
9278   *p++ = '$';
9279
9280   for (i = 0; i < cnt; i++)
9281     {
9282       csum += buf[i];
9283       *p++ = buf[i];
9284     }
9285   *p++ = '#';
9286   *p++ = tohex ((csum >> 4) & 0xf);
9287   *p++ = tohex (csum & 0xf);
9288
9289   /* Send it over and over until we get a positive ack.  */
9290
9291   while (1)
9292     {
9293       int started_error_output = 0;
9294
9295       if (remote_debug)
9296         {
9297           *p = '\0';
9298
9299           int len = (int) (p - buf2);
9300
9301           std::string str
9302             = escape_buffer (buf2, std::min (len, REMOTE_DEBUG_MAX_CHAR));
9303
9304           fprintf_unfiltered (gdb_stdlog, "Sending packet: %s", str.c_str ());
9305
9306           if (len > REMOTE_DEBUG_MAX_CHAR)
9307             fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9308                                 len - REMOTE_DEBUG_MAX_CHAR);
9309
9310           fprintf_unfiltered (gdb_stdlog, "...");
9311
9312           gdb_flush (gdb_stdlog);
9313         }
9314       remote_serial_write (buf2, p - buf2);
9315
9316       /* If this is a no acks version of the remote protocol, send the
9317          packet and move on.  */
9318       if (rs->noack_mode)
9319         break;
9320
9321       /* Read until either a timeout occurs (-2) or '+' is read.
9322          Handle any notification that arrives in the mean time.  */
9323       while (1)
9324         {
9325           ch = readchar (remote_timeout);
9326
9327           if (remote_debug)
9328             {
9329               switch (ch)
9330                 {
9331                 case '+':
9332                 case '-':
9333                 case SERIAL_TIMEOUT:
9334                 case '$':
9335                 case '%':
9336                   if (started_error_output)
9337                     {
9338                       putchar_unfiltered ('\n');
9339                       started_error_output = 0;
9340                     }
9341                 }
9342             }
9343
9344           switch (ch)
9345             {
9346             case '+':
9347               if (remote_debug)
9348                 fprintf_unfiltered (gdb_stdlog, "Ack\n");
9349               return 1;
9350             case '-':
9351               if (remote_debug)
9352                 fprintf_unfiltered (gdb_stdlog, "Nak\n");
9353               /* FALLTHROUGH */
9354             case SERIAL_TIMEOUT:
9355               tcount++;
9356               if (tcount > 3)
9357                 return 0;
9358               break;            /* Retransmit buffer.  */
9359             case '$':
9360               {
9361                 if (remote_debug)
9362                   fprintf_unfiltered (gdb_stdlog,
9363                                       "Packet instead of Ack, ignoring it\n");
9364                 /* It's probably an old response sent because an ACK
9365                    was lost.  Gobble up the packet and ack it so it
9366                    doesn't get retransmitted when we resend this
9367                    packet.  */
9368                 skip_frame ();
9369                 remote_serial_write ("+", 1);
9370                 continue;       /* Now, go look for +.  */
9371               }
9372
9373             case '%':
9374               {
9375                 int val;
9376
9377                 /* If we got a notification, handle it, and go back to looking
9378                    for an ack.  */
9379                 /* We've found the start of a notification.  Now
9380                    collect the data.  */
9381                 val = read_frame (&rs->buf, &rs->buf_size);
9382                 if (val >= 0)
9383                   {
9384                     if (remote_debug)
9385                       {
9386                         std::string str = escape_buffer (rs->buf, val);
9387
9388                         fprintf_unfiltered (gdb_stdlog,
9389                                             "  Notification received: %s\n",
9390                                             str.c_str ());
9391                       }
9392                     handle_notification (rs->notif_state, rs->buf);
9393                     /* We're in sync now, rewait for the ack.  */
9394                     tcount = 0;
9395                   }
9396                 else
9397                   {
9398                     if (remote_debug)
9399                       {
9400                         if (!started_error_output)
9401                           {
9402                             started_error_output = 1;
9403                             fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9404                           }
9405                         fputc_unfiltered (ch & 0177, gdb_stdlog);
9406                         fprintf_unfiltered (gdb_stdlog, "%s", rs->buf);
9407                       }
9408                   }
9409                 continue;
9410               }
9411               /* fall-through */
9412             default:
9413               if (remote_debug)
9414                 {
9415                   if (!started_error_output)
9416                     {
9417                       started_error_output = 1;
9418                       fprintf_unfiltered (gdb_stdlog, "putpkt: Junk: ");
9419                     }
9420                   fputc_unfiltered (ch & 0177, gdb_stdlog);
9421                 }
9422               continue;
9423             }
9424           break;                /* Here to retransmit.  */
9425         }
9426
9427 #if 0
9428       /* This is wrong.  If doing a long backtrace, the user should be
9429          able to get out next time we call QUIT, without anything as
9430          violent as interrupt_query.  If we want to provide a way out of
9431          here without getting to the next QUIT, it should be based on
9432          hitting ^C twice as in remote_wait.  */
9433       if (quit_flag)
9434         {
9435           quit_flag = 0;
9436           interrupt_query ();
9437         }
9438 #endif
9439     }
9440
9441   return 0;
9442 }
9443
9444 /* Come here after finding the start of a frame when we expected an
9445    ack.  Do our best to discard the rest of this packet.  */
9446
9447 void
9448 remote_target::skip_frame ()
9449 {
9450   int c;
9451
9452   while (1)
9453     {
9454       c = readchar (remote_timeout);
9455       switch (c)
9456         {
9457         case SERIAL_TIMEOUT:
9458           /* Nothing we can do.  */
9459           return;
9460         case '#':
9461           /* Discard the two bytes of checksum and stop.  */
9462           c = readchar (remote_timeout);
9463           if (c >= 0)
9464             c = readchar (remote_timeout);
9465
9466           return;
9467         case '*':               /* Run length encoding.  */
9468           /* Discard the repeat count.  */
9469           c = readchar (remote_timeout);
9470           if (c < 0)
9471             return;
9472           break;
9473         default:
9474           /* A regular character.  */
9475           break;
9476         }
9477     }
9478 }
9479
9480 /* Come here after finding the start of the frame.  Collect the rest
9481    into *BUF, verifying the checksum, length, and handling run-length
9482    compression.  NUL terminate the buffer.  If there is not enough room,
9483    expand *BUF using xrealloc.
9484
9485    Returns -1 on error, number of characters in buffer (ignoring the
9486    trailing NULL) on success. (could be extended to return one of the
9487    SERIAL status indications).  */
9488
9489 long
9490 remote_target::read_frame (char **buf_p, long *sizeof_buf)
9491 {
9492   unsigned char csum;
9493   long bc;
9494   int c;
9495   char *buf = *buf_p;
9496   struct remote_state *rs = get_remote_state ();
9497
9498   csum = 0;
9499   bc = 0;
9500
9501   while (1)
9502     {
9503       c = readchar (remote_timeout);
9504       switch (c)
9505         {
9506         case SERIAL_TIMEOUT:
9507           if (remote_debug)
9508             fputs_filtered ("Timeout in mid-packet, retrying\n", gdb_stdlog);
9509           return -1;
9510         case '$':
9511           if (remote_debug)
9512             fputs_filtered ("Saw new packet start in middle of old one\n",
9513                             gdb_stdlog);
9514           return -1;            /* Start a new packet, count retries.  */
9515         case '#':
9516           {
9517             unsigned char pktcsum;
9518             int check_0 = 0;
9519             int check_1 = 0;
9520
9521             buf[bc] = '\0';
9522
9523             check_0 = readchar (remote_timeout);
9524             if (check_0 >= 0)
9525               check_1 = readchar (remote_timeout);
9526
9527             if (check_0 == SERIAL_TIMEOUT || check_1 == SERIAL_TIMEOUT)
9528               {
9529                 if (remote_debug)
9530                   fputs_filtered ("Timeout in checksum, retrying\n",
9531                                   gdb_stdlog);
9532                 return -1;
9533               }
9534             else if (check_0 < 0 || check_1 < 0)
9535               {
9536                 if (remote_debug)
9537                   fputs_filtered ("Communication error in checksum\n",
9538                                   gdb_stdlog);
9539                 return -1;
9540               }
9541
9542             /* Don't recompute the checksum; with no ack packets we
9543                don't have any way to indicate a packet retransmission
9544                is necessary.  */
9545             if (rs->noack_mode)
9546               return bc;
9547
9548             pktcsum = (fromhex (check_0) << 4) | fromhex (check_1);
9549             if (csum == pktcsum)
9550               return bc;
9551
9552             if (remote_debug)
9553               {
9554                 std::string str = escape_buffer (buf, bc);
9555
9556                 fprintf_unfiltered (gdb_stdlog,
9557                                     "Bad checksum, sentsum=0x%x, "
9558                                     "csum=0x%x, buf=%s\n",
9559                                     pktcsum, csum, str.c_str ());
9560               }
9561             /* Number of characters in buffer ignoring trailing
9562                NULL.  */
9563             return -1;
9564           }
9565         case '*':               /* Run length encoding.  */
9566           {
9567             int repeat;
9568
9569             csum += c;
9570             c = readchar (remote_timeout);
9571             csum += c;
9572             repeat = c - ' ' + 3;       /* Compute repeat count.  */
9573
9574             /* The character before ``*'' is repeated.  */
9575
9576             if (repeat > 0 && repeat <= 255 && bc > 0)
9577               {
9578                 if (bc + repeat - 1 >= *sizeof_buf - 1)
9579                   {
9580                     /* Make some more room in the buffer.  */
9581                     *sizeof_buf += repeat;
9582                     *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9583                     buf = *buf_p;
9584                   }
9585
9586                 memset (&buf[bc], buf[bc - 1], repeat);
9587                 bc += repeat;
9588                 continue;
9589               }
9590
9591             buf[bc] = '\0';
9592             printf_filtered (_("Invalid run length encoding: %s\n"), buf);
9593             return -1;
9594           }
9595         default:
9596           if (bc >= *sizeof_buf - 1)
9597             {
9598               /* Make some more room in the buffer.  */
9599               *sizeof_buf *= 2;
9600               *buf_p = (char *) xrealloc (*buf_p, *sizeof_buf);
9601               buf = *buf_p;
9602             }
9603
9604           buf[bc++] = c;
9605           csum += c;
9606           continue;
9607         }
9608     }
9609 }
9610
9611 /* Read a packet from the remote machine, with error checking, and
9612    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9613    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9614    rather than timing out; this is used (in synchronous mode) to wait
9615    for a target that is is executing user code to stop.  */
9616 /* FIXME: ezannoni 2000-02-01 this wrapper is necessary so that we
9617    don't have to change all the calls to getpkt to deal with the
9618    return value, because at the moment I don't know what the right
9619    thing to do it for those.  */
9620
9621 void
9622 remote_target::getpkt (char **buf, long *sizeof_buf, int forever)
9623 {
9624   getpkt_sane (buf, sizeof_buf, forever);
9625 }
9626
9627
9628 /* Read a packet from the remote machine, with error checking, and
9629    store it in *BUF.  Resize *BUF using xrealloc if necessary to hold
9630    the result, and update *SIZEOF_BUF.  If FOREVER, wait forever
9631    rather than timing out; this is used (in synchronous mode) to wait
9632    for a target that is is executing user code to stop.  If FOREVER ==
9633    0, this function is allowed to time out gracefully and return an
9634    indication of this to the caller.  Otherwise return the number of
9635    bytes read.  If EXPECTING_NOTIF, consider receiving a notification
9636    enough reason to return to the caller.  *IS_NOTIF is an output
9637    boolean that indicates whether *BUF holds a notification or not
9638    (a regular packet).  */
9639
9640 int
9641 remote_target::getpkt_or_notif_sane_1 (char **buf, long *sizeof_buf,
9642                                        int forever, int expecting_notif,
9643                                        int *is_notif)
9644 {
9645   struct remote_state *rs = get_remote_state ();
9646   int c;
9647   int tries;
9648   int timeout;
9649   int val = -1;
9650
9651   /* We're reading a new response.  Make sure we don't look at a
9652      previously cached response.  */
9653   rs->cached_wait_status = 0;
9654
9655   strcpy (*buf, "timeout");
9656
9657   if (forever)
9658     timeout = watchdog > 0 ? watchdog : -1;
9659   else if (expecting_notif)
9660     timeout = 0; /* There should already be a char in the buffer.  If
9661                     not, bail out.  */
9662   else
9663     timeout = remote_timeout;
9664
9665 #define MAX_TRIES 3
9666
9667   /* Process any number of notifications, and then return when
9668      we get a packet.  */
9669   for (;;)
9670     {
9671       /* If we get a timeout or bad checksum, retry up to MAX_TRIES
9672          times.  */
9673       for (tries = 1; tries <= MAX_TRIES; tries++)
9674         {
9675           /* This can loop forever if the remote side sends us
9676              characters continuously, but if it pauses, we'll get
9677              SERIAL_TIMEOUT from readchar because of timeout.  Then
9678              we'll count that as a retry.
9679
9680              Note that even when forever is set, we will only wait
9681              forever prior to the start of a packet.  After that, we
9682              expect characters to arrive at a brisk pace.  They should
9683              show up within remote_timeout intervals.  */
9684           do
9685             c = readchar (timeout);
9686           while (c != SERIAL_TIMEOUT && c != '$' && c != '%');
9687
9688           if (c == SERIAL_TIMEOUT)
9689             {
9690               if (expecting_notif)
9691                 return -1; /* Don't complain, it's normal to not get
9692                               anything in this case.  */
9693
9694               if (forever)      /* Watchdog went off?  Kill the target.  */
9695                 {
9696                   remote_unpush_target ();
9697                   throw_error (TARGET_CLOSE_ERROR,
9698                                _("Watchdog timeout has expired.  "
9699                                  "Target detached."));
9700                 }
9701               if (remote_debug)
9702                 fputs_filtered ("Timed out.\n", gdb_stdlog);
9703             }
9704           else
9705             {
9706               /* We've found the start of a packet or notification.
9707                  Now collect the data.  */
9708               val = read_frame (buf, sizeof_buf);
9709               if (val >= 0)
9710                 break;
9711             }
9712
9713           remote_serial_write ("-", 1);
9714         }
9715
9716       if (tries > MAX_TRIES)
9717         {
9718           /* We have tried hard enough, and just can't receive the
9719              packet/notification.  Give up.  */
9720           printf_unfiltered (_("Ignoring packet error, continuing...\n"));
9721
9722           /* Skip the ack char if we're in no-ack mode.  */
9723           if (!rs->noack_mode)
9724             remote_serial_write ("+", 1);
9725           return -1;
9726         }
9727
9728       /* If we got an ordinary packet, return that to our caller.  */
9729       if (c == '$')
9730         {
9731           if (remote_debug)
9732             {
9733               std::string str
9734                 = escape_buffer (*buf,
9735                                  std::min (val, REMOTE_DEBUG_MAX_CHAR));
9736
9737               fprintf_unfiltered (gdb_stdlog, "Packet received: %s",
9738                                   str.c_str ());
9739
9740               if (val > REMOTE_DEBUG_MAX_CHAR)
9741                 fprintf_unfiltered (gdb_stdlog, "[%d bytes omitted]",
9742                                     val - REMOTE_DEBUG_MAX_CHAR);
9743
9744               fprintf_unfiltered (gdb_stdlog, "\n");
9745             }
9746
9747           /* Skip the ack char if we're in no-ack mode.  */
9748           if (!rs->noack_mode)
9749             remote_serial_write ("+", 1);
9750           if (is_notif != NULL)
9751             *is_notif = 0;
9752           return val;
9753         }
9754
9755        /* If we got a notification, handle it, and go back to looking
9756          for a packet.  */
9757       else
9758         {
9759           gdb_assert (c == '%');
9760
9761           if (remote_debug)
9762             {
9763               std::string str = escape_buffer (*buf, val);
9764
9765               fprintf_unfiltered (gdb_stdlog,
9766                                   "  Notification received: %s\n",
9767                                   str.c_str ());
9768             }
9769           if (is_notif != NULL)
9770             *is_notif = 1;
9771
9772           handle_notification (rs->notif_state, *buf);
9773
9774           /* Notifications require no acknowledgement.  */
9775
9776           if (expecting_notif)
9777             return val;
9778         }
9779     }
9780 }
9781
9782 int
9783 remote_target::getpkt_sane (char **buf, long *sizeof_buf, int forever)
9784 {
9785   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 0, NULL);
9786 }
9787
9788 int
9789 remote_target::getpkt_or_notif_sane (char **buf, long *sizeof_buf, int forever,
9790                                      int *is_notif)
9791 {
9792   return getpkt_or_notif_sane_1 (buf, sizeof_buf, forever, 1,
9793                                  is_notif);
9794 }
9795
9796 /* Check whether EVENT is a fork event for the process specified
9797    by the pid passed in DATA, and if it is, kill the fork child.  */
9798
9799 int
9800 remote_kill_child_of_pending_fork (QUEUE (stop_reply_p) *q,
9801                                    QUEUE_ITER (stop_reply_p) *iter,
9802                                    stop_reply_p event,
9803                                    void *data)
9804 {
9805   struct queue_iter_param *param = (struct queue_iter_param *) data;
9806   int parent_pid = *(int *) param->input;
9807
9808   if (is_pending_fork_parent (&event->ws, parent_pid, event->ptid))
9809     {
9810       remote_target *remote = param->remote;
9811       int child_pid = ptid_get_pid (event->ws.value.related_pid);
9812       int res;
9813
9814       res = remote->remote_vkill (child_pid);
9815       if (res != 0)
9816         error (_("Can't kill fork child process %d"), child_pid);
9817     }
9818
9819   return 1;
9820 }
9821
9822 /* Kill any new fork children of process PID that haven't been
9823    processed by follow_fork.  */
9824
9825 void
9826 remote_target::kill_new_fork_children (int pid)
9827 {
9828   remote_state *rs = get_remote_state ();
9829   struct thread_info *thread;
9830   struct notif_client *notif = &notif_client_stop;
9831   struct queue_iter_param param;
9832
9833   /* Kill the fork child threads of any threads in process PID
9834      that are stopped at a fork event.  */
9835   ALL_NON_EXITED_THREADS (thread)
9836     {
9837       struct target_waitstatus *ws = &thread->pending_follow;
9838
9839       if (is_pending_fork_parent (ws, pid, thread->ptid))
9840         {
9841           int child_pid = ptid_get_pid (ws->value.related_pid);
9842           int res;
9843
9844           res = remote_vkill (child_pid);
9845           if (res != 0)
9846             error (_("Can't kill fork child process %d"), child_pid);
9847         }
9848     }
9849
9850   /* Check for any pending fork events (not reported or processed yet)
9851      in process PID and kill those fork child threads as well.  */
9852   remote_notif_get_pending_events (notif);
9853   param.remote = this;
9854   param.input = &pid;
9855   param.output = NULL;
9856   QUEUE_iterate (stop_reply_p, rs->stop_reply_queue,
9857                  remote_kill_child_of_pending_fork, &param);
9858 }
9859
9860 \f
9861 /* Target hook to kill the current inferior.  */
9862
9863 void
9864 remote_target::kill ()
9865 {
9866   int res = -1;
9867   int pid = ptid_get_pid (inferior_ptid);
9868   struct remote_state *rs = get_remote_state ();
9869
9870   if (packet_support (PACKET_vKill) != PACKET_DISABLE)
9871     {
9872       /* If we're stopped while forking and we haven't followed yet,
9873          kill the child task.  We need to do this before killing the
9874          parent task because if this is a vfork then the parent will
9875          be sleeping.  */
9876       kill_new_fork_children (pid);
9877
9878       res = remote_vkill (pid);
9879       if (res == 0)
9880         {
9881           target_mourn_inferior (inferior_ptid);
9882           return;
9883         }
9884     }
9885
9886   /* If we are in 'target remote' mode and we are killing the only
9887      inferior, then we will tell gdbserver to exit and unpush the
9888      target.  */
9889   if (res == -1 && !remote_multi_process_p (rs)
9890       && number_of_live_inferiors () == 1)
9891     {
9892       remote_kill_k ();
9893
9894       /* We've killed the remote end, we get to mourn it.  If we are
9895          not in extended mode, mourning the inferior also unpushes
9896          remote_ops from the target stack, which closes the remote
9897          connection.  */
9898       target_mourn_inferior (inferior_ptid);
9899
9900       return;
9901     }
9902
9903   error (_("Can't kill process"));
9904 }
9905
9906 /* Send a kill request to the target using the 'vKill' packet.  */
9907
9908 int
9909 remote_target::remote_vkill (int pid)
9910 {
9911   if (packet_support (PACKET_vKill) == PACKET_DISABLE)
9912     return -1;
9913
9914   remote_state *rs = get_remote_state ();
9915
9916   /* Tell the remote target to detach.  */
9917   xsnprintf (rs->buf, get_remote_packet_size (), "vKill;%x", pid);
9918   putpkt (rs->buf);
9919   getpkt (&rs->buf, &rs->buf_size, 0);
9920
9921   switch (packet_ok (rs->buf,
9922                      &remote_protocol_packets[PACKET_vKill]))
9923     {
9924     case PACKET_OK:
9925       return 0;
9926     case PACKET_ERROR:
9927       return 1;
9928     case PACKET_UNKNOWN:
9929       return -1;
9930     default:
9931       internal_error (__FILE__, __LINE__, _("Bad result from packet_ok"));
9932     }
9933 }
9934
9935 /* Send a kill request to the target using the 'k' packet.  */
9936
9937 void
9938 remote_target::remote_kill_k ()
9939 {
9940   /* Catch errors so the user can quit from gdb even when we
9941      aren't on speaking terms with the remote system.  */
9942   TRY
9943     {
9944       putpkt ("k");
9945     }
9946   CATCH (ex, RETURN_MASK_ERROR)
9947     {
9948       if (ex.error == TARGET_CLOSE_ERROR)
9949         {
9950           /* If we got an (EOF) error that caused the target
9951              to go away, then we're done, that's what we wanted.
9952              "k" is susceptible to cause a premature EOF, given
9953              that the remote server isn't actually required to
9954              reply to "k", and it can happen that it doesn't
9955              even get to reply ACK to the "k".  */
9956           return;
9957         }
9958
9959       /* Otherwise, something went wrong.  We didn't actually kill
9960          the target.  Just propagate the exception, and let the
9961          user or higher layers decide what to do.  */
9962       throw_exception (ex);
9963     }
9964   END_CATCH
9965 }
9966
9967 void
9968 remote_target::mourn_inferior ()
9969 {
9970   struct remote_state *rs = get_remote_state ();
9971
9972   /* We're no longer interested in notification events of an inferior
9973      that exited or was killed/detached.  */
9974   discard_pending_stop_replies (current_inferior ());
9975
9976   /* In 'target remote' mode with one inferior, we close the connection.  */
9977   if (!rs->extended && number_of_live_inferiors () <= 1)
9978     {
9979       unpush_target (this);
9980
9981       /* remote_close takes care of doing most of the clean up.  */
9982       generic_mourn_inferior ();
9983       return;
9984     }
9985
9986   /* In case we got here due to an error, but we're going to stay
9987      connected.  */
9988   rs->waiting_for_stop_reply = 0;
9989
9990   /* If the current general thread belonged to the process we just
9991      detached from or has exited, the remote side current general
9992      thread becomes undefined.  Considering a case like this:
9993
9994      - We just got here due to a detach.
9995      - The process that we're detaching from happens to immediately
9996        report a global breakpoint being hit in non-stop mode, in the
9997        same thread we had selected before.
9998      - GDB attaches to this process again.
9999      - This event happens to be the next event we handle.
10000
10001      GDB would consider that the current general thread didn't need to
10002      be set on the stub side (with Hg), since for all it knew,
10003      GENERAL_THREAD hadn't changed.
10004
10005      Notice that although in all-stop mode, the remote server always
10006      sets the current thread to the thread reporting the stop event,
10007      that doesn't happen in non-stop mode; in non-stop, the stub *must
10008      not* change the current thread when reporting a breakpoint hit,
10009      due to the decoupling of event reporting and event handling.
10010
10011      To keep things simple, we always invalidate our notion of the
10012      current thread.  */
10013   record_currthread (rs, minus_one_ptid);
10014
10015   /* Call common code to mark the inferior as not running.  */
10016   generic_mourn_inferior ();
10017
10018   if (!have_inferiors ())
10019     {
10020       if (!remote_multi_process_p (rs))
10021         {
10022           /* Check whether the target is running now - some remote stubs
10023              automatically restart after kill.  */
10024           putpkt ("?");
10025           getpkt (&rs->buf, &rs->buf_size, 0);
10026
10027           if (rs->buf[0] == 'S' || rs->buf[0] == 'T')
10028             {
10029               /* Assume that the target has been restarted.  Set
10030                  inferior_ptid so that bits of core GDB realizes
10031                  there's something here, e.g., so that the user can
10032                  say "kill" again.  */
10033               inferior_ptid = magic_null_ptid;
10034             }
10035         }
10036     }
10037 }
10038
10039 bool
10040 extended_remote_target::supports_disable_randomization ()
10041 {
10042   return packet_support (PACKET_QDisableRandomization) == PACKET_ENABLE;
10043 }
10044
10045 void
10046 remote_target::extended_remote_disable_randomization (int val)
10047 {
10048   struct remote_state *rs = get_remote_state ();
10049   char *reply;
10050
10051   xsnprintf (rs->buf, get_remote_packet_size (), "QDisableRandomization:%x",
10052              val);
10053   putpkt (rs->buf);
10054   reply = remote_get_noisy_reply ();
10055   if (*reply == '\0')
10056     error (_("Target does not support QDisableRandomization."));
10057   if (strcmp (reply, "OK") != 0)
10058     error (_("Bogus QDisableRandomization reply from target: %s"), reply);
10059 }
10060
10061 int
10062 remote_target::extended_remote_run (const std::string &args)
10063 {
10064   struct remote_state *rs = get_remote_state ();
10065   int len;
10066   const char *remote_exec_file = get_remote_exec_file ();
10067
10068   /* If the user has disabled vRun support, or we have detected that
10069      support is not available, do not try it.  */
10070   if (packet_support (PACKET_vRun) == PACKET_DISABLE)
10071     return -1;
10072
10073   strcpy (rs->buf, "vRun;");
10074   len = strlen (rs->buf);
10075
10076   if (strlen (remote_exec_file) * 2 + len >= get_remote_packet_size ())
10077     error (_("Remote file name too long for run packet"));
10078   len += 2 * bin2hex ((gdb_byte *) remote_exec_file, rs->buf + len,
10079                       strlen (remote_exec_file));
10080
10081   if (!args.empty ())
10082     {
10083       int i;
10084
10085       gdb_argv argv (args.c_str ());
10086       for (i = 0; argv[i] != NULL; i++)
10087         {
10088           if (strlen (argv[i]) * 2 + 1 + len >= get_remote_packet_size ())
10089             error (_("Argument list too long for run packet"));
10090           rs->buf[len++] = ';';
10091           len += 2 * bin2hex ((gdb_byte *) argv[i], rs->buf + len,
10092                               strlen (argv[i]));
10093         }
10094     }
10095
10096   rs->buf[len++] = '\0';
10097
10098   putpkt (rs->buf);
10099   getpkt (&rs->buf, &rs->buf_size, 0);
10100
10101   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_vRun]))
10102     {
10103     case PACKET_OK:
10104       /* We have a wait response.  All is well.  */
10105       return 0;
10106     case PACKET_UNKNOWN:
10107       return -1;
10108     case PACKET_ERROR:
10109       if (remote_exec_file[0] == '\0')
10110         error (_("Running the default executable on the remote target failed; "
10111                  "try \"set remote exec-file\"?"));
10112       else
10113         error (_("Running \"%s\" on the remote target failed"),
10114                remote_exec_file);
10115     default:
10116       gdb_assert_not_reached (_("bad switch"));
10117     }
10118 }
10119
10120 /* Helper function to send set/unset environment packets.  ACTION is
10121    either "set" or "unset".  PACKET is either "QEnvironmentHexEncoded"
10122    or "QEnvironmentUnsetVariable".  VALUE is the variable to be
10123    sent.  */
10124
10125 void
10126 remote_target::send_environment_packet (const char *action,
10127                                         const char *packet,
10128                                         const char *value)
10129 {
10130   remote_state *rs = get_remote_state ();
10131
10132   /* Convert the environment variable to an hex string, which
10133      is the best format to be transmitted over the wire.  */
10134   std::string encoded_value = bin2hex ((const gdb_byte *) value,
10135                                          strlen (value));
10136
10137   xsnprintf (rs->buf, get_remote_packet_size (),
10138              "%s:%s", packet, encoded_value.c_str ());
10139
10140   putpkt (rs->buf);
10141   getpkt (&rs->buf, &rs->buf_size, 0);
10142   if (strcmp (rs->buf, "OK") != 0)
10143     warning (_("Unable to %s environment variable '%s' on remote."),
10144              action, value);
10145 }
10146
10147 /* Helper function to handle the QEnvironment* packets.  */
10148
10149 void
10150 remote_target::extended_remote_environment_support ()
10151 {
10152   remote_state *rs = get_remote_state ();
10153
10154   if (packet_support (PACKET_QEnvironmentReset) != PACKET_DISABLE)
10155     {
10156       putpkt ("QEnvironmentReset");
10157       getpkt (&rs->buf, &rs->buf_size, 0);
10158       if (strcmp (rs->buf, "OK") != 0)
10159         warning (_("Unable to reset environment on remote."));
10160     }
10161
10162   gdb_environ *e = &current_inferior ()->environment;
10163
10164   if (packet_support (PACKET_QEnvironmentHexEncoded) != PACKET_DISABLE)
10165     for (const std::string &el : e->user_set_env ())
10166       send_environment_packet ("set", "QEnvironmentHexEncoded",
10167                                el.c_str ());
10168
10169   if (packet_support (PACKET_QEnvironmentUnset) != PACKET_DISABLE)
10170     for (const std::string &el : e->user_unset_env ())
10171       send_environment_packet ("unset", "QEnvironmentUnset", el.c_str ());
10172 }
10173
10174 /* Helper function to set the current working directory for the
10175    inferior in the remote target.  */
10176
10177 void
10178 remote_target::extended_remote_set_inferior_cwd ()
10179 {
10180   if (packet_support (PACKET_QSetWorkingDir) != PACKET_DISABLE)
10181     {
10182       const char *inferior_cwd = get_inferior_cwd ();
10183       remote_state *rs = get_remote_state ();
10184
10185       if (inferior_cwd != NULL)
10186         {
10187           std::string hexpath = bin2hex ((const gdb_byte *) inferior_cwd,
10188                                          strlen (inferior_cwd));
10189
10190           xsnprintf (rs->buf, get_remote_packet_size (),
10191                      "QSetWorkingDir:%s", hexpath.c_str ());
10192         }
10193       else
10194         {
10195           /* An empty inferior_cwd means that the user wants us to
10196              reset the remote server's inferior's cwd.  */
10197           xsnprintf (rs->buf, get_remote_packet_size (),
10198                      "QSetWorkingDir:");
10199         }
10200
10201       putpkt (rs->buf);
10202       getpkt (&rs->buf, &rs->buf_size, 0);
10203       if (packet_ok (rs->buf,
10204                      &remote_protocol_packets[PACKET_QSetWorkingDir])
10205           != PACKET_OK)
10206         error (_("\
10207 Remote replied unexpectedly while setting the inferior's working\n\
10208 directory: %s"),
10209                rs->buf);
10210
10211     }
10212 }
10213
10214 /* In the extended protocol we want to be able to do things like
10215    "run" and have them basically work as expected.  So we need
10216    a special create_inferior function.  We support changing the
10217    executable file and the command line arguments, but not the
10218    environment.  */
10219
10220 void
10221 extended_remote_target::create_inferior (const char *exec_file,
10222                                          const std::string &args,
10223                                          char **env, int from_tty)
10224 {
10225   int run_worked;
10226   char *stop_reply;
10227   struct remote_state *rs = get_remote_state ();
10228   const char *remote_exec_file = get_remote_exec_file ();
10229
10230   /* If running asynchronously, register the target file descriptor
10231      with the event loop.  */
10232   if (target_can_async_p ())
10233     target_async (1);
10234
10235   /* Disable address space randomization if requested (and supported).  */
10236   if (supports_disable_randomization ())
10237     extended_remote_disable_randomization (disable_randomization);
10238
10239   /* If startup-with-shell is on, we inform gdbserver to start the
10240      remote inferior using a shell.  */
10241   if (packet_support (PACKET_QStartupWithShell) != PACKET_DISABLE)
10242     {
10243       xsnprintf (rs->buf, get_remote_packet_size (),
10244                  "QStartupWithShell:%d", startup_with_shell ? 1 : 0);
10245       putpkt (rs->buf);
10246       getpkt (&rs->buf, &rs->buf_size, 0);
10247       if (strcmp (rs->buf, "OK") != 0)
10248         error (_("\
10249 Remote replied unexpectedly while setting startup-with-shell: %s"),
10250                rs->buf);
10251     }
10252
10253   extended_remote_environment_support ();
10254
10255   extended_remote_set_inferior_cwd ();
10256
10257   /* Now restart the remote server.  */
10258   run_worked = extended_remote_run (args) != -1;
10259   if (!run_worked)
10260     {
10261       /* vRun was not supported.  Fail if we need it to do what the
10262          user requested.  */
10263       if (remote_exec_file[0])
10264         error (_("Remote target does not support \"set remote exec-file\""));
10265       if (!args.empty ())
10266         error (_("Remote target does not support \"set args\" or run <ARGS>"));
10267
10268       /* Fall back to "R".  */
10269       extended_remote_restart ();
10270     }
10271
10272   if (!have_inferiors ())
10273     {
10274       /* Clean up from the last time we ran, before we mark the target
10275          running again.  This will mark breakpoints uninserted, and
10276          get_offsets may insert breakpoints.  */
10277       init_thread_list ();
10278       init_wait_for_inferior ();
10279     }
10280
10281   /* vRun's success return is a stop reply.  */
10282   stop_reply = run_worked ? rs->buf : NULL;
10283   add_current_inferior_and_thread (stop_reply);
10284
10285   /* Get updated offsets, if the stub uses qOffsets.  */
10286   get_offsets ();
10287 }
10288 \f
10289
10290 /* Given a location's target info BP_TGT and the packet buffer BUF,  output
10291    the list of conditions (in agent expression bytecode format), if any, the
10292    target needs to evaluate.  The output is placed into the packet buffer
10293    started from BUF and ended at BUF_END.  */
10294
10295 static int
10296 remote_add_target_side_condition (struct gdbarch *gdbarch,
10297                                   struct bp_target_info *bp_tgt, char *buf,
10298                                   char *buf_end)
10299 {
10300   if (bp_tgt->conditions.empty ())
10301     return 0;
10302
10303   buf += strlen (buf);
10304   xsnprintf (buf, buf_end - buf, "%s", ";");
10305   buf++;
10306
10307   /* Send conditions to the target.  */
10308   for (agent_expr *aexpr : bp_tgt->conditions)
10309     {
10310       xsnprintf (buf, buf_end - buf, "X%x,", aexpr->len);
10311       buf += strlen (buf);
10312       for (int i = 0; i < aexpr->len; ++i)
10313         buf = pack_hex_byte (buf, aexpr->buf[i]);
10314       *buf = '\0';
10315     }
10316   return 0;
10317 }
10318
10319 static void
10320 remote_add_target_side_commands (struct gdbarch *gdbarch,
10321                                  struct bp_target_info *bp_tgt, char *buf)
10322 {
10323   if (bp_tgt->tcommands.empty ())
10324     return;
10325
10326   buf += strlen (buf);
10327
10328   sprintf (buf, ";cmds:%x,", bp_tgt->persist);
10329   buf += strlen (buf);
10330
10331   /* Concatenate all the agent expressions that are commands into the
10332      cmds parameter.  */
10333   for (agent_expr *aexpr : bp_tgt->tcommands)
10334     {
10335       sprintf (buf, "X%x,", aexpr->len);
10336       buf += strlen (buf);
10337       for (int i = 0; i < aexpr->len; ++i)
10338         buf = pack_hex_byte (buf, aexpr->buf[i]);
10339       *buf = '\0';
10340     }
10341 }
10342
10343 /* Insert a breakpoint.  On targets that have software breakpoint
10344    support, we ask the remote target to do the work; on targets
10345    which don't, we insert a traditional memory breakpoint.  */
10346
10347 int
10348 remote_target::insert_breakpoint (struct gdbarch *gdbarch,
10349                                   struct bp_target_info *bp_tgt)
10350 {
10351   /* Try the "Z" s/w breakpoint packet if it is not already disabled.
10352      If it succeeds, then set the support to PACKET_ENABLE.  If it
10353      fails, and the user has explicitly requested the Z support then
10354      report an error, otherwise, mark it disabled and go on.  */
10355
10356   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10357     {
10358       CORE_ADDR addr = bp_tgt->reqstd_address;
10359       struct remote_state *rs;
10360       char *p, *endbuf;
10361
10362       /* Make sure the remote is pointing at the right process, if
10363          necessary.  */
10364       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10365         set_general_process ();
10366
10367       rs = get_remote_state ();
10368       p = rs->buf;
10369       endbuf = rs->buf + get_remote_packet_size ();
10370
10371       *(p++) = 'Z';
10372       *(p++) = '0';
10373       *(p++) = ',';
10374       addr = (ULONGEST) remote_address_masked (addr);
10375       p += hexnumstr (p, addr);
10376       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10377
10378       if (supports_evaluation_of_breakpoint_conditions ())
10379         remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10380
10381       if (can_run_breakpoint_commands ())
10382         remote_add_target_side_commands (gdbarch, bp_tgt, p);
10383
10384       putpkt (rs->buf);
10385       getpkt (&rs->buf, &rs->buf_size, 0);
10386
10387       switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0]))
10388         {
10389         case PACKET_ERROR:
10390           return -1;
10391         case PACKET_OK:
10392           return 0;
10393         case PACKET_UNKNOWN:
10394           break;
10395         }
10396     }
10397
10398   /* If this breakpoint has target-side commands but this stub doesn't
10399      support Z0 packets, throw error.  */
10400   if (!bp_tgt->tcommands.empty ())
10401     throw_error (NOT_SUPPORTED_ERROR, _("\
10402 Target doesn't support breakpoints that have target side commands."));
10403
10404   return memory_insert_breakpoint (this, gdbarch, bp_tgt);
10405 }
10406
10407 int
10408 remote_target::remove_breakpoint (struct gdbarch *gdbarch,
10409                                   struct bp_target_info *bp_tgt,
10410                                   enum remove_bp_reason reason)
10411 {
10412   CORE_ADDR addr = bp_tgt->placed_address;
10413   struct remote_state *rs = get_remote_state ();
10414
10415   if (packet_support (PACKET_Z0) != PACKET_DISABLE)
10416     {
10417       char *p = rs->buf;
10418       char *endbuf = rs->buf + get_remote_packet_size ();
10419
10420       /* Make sure the remote is pointing at the right process, if
10421          necessary.  */
10422       if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10423         set_general_process ();
10424
10425       *(p++) = 'z';
10426       *(p++) = '0';
10427       *(p++) = ',';
10428
10429       addr = (ULONGEST) remote_address_masked (bp_tgt->placed_address);
10430       p += hexnumstr (p, addr);
10431       xsnprintf (p, endbuf - p, ",%d", bp_tgt->kind);
10432
10433       putpkt (rs->buf);
10434       getpkt (&rs->buf, &rs->buf_size, 0);
10435
10436       return (rs->buf[0] == 'E');
10437     }
10438
10439   return memory_remove_breakpoint (this, gdbarch, bp_tgt, reason);
10440 }
10441
10442 static enum Z_packet_type
10443 watchpoint_to_Z_packet (int type)
10444 {
10445   switch (type)
10446     {
10447     case hw_write:
10448       return Z_PACKET_WRITE_WP;
10449       break;
10450     case hw_read:
10451       return Z_PACKET_READ_WP;
10452       break;
10453     case hw_access:
10454       return Z_PACKET_ACCESS_WP;
10455       break;
10456     default:
10457       internal_error (__FILE__, __LINE__,
10458                       _("hw_bp_to_z: bad watchpoint type %d"), type);
10459     }
10460 }
10461
10462 int
10463 remote_target::insert_watchpoint (CORE_ADDR addr, int len,
10464                                   enum target_hw_bp_type type, struct expression *cond)
10465 {
10466   struct remote_state *rs = get_remote_state ();
10467   char *endbuf = rs->buf + get_remote_packet_size ();
10468   char *p;
10469   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10470
10471   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10472     return 1;
10473
10474   /* Make sure the remote is pointing at the right process, if
10475      necessary.  */
10476   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10477     set_general_process ();
10478
10479   xsnprintf (rs->buf, endbuf - rs->buf, "Z%x,", packet);
10480   p = strchr (rs->buf, '\0');
10481   addr = remote_address_masked (addr);
10482   p += hexnumstr (p, (ULONGEST) addr);
10483   xsnprintf (p, endbuf - p, ",%x", len);
10484
10485   putpkt (rs->buf);
10486   getpkt (&rs->buf, &rs->buf_size, 0);
10487
10488   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10489     {
10490     case PACKET_ERROR:
10491       return -1;
10492     case PACKET_UNKNOWN:
10493       return 1;
10494     case PACKET_OK:
10495       return 0;
10496     }
10497   internal_error (__FILE__, __LINE__,
10498                   _("remote_insert_watchpoint: reached end of function"));
10499 }
10500
10501 bool
10502 remote_target::watchpoint_addr_within_range (CORE_ADDR addr,
10503                                              CORE_ADDR start, int length)
10504 {
10505   CORE_ADDR diff = remote_address_masked (addr - start);
10506
10507   return diff < length;
10508 }
10509
10510
10511 int
10512 remote_target::remove_watchpoint (CORE_ADDR addr, int len,
10513                                   enum target_hw_bp_type type, struct expression *cond)
10514 {
10515   struct remote_state *rs = get_remote_state ();
10516   char *endbuf = rs->buf + get_remote_packet_size ();
10517   char *p;
10518   enum Z_packet_type packet = watchpoint_to_Z_packet (type);
10519
10520   if (packet_support (PACKET_Z0 + packet) == PACKET_DISABLE)
10521     return -1;
10522
10523   /* Make sure the remote is pointing at the right process, if
10524      necessary.  */
10525   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10526     set_general_process ();
10527
10528   xsnprintf (rs->buf, endbuf - rs->buf, "z%x,", packet);
10529   p = strchr (rs->buf, '\0');
10530   addr = remote_address_masked (addr);
10531   p += hexnumstr (p, (ULONGEST) addr);
10532   xsnprintf (p, endbuf - p, ",%x", len);
10533   putpkt (rs->buf);
10534   getpkt (&rs->buf, &rs->buf_size, 0);
10535
10536   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z0 + packet]))
10537     {
10538     case PACKET_ERROR:
10539     case PACKET_UNKNOWN:
10540       return -1;
10541     case PACKET_OK:
10542       return 0;
10543     }
10544   internal_error (__FILE__, __LINE__,
10545                   _("remote_remove_watchpoint: reached end of function"));
10546 }
10547
10548
10549 int remote_hw_watchpoint_limit = -1;
10550 int remote_hw_watchpoint_length_limit = -1;
10551 int remote_hw_breakpoint_limit = -1;
10552
10553 int
10554 remote_target::region_ok_for_hw_watchpoint (CORE_ADDR addr, int len)
10555 {
10556   if (remote_hw_watchpoint_length_limit == 0)
10557     return 0;
10558   else if (remote_hw_watchpoint_length_limit < 0)
10559     return 1;
10560   else if (len <= remote_hw_watchpoint_length_limit)
10561     return 1;
10562   else
10563     return 0;
10564 }
10565
10566 int
10567 remote_target::can_use_hw_breakpoint (enum bptype type, int cnt, int ot)
10568 {
10569   if (type == bp_hardware_breakpoint)
10570     {
10571       if (remote_hw_breakpoint_limit == 0)
10572         return 0;
10573       else if (remote_hw_breakpoint_limit < 0)
10574         return 1;
10575       else if (cnt <= remote_hw_breakpoint_limit)
10576         return 1;
10577     }
10578   else
10579     {
10580       if (remote_hw_watchpoint_limit == 0)
10581         return 0;
10582       else if (remote_hw_watchpoint_limit < 0)
10583         return 1;
10584       else if (ot)
10585         return -1;
10586       else if (cnt <= remote_hw_watchpoint_limit)
10587         return 1;
10588     }
10589   return -1;
10590 }
10591
10592 /* The to_stopped_by_sw_breakpoint method of target remote.  */
10593
10594 bool
10595 remote_target::stopped_by_sw_breakpoint ()
10596 {
10597   struct thread_info *thread = inferior_thread ();
10598
10599   return (thread->priv != NULL
10600           && (get_remote_thread_info (thread)->stop_reason
10601               == TARGET_STOPPED_BY_SW_BREAKPOINT));
10602 }
10603
10604 /* The to_supports_stopped_by_sw_breakpoint method of target
10605    remote.  */
10606
10607 bool
10608 remote_target::supports_stopped_by_sw_breakpoint ()
10609 {
10610   return (packet_support (PACKET_swbreak_feature) == PACKET_ENABLE);
10611 }
10612
10613 /* The to_stopped_by_hw_breakpoint method of target remote.  */
10614
10615 bool
10616 remote_target::stopped_by_hw_breakpoint ()
10617 {
10618   struct thread_info *thread = inferior_thread ();
10619
10620   return (thread->priv != NULL
10621           && (get_remote_thread_info (thread)->stop_reason
10622               == TARGET_STOPPED_BY_HW_BREAKPOINT));
10623 }
10624
10625 /* The to_supports_stopped_by_hw_breakpoint method of target
10626    remote.  */
10627
10628 bool
10629 remote_target::supports_stopped_by_hw_breakpoint ()
10630 {
10631   return (packet_support (PACKET_hwbreak_feature) == PACKET_ENABLE);
10632 }
10633
10634 bool
10635 remote_target::stopped_by_watchpoint ()
10636 {
10637   struct thread_info *thread = inferior_thread ();
10638
10639   return (thread->priv != NULL
10640           && (get_remote_thread_info (thread)->stop_reason
10641               == TARGET_STOPPED_BY_WATCHPOINT));
10642 }
10643
10644 bool
10645 remote_target::stopped_data_address (CORE_ADDR *addr_p)
10646 {
10647   struct thread_info *thread = inferior_thread ();
10648
10649   if (thread->priv != NULL
10650       && (get_remote_thread_info (thread)->stop_reason
10651           == TARGET_STOPPED_BY_WATCHPOINT))
10652     {
10653       *addr_p = get_remote_thread_info (thread)->watch_data_address;
10654       return true;
10655     }
10656
10657   return false;
10658 }
10659
10660
10661 int
10662 remote_target::insert_hw_breakpoint (struct gdbarch *gdbarch,
10663                                      struct bp_target_info *bp_tgt)
10664 {
10665   CORE_ADDR addr = bp_tgt->reqstd_address;
10666   struct remote_state *rs;
10667   char *p, *endbuf;
10668   char *message;
10669
10670   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10671     return -1;
10672
10673   /* Make sure the remote is pointing at the right process, if
10674      necessary.  */
10675   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10676     set_general_process ();
10677
10678   rs = get_remote_state ();
10679   p = rs->buf;
10680   endbuf = rs->buf + get_remote_packet_size ();
10681
10682   *(p++) = 'Z';
10683   *(p++) = '1';
10684   *(p++) = ',';
10685
10686   addr = remote_address_masked (addr);
10687   p += hexnumstr (p, (ULONGEST) addr);
10688   xsnprintf (p, endbuf - p, ",%x", bp_tgt->kind);
10689
10690   if (supports_evaluation_of_breakpoint_conditions ())
10691     remote_add_target_side_condition (gdbarch, bp_tgt, p, endbuf);
10692
10693   if (can_run_breakpoint_commands ())
10694     remote_add_target_side_commands (gdbarch, bp_tgt, p);
10695
10696   putpkt (rs->buf);
10697   getpkt (&rs->buf, &rs->buf_size, 0);
10698
10699   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10700     {
10701     case PACKET_ERROR:
10702       if (rs->buf[1] == '.')
10703         {
10704           message = strchr (rs->buf + 2, '.');
10705           if (message)
10706             error (_("Remote failure reply: %s"), message + 1);
10707         }
10708       return -1;
10709     case PACKET_UNKNOWN:
10710       return -1;
10711     case PACKET_OK:
10712       return 0;
10713     }
10714   internal_error (__FILE__, __LINE__,
10715                   _("remote_insert_hw_breakpoint: reached end of function"));
10716 }
10717
10718
10719 int
10720 remote_target::remove_hw_breakpoint (struct gdbarch *gdbarch,
10721                                      struct bp_target_info *bp_tgt)
10722 {
10723   CORE_ADDR addr;
10724   struct remote_state *rs = get_remote_state ();
10725   char *p = rs->buf;
10726   char *endbuf = rs->buf + get_remote_packet_size ();
10727
10728   if (packet_support (PACKET_Z1) == PACKET_DISABLE)
10729     return -1;
10730
10731   /* Make sure the remote is pointing at the right process, if
10732      necessary.  */
10733   if (!gdbarch_has_global_breakpoints (target_gdbarch ()))
10734     set_general_process ();
10735
10736   *(p++) = 'z';
10737   *(p++) = '1';
10738   *(p++) = ',';
10739
10740   addr = remote_address_masked (bp_tgt->placed_address);
10741   p += hexnumstr (p, (ULONGEST) addr);
10742   xsnprintf (p, endbuf  - p, ",%x", bp_tgt->kind);
10743
10744   putpkt (rs->buf);
10745   getpkt (&rs->buf, &rs->buf_size, 0);
10746
10747   switch (packet_ok (rs->buf, &remote_protocol_packets[PACKET_Z1]))
10748     {
10749     case PACKET_ERROR:
10750     case PACKET_UNKNOWN:
10751       return -1;
10752     case PACKET_OK:
10753       return 0;
10754     }
10755   internal_error (__FILE__, __LINE__,
10756                   _("remote_remove_hw_breakpoint: reached end of function"));
10757 }
10758
10759 /* Verify memory using the "qCRC:" request.  */
10760
10761 int
10762 remote_target::verify_memory (const gdb_byte *data, CORE_ADDR lma, ULONGEST size)
10763 {
10764   struct remote_state *rs = get_remote_state ();
10765   unsigned long host_crc, target_crc;
10766   char *tmp;
10767
10768   /* It doesn't make sense to use qCRC if the remote target is
10769      connected but not running.  */
10770   if (target_has_execution && packet_support (PACKET_qCRC) != PACKET_DISABLE)
10771     {
10772       enum packet_result result;
10773
10774       /* Make sure the remote is pointing at the right process.  */
10775       set_general_process ();
10776
10777       /* FIXME: assumes lma can fit into long.  */
10778       xsnprintf (rs->buf, get_remote_packet_size (), "qCRC:%lx,%lx",
10779                  (long) lma, (long) size);
10780       putpkt (rs->buf);
10781
10782       /* Be clever; compute the host_crc before waiting for target
10783          reply.  */
10784       host_crc = xcrc32 (data, size, 0xffffffff);
10785
10786       getpkt (&rs->buf, &rs->buf_size, 0);
10787
10788       result = packet_ok (rs->buf,
10789                           &remote_protocol_packets[PACKET_qCRC]);
10790       if (result == PACKET_ERROR)
10791         return -1;
10792       else if (result == PACKET_OK)
10793         {
10794           for (target_crc = 0, tmp = &rs->buf[1]; *tmp; tmp++)
10795             target_crc = target_crc * 16 + fromhex (*tmp);
10796
10797           return (host_crc == target_crc);
10798         }
10799     }
10800
10801   return simple_verify_memory (this, data, lma, size);
10802 }
10803
10804 /* compare-sections command
10805
10806    With no arguments, compares each loadable section in the exec bfd
10807    with the same memory range on the target, and reports mismatches.
10808    Useful for verifying the image on the target against the exec file.  */
10809
10810 static void
10811 compare_sections_command (const char *args, int from_tty)
10812 {
10813   asection *s;
10814   const char *sectname;
10815   bfd_size_type size;
10816   bfd_vma lma;
10817   int matched = 0;
10818   int mismatched = 0;
10819   int res;
10820   int read_only = 0;
10821
10822   if (!exec_bfd)
10823     error (_("command cannot be used without an exec file"));
10824
10825   if (args != NULL && strcmp (args, "-r") == 0)
10826     {
10827       read_only = 1;
10828       args = NULL;
10829     }
10830
10831   for (s = exec_bfd->sections; s; s = s->next)
10832     {
10833       if (!(s->flags & SEC_LOAD))
10834         continue;               /* Skip non-loadable section.  */
10835
10836       if (read_only && (s->flags & SEC_READONLY) == 0)
10837         continue;               /* Skip writeable sections */
10838
10839       size = bfd_get_section_size (s);
10840       if (size == 0)
10841         continue;               /* Skip zero-length section.  */
10842
10843       sectname = bfd_get_section_name (exec_bfd, s);
10844       if (args && strcmp (args, sectname) != 0)
10845         continue;               /* Not the section selected by user.  */
10846
10847       matched = 1;              /* Do this section.  */
10848       lma = s->lma;
10849
10850       gdb::byte_vector sectdata (size);
10851       bfd_get_section_contents (exec_bfd, s, sectdata.data (), 0, size);
10852
10853       res = target_verify_memory (sectdata.data (), lma, size);
10854
10855       if (res == -1)
10856         error (_("target memory fault, section %s, range %s -- %s"), sectname,
10857                paddress (target_gdbarch (), lma),
10858                paddress (target_gdbarch (), lma + size));
10859
10860       printf_filtered ("Section %s, range %s -- %s: ", sectname,
10861                        paddress (target_gdbarch (), lma),
10862                        paddress (target_gdbarch (), lma + size));
10863       if (res)
10864         printf_filtered ("matched.\n");
10865       else
10866         {
10867           printf_filtered ("MIS-MATCHED!\n");
10868           mismatched++;
10869         }
10870     }
10871   if (mismatched > 0)
10872     warning (_("One or more sections of the target image does not match\n\
10873 the loaded file\n"));
10874   if (args && !matched)
10875     printf_filtered (_("No loaded section named '%s'.\n"), args);
10876 }
10877
10878 /* Write LEN bytes from WRITEBUF into OBJECT_NAME/ANNEX at OFFSET
10879    into remote target.  The number of bytes written to the remote
10880    target is returned, or -1 for error.  */
10881
10882 target_xfer_status
10883 remote_target::remote_write_qxfer (const char *object_name,
10884                                    const char *annex, const gdb_byte *writebuf,
10885                                    ULONGEST offset, LONGEST len,
10886                                    ULONGEST *xfered_len,
10887                                    struct packet_config *packet)
10888 {
10889   int i, buf_len;
10890   ULONGEST n;
10891   struct remote_state *rs = get_remote_state ();
10892   int max_size = get_memory_write_packet_size (); 
10893
10894   if (packet_config_support (packet) == PACKET_DISABLE)
10895     return TARGET_XFER_E_IO;
10896
10897   /* Insert header.  */
10898   i = snprintf (rs->buf, max_size, 
10899                 "qXfer:%s:write:%s:%s:",
10900                 object_name, annex ? annex : "",
10901                 phex_nz (offset, sizeof offset));
10902   max_size -= (i + 1);
10903
10904   /* Escape as much data as fits into rs->buf.  */
10905   buf_len = remote_escape_output 
10906     (writebuf, len, 1, (gdb_byte *) rs->buf + i, &max_size, max_size);
10907
10908   if (putpkt_binary (rs->buf, i + buf_len) < 0
10909       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
10910       || packet_ok (rs->buf, packet) != PACKET_OK)
10911     return TARGET_XFER_E_IO;
10912
10913   unpack_varlen_hex (rs->buf, &n);
10914
10915   *xfered_len = n;
10916   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
10917 }
10918
10919 /* Read OBJECT_NAME/ANNEX from the remote target using a qXfer packet.
10920    Data at OFFSET, of up to LEN bytes, is read into READBUF; the
10921    number of bytes read is returned, or 0 for EOF, or -1 for error.
10922    The number of bytes read may be less than LEN without indicating an
10923    EOF.  PACKET is checked and updated to indicate whether the remote
10924    target supports this object.  */
10925
10926 target_xfer_status
10927 remote_target::remote_read_qxfer (const char *object_name,
10928                                   const char *annex,
10929                                   gdb_byte *readbuf, ULONGEST offset,
10930                                   LONGEST len,
10931                                   ULONGEST *xfered_len,
10932                                   struct packet_config *packet)
10933 {
10934   struct remote_state *rs = get_remote_state ();
10935   LONGEST i, n, packet_len;
10936
10937   if (packet_config_support (packet) == PACKET_DISABLE)
10938     return TARGET_XFER_E_IO;
10939
10940   /* Check whether we've cached an end-of-object packet that matches
10941      this request.  */
10942   if (rs->finished_object)
10943     {
10944       if (strcmp (object_name, rs->finished_object) == 0
10945           && strcmp (annex ? annex : "", rs->finished_annex) == 0
10946           && offset == rs->finished_offset)
10947         return TARGET_XFER_EOF;
10948
10949
10950       /* Otherwise, we're now reading something different.  Discard
10951          the cache.  */
10952       xfree (rs->finished_object);
10953       xfree (rs->finished_annex);
10954       rs->finished_object = NULL;
10955       rs->finished_annex = NULL;
10956     }
10957
10958   /* Request only enough to fit in a single packet.  The actual data
10959      may not, since we don't know how much of it will need to be escaped;
10960      the target is free to respond with slightly less data.  We subtract
10961      five to account for the response type and the protocol frame.  */
10962   n = std::min<LONGEST> (get_remote_packet_size () - 5, len);
10963   snprintf (rs->buf, get_remote_packet_size () - 4, "qXfer:%s:read:%s:%s,%s",
10964             object_name, annex ? annex : "",
10965             phex_nz (offset, sizeof offset),
10966             phex_nz (n, sizeof n));
10967   i = putpkt (rs->buf);
10968   if (i < 0)
10969     return TARGET_XFER_E_IO;
10970
10971   rs->buf[0] = '\0';
10972   packet_len = getpkt_sane (&rs->buf, &rs->buf_size, 0);
10973   if (packet_len < 0 || packet_ok (rs->buf, packet) != PACKET_OK)
10974     return TARGET_XFER_E_IO;
10975
10976   if (rs->buf[0] != 'l' && rs->buf[0] != 'm')
10977     error (_("Unknown remote qXfer reply: %s"), rs->buf);
10978
10979   /* 'm' means there is (or at least might be) more data after this
10980      batch.  That does not make sense unless there's at least one byte
10981      of data in this reply.  */
10982   if (rs->buf[0] == 'm' && packet_len == 1)
10983     error (_("Remote qXfer reply contained no data."));
10984
10985   /* Got some data.  */
10986   i = remote_unescape_input ((gdb_byte *) rs->buf + 1,
10987                              packet_len - 1, readbuf, n);
10988
10989   /* 'l' is an EOF marker, possibly including a final block of data,
10990      or possibly empty.  If we have the final block of a non-empty
10991      object, record this fact to bypass a subsequent partial read.  */
10992   if (rs->buf[0] == 'l' && offset + i > 0)
10993     {
10994       rs->finished_object = xstrdup (object_name);
10995       rs->finished_annex = xstrdup (annex ? annex : "");
10996       rs->finished_offset = offset + i;
10997     }
10998
10999   if (i == 0)
11000     return TARGET_XFER_EOF;
11001   else
11002     {
11003       *xfered_len = i;
11004       return TARGET_XFER_OK;
11005     }
11006 }
11007
11008 enum target_xfer_status
11009 remote_target::xfer_partial (enum target_object object,
11010                              const char *annex, gdb_byte *readbuf,
11011                              const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
11012                              ULONGEST *xfered_len)
11013 {
11014   struct remote_state *rs;
11015   int i;
11016   char *p2;
11017   char query_type;
11018   int unit_size = gdbarch_addressable_memory_unit_size (target_gdbarch ());
11019
11020   set_remote_traceframe ();
11021   set_general_thread (inferior_ptid);
11022
11023   rs = get_remote_state ();
11024
11025   /* Handle memory using the standard memory routines.  */
11026   if (object == TARGET_OBJECT_MEMORY)
11027     {
11028       /* If the remote target is connected but not running, we should
11029          pass this request down to a lower stratum (e.g. the executable
11030          file).  */
11031       if (!target_has_execution)
11032         return TARGET_XFER_EOF;
11033
11034       if (writebuf != NULL)
11035         return remote_write_bytes (offset, writebuf, len, unit_size,
11036                                    xfered_len);
11037       else
11038         return remote_read_bytes (offset, readbuf, len, unit_size,
11039                                   xfered_len);
11040     }
11041
11042   /* Handle SPU memory using qxfer packets.  */
11043   if (object == TARGET_OBJECT_SPU)
11044     {
11045       if (readbuf)
11046         return remote_read_qxfer ("spu", annex, readbuf, offset, len,
11047                                   xfered_len, &remote_protocol_packets
11048                                   [PACKET_qXfer_spu_read]);
11049       else
11050         return remote_write_qxfer ("spu", annex, writebuf, offset, len,
11051                                    xfered_len, &remote_protocol_packets
11052                                    [PACKET_qXfer_spu_write]);
11053     }
11054
11055   /* Handle extra signal info using qxfer packets.  */
11056   if (object == TARGET_OBJECT_SIGNAL_INFO)
11057     {
11058       if (readbuf)
11059         return remote_read_qxfer ("siginfo", annex, readbuf, offset, len,
11060                                   xfered_len, &remote_protocol_packets
11061                                   [PACKET_qXfer_siginfo_read]);
11062       else
11063         return remote_write_qxfer ("siginfo", annex,
11064                                    writebuf, offset, len, xfered_len,
11065                                    &remote_protocol_packets
11066                                    [PACKET_qXfer_siginfo_write]);
11067     }
11068
11069   if (object == TARGET_OBJECT_STATIC_TRACE_DATA)
11070     {
11071       if (readbuf)
11072         return remote_read_qxfer ("statictrace", annex,
11073                                   readbuf, offset, len, xfered_len,
11074                                   &remote_protocol_packets
11075                                   [PACKET_qXfer_statictrace_read]);
11076       else
11077         return TARGET_XFER_E_IO;
11078     }
11079
11080   /* Only handle flash writes.  */
11081   if (writebuf != NULL)
11082     {
11083       switch (object)
11084         {
11085         case TARGET_OBJECT_FLASH:
11086           return remote_flash_write (offset, len, xfered_len,
11087                                      writebuf);
11088
11089         default:
11090           return TARGET_XFER_E_IO;
11091         }
11092     }
11093
11094   /* Map pre-existing objects onto letters.  DO NOT do this for new
11095      objects!!!  Instead specify new query packets.  */
11096   switch (object)
11097     {
11098     case TARGET_OBJECT_AVR:
11099       query_type = 'R';
11100       break;
11101
11102     case TARGET_OBJECT_AUXV:
11103       gdb_assert (annex == NULL);
11104       return remote_read_qxfer ("auxv", annex, readbuf, offset, len,
11105                                 xfered_len,
11106                                 &remote_protocol_packets[PACKET_qXfer_auxv]);
11107
11108     case TARGET_OBJECT_AVAILABLE_FEATURES:
11109       return remote_read_qxfer
11110         ("features", annex, readbuf, offset, len, xfered_len,
11111          &remote_protocol_packets[PACKET_qXfer_features]);
11112
11113     case TARGET_OBJECT_LIBRARIES:
11114       return remote_read_qxfer
11115         ("libraries", annex, readbuf, offset, len, xfered_len,
11116          &remote_protocol_packets[PACKET_qXfer_libraries]);
11117
11118     case TARGET_OBJECT_LIBRARIES_SVR4:
11119       return remote_read_qxfer
11120         ("libraries-svr4", annex, readbuf, offset, len, xfered_len,
11121          &remote_protocol_packets[PACKET_qXfer_libraries_svr4]);
11122
11123     case TARGET_OBJECT_MEMORY_MAP:
11124       gdb_assert (annex == NULL);
11125       return remote_read_qxfer ("memory-map", annex, readbuf, offset, len,
11126                                  xfered_len,
11127                                 &remote_protocol_packets[PACKET_qXfer_memory_map]);
11128
11129     case TARGET_OBJECT_OSDATA:
11130       /* Should only get here if we're connected.  */
11131       gdb_assert (rs->remote_desc);
11132       return remote_read_qxfer
11133         ("osdata", annex, readbuf, offset, len, xfered_len,
11134         &remote_protocol_packets[PACKET_qXfer_osdata]);
11135
11136     case TARGET_OBJECT_THREADS:
11137       gdb_assert (annex == NULL);
11138       return remote_read_qxfer ("threads", annex, readbuf, offset, len,
11139                                 xfered_len,
11140                                 &remote_protocol_packets[PACKET_qXfer_threads]);
11141
11142     case TARGET_OBJECT_TRACEFRAME_INFO:
11143       gdb_assert (annex == NULL);
11144       return remote_read_qxfer
11145         ("traceframe-info", annex, readbuf, offset, len, xfered_len,
11146          &remote_protocol_packets[PACKET_qXfer_traceframe_info]);
11147
11148     case TARGET_OBJECT_FDPIC:
11149       return remote_read_qxfer ("fdpic", annex, readbuf, offset, len,
11150                                 xfered_len,
11151                                 &remote_protocol_packets[PACKET_qXfer_fdpic]);
11152
11153     case TARGET_OBJECT_OPENVMS_UIB:
11154       return remote_read_qxfer ("uib", annex, readbuf, offset, len,
11155                                 xfered_len,
11156                                 &remote_protocol_packets[PACKET_qXfer_uib]);
11157
11158     case TARGET_OBJECT_BTRACE:
11159       return remote_read_qxfer ("btrace", annex, readbuf, offset, len,
11160                                 xfered_len,
11161         &remote_protocol_packets[PACKET_qXfer_btrace]);
11162
11163     case TARGET_OBJECT_BTRACE_CONF:
11164       return remote_read_qxfer ("btrace-conf", annex, readbuf, offset,
11165                                 len, xfered_len,
11166         &remote_protocol_packets[PACKET_qXfer_btrace_conf]);
11167
11168     case TARGET_OBJECT_EXEC_FILE:
11169       return remote_read_qxfer ("exec-file", annex, readbuf, offset,
11170                                 len, xfered_len,
11171         &remote_protocol_packets[PACKET_qXfer_exec_file]);
11172
11173     default:
11174       return TARGET_XFER_E_IO;
11175     }
11176
11177   /* Minimum outbuf size is get_remote_packet_size ().  If LEN is not
11178      large enough let the caller deal with it.  */
11179   if (len < get_remote_packet_size ())
11180     return TARGET_XFER_E_IO;
11181   len = get_remote_packet_size ();
11182
11183   /* Except for querying the minimum buffer size, target must be open.  */
11184   if (!rs->remote_desc)
11185     error (_("remote query is only available after target open"));
11186
11187   gdb_assert (annex != NULL);
11188   gdb_assert (readbuf != NULL);
11189
11190   p2 = rs->buf;
11191   *p2++ = 'q';
11192   *p2++ = query_type;
11193
11194   /* We used one buffer char for the remote protocol q command and
11195      another for the query type.  As the remote protocol encapsulation
11196      uses 4 chars plus one extra in case we are debugging
11197      (remote_debug), we have PBUFZIZ - 7 left to pack the query
11198      string.  */
11199   i = 0;
11200   while (annex[i] && (i < (get_remote_packet_size () - 8)))
11201     {
11202       /* Bad caller may have sent forbidden characters.  */
11203       gdb_assert (isprint (annex[i]) && annex[i] != '$' && annex[i] != '#');
11204       *p2++ = annex[i];
11205       i++;
11206     }
11207   *p2 = '\0';
11208   gdb_assert (annex[i] == '\0');
11209
11210   i = putpkt (rs->buf);
11211   if (i < 0)
11212     return TARGET_XFER_E_IO;
11213
11214   getpkt (&rs->buf, &rs->buf_size, 0);
11215   strcpy ((char *) readbuf, rs->buf);
11216
11217   *xfered_len = strlen ((char *) readbuf);
11218   return (*xfered_len != 0) ? TARGET_XFER_OK : TARGET_XFER_EOF;
11219 }
11220
11221 /* Implementation of to_get_memory_xfer_limit.  */
11222
11223 ULONGEST
11224 remote_target::get_memory_xfer_limit ()
11225 {
11226   return get_memory_write_packet_size ();
11227 }
11228
11229 int
11230 remote_target::search_memory (CORE_ADDR start_addr, ULONGEST search_space_len,
11231                               const gdb_byte *pattern, ULONGEST pattern_len,
11232                               CORE_ADDR *found_addrp)
11233 {
11234   int addr_size = gdbarch_addr_bit (target_gdbarch ()) / 8;
11235   struct remote_state *rs = get_remote_state ();
11236   int max_size = get_memory_write_packet_size ();
11237   struct packet_config *packet =
11238     &remote_protocol_packets[PACKET_qSearch_memory];
11239   /* Number of packet bytes used to encode the pattern;
11240      this could be more than PATTERN_LEN due to escape characters.  */
11241   int escaped_pattern_len;
11242   /* Amount of pattern that was encodable in the packet.  */
11243   int used_pattern_len;
11244   int i;
11245   int found;
11246   ULONGEST found_addr;
11247
11248   /* Don't go to the target if we don't have to.  This is done before
11249      checking packet_config_support to avoid the possibility that a
11250      success for this edge case means the facility works in
11251      general.  */
11252   if (pattern_len > search_space_len)
11253     return 0;
11254   if (pattern_len == 0)
11255     {
11256       *found_addrp = start_addr;
11257       return 1;
11258     }
11259
11260   /* If we already know the packet isn't supported, fall back to the simple
11261      way of searching memory.  */
11262
11263   if (packet_config_support (packet) == PACKET_DISABLE)
11264     {
11265       /* Target doesn't provided special support, fall back and use the
11266          standard support (copy memory and do the search here).  */
11267       return simple_search_memory (this, start_addr, search_space_len,
11268                                    pattern, pattern_len, found_addrp);
11269     }
11270
11271   /* Make sure the remote is pointing at the right process.  */
11272   set_general_process ();
11273
11274   /* Insert header.  */
11275   i = snprintf (rs->buf, max_size, 
11276                 "qSearch:memory:%s;%s;",
11277                 phex_nz (start_addr, addr_size),
11278                 phex_nz (search_space_len, sizeof (search_space_len)));
11279   max_size -= (i + 1);
11280
11281   /* Escape as much data as fits into rs->buf.  */
11282   escaped_pattern_len =
11283     remote_escape_output (pattern, pattern_len, 1, (gdb_byte *) rs->buf + i,
11284                           &used_pattern_len, max_size);
11285
11286   /* Bail if the pattern is too large.  */
11287   if (used_pattern_len != pattern_len)
11288     error (_("Pattern is too large to transmit to remote target."));
11289
11290   if (putpkt_binary (rs->buf, i + escaped_pattern_len) < 0
11291       || getpkt_sane (&rs->buf, &rs->buf_size, 0) < 0
11292       || packet_ok (rs->buf, packet) != PACKET_OK)
11293     {
11294       /* The request may not have worked because the command is not
11295          supported.  If so, fall back to the simple way.  */
11296       if (packet_config_support (packet) == PACKET_DISABLE)
11297         {
11298           return simple_search_memory (this, start_addr, search_space_len,
11299                                        pattern, pattern_len, found_addrp);
11300         }
11301       return -1;
11302     }
11303
11304   if (rs->buf[0] == '0')
11305     found = 0;
11306   else if (rs->buf[0] == '1')
11307     {
11308       found = 1;
11309       if (rs->buf[1] != ',')
11310         error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11311       unpack_varlen_hex (rs->buf + 2, &found_addr);
11312       *found_addrp = found_addr;
11313     }
11314   else
11315     error (_("Unknown qSearch:memory reply: %s"), rs->buf);
11316
11317   return found;
11318 }
11319
11320 void
11321 remote_target::rcmd (const char *command, struct ui_file *outbuf)
11322 {
11323   struct remote_state *rs = get_remote_state ();
11324   char *p = rs->buf;
11325
11326   if (!rs->remote_desc)
11327     error (_("remote rcmd is only available after target open"));
11328
11329   /* Send a NULL command across as an empty command.  */
11330   if (command == NULL)
11331     command = "";
11332
11333   /* The query prefix.  */
11334   strcpy (rs->buf, "qRcmd,");
11335   p = strchr (rs->buf, '\0');
11336
11337   if ((strlen (rs->buf) + strlen (command) * 2 + 8/*misc*/)
11338       > get_remote_packet_size ())
11339     error (_("\"monitor\" command ``%s'' is too long."), command);
11340
11341   /* Encode the actual command.  */
11342   bin2hex ((const gdb_byte *) command, p, strlen (command));
11343
11344   if (putpkt (rs->buf) < 0)
11345     error (_("Communication problem with target."));
11346
11347   /* get/display the response */
11348   while (1)
11349     {
11350       char *buf;
11351
11352       /* XXX - see also remote_get_noisy_reply().  */
11353       QUIT;                     /* Allow user to bail out with ^C.  */
11354       rs->buf[0] = '\0';
11355       if (getpkt_sane (&rs->buf, &rs->buf_size, 0) == -1)
11356         { 
11357           /* Timeout.  Continue to (try to) read responses.
11358              This is better than stopping with an error, assuming the stub
11359              is still executing the (long) monitor command.
11360              If needed, the user can interrupt gdb using C-c, obtaining
11361              an effect similar to stop on timeout.  */
11362           continue;
11363         }
11364       buf = rs->buf;
11365       if (buf[0] == '\0')
11366         error (_("Target does not support this command."));
11367       if (buf[0] == 'O' && buf[1] != 'K')
11368         {
11369           remote_console_output (buf + 1); /* 'O' message from stub.  */
11370           continue;
11371         }
11372       if (strcmp (buf, "OK") == 0)
11373         break;
11374       if (strlen (buf) == 3 && buf[0] == 'E'
11375           && isdigit (buf[1]) && isdigit (buf[2]))
11376         {
11377           error (_("Protocol error with Rcmd"));
11378         }
11379       for (p = buf; p[0] != '\0' && p[1] != '\0'; p += 2)
11380         {
11381           char c = (fromhex (p[0]) << 4) + fromhex (p[1]);
11382
11383           fputc_unfiltered (c, outbuf);
11384         }
11385       break;
11386     }
11387 }
11388
11389 std::vector<mem_region>
11390 remote_target::memory_map ()
11391 {
11392   std::vector<mem_region> result;
11393   gdb::optional<gdb::char_vector> text
11394     = target_read_stralloc (current_top_target (), TARGET_OBJECT_MEMORY_MAP, NULL);
11395
11396   if (text)
11397     result = parse_memory_map (text->data ());
11398
11399   return result;
11400 }
11401
11402 static void
11403 packet_command (const char *args, int from_tty)
11404 {
11405   remote_target *remote = get_current_remote_target ();
11406
11407   if (remote == nullptr)
11408     error (_("command can only be used with remote target"));
11409
11410   remote->packet_command (args, from_tty);
11411 }
11412
11413 void
11414 remote_target::packet_command (const char *args, int from_tty)
11415 {
11416   if (!args)
11417     error (_("remote-packet command requires packet text as argument"));
11418
11419   puts_filtered ("sending: ");
11420   print_packet (args);
11421   puts_filtered ("\n");
11422   putpkt (args);
11423
11424   remote_state *rs = get_remote_state ();
11425
11426   getpkt (&rs->buf, &rs->buf_size, 0);
11427   puts_filtered ("received: ");
11428   print_packet (rs->buf);
11429   puts_filtered ("\n");
11430 }
11431
11432 #if 0
11433 /* --------- UNIT_TEST for THREAD oriented PACKETS ------------------- */
11434
11435 static void display_thread_info (struct gdb_ext_thread_info *info);
11436
11437 static void threadset_test_cmd (char *cmd, int tty);
11438
11439 static void threadalive_test (char *cmd, int tty);
11440
11441 static void threadlist_test_cmd (char *cmd, int tty);
11442
11443 int get_and_display_threadinfo (threadref *ref);
11444
11445 static void threadinfo_test_cmd (char *cmd, int tty);
11446
11447 static int thread_display_step (threadref *ref, void *context);
11448
11449 static void threadlist_update_test_cmd (char *cmd, int tty);
11450
11451 static void init_remote_threadtests (void);
11452
11453 #define SAMPLE_THREAD  0x05060708       /* Truncated 64 bit threadid.  */
11454
11455 static void
11456 threadset_test_cmd (const char *cmd, int tty)
11457 {
11458   int sample_thread = SAMPLE_THREAD;
11459
11460   printf_filtered (_("Remote threadset test\n"));
11461   set_general_thread (sample_thread);
11462 }
11463
11464
11465 static void
11466 threadalive_test (const char *cmd, int tty)
11467 {
11468   int sample_thread = SAMPLE_THREAD;
11469   int pid = ptid_get_pid (inferior_ptid);
11470   ptid_t ptid = ptid_build (pid, sample_thread, 0);
11471
11472   if (remote_thread_alive (ptid))
11473     printf_filtered ("PASS: Thread alive test\n");
11474   else
11475     printf_filtered ("FAIL: Thread alive test\n");
11476 }
11477
11478 void output_threadid (char *title, threadref *ref);
11479
11480 void
11481 output_threadid (char *title, threadref *ref)
11482 {
11483   char hexid[20];
11484
11485   pack_threadid (&hexid[0], ref);       /* Convert threead id into hex.  */
11486   hexid[16] = 0;
11487   printf_filtered ("%s  %s\n", title, (&hexid[0]));
11488 }
11489
11490 static void
11491 threadlist_test_cmd (const char *cmd, int tty)
11492 {
11493   int startflag = 1;
11494   threadref nextthread;
11495   int done, result_count;
11496   threadref threadlist[3];
11497
11498   printf_filtered ("Remote Threadlist test\n");
11499   if (!remote_get_threadlist (startflag, &nextthread, 3, &done,
11500                               &result_count, &threadlist[0]))
11501     printf_filtered ("FAIL: threadlist test\n");
11502   else
11503     {
11504       threadref *scan = threadlist;
11505       threadref *limit = scan + result_count;
11506
11507       while (scan < limit)
11508         output_threadid (" thread ", scan++);
11509     }
11510 }
11511
11512 void
11513 display_thread_info (struct gdb_ext_thread_info *info)
11514 {
11515   output_threadid ("Threadid: ", &info->threadid);
11516   printf_filtered ("Name: %s\n ", info->shortname);
11517   printf_filtered ("State: %s\n", info->display);
11518   printf_filtered ("other: %s\n\n", info->more_display);
11519 }
11520
11521 int
11522 get_and_display_threadinfo (threadref *ref)
11523 {
11524   int result;
11525   int set;
11526   struct gdb_ext_thread_info threadinfo;
11527
11528   set = TAG_THREADID | TAG_EXISTS | TAG_THREADNAME
11529     | TAG_MOREDISPLAY | TAG_DISPLAY;
11530   if (0 != (result = remote_get_threadinfo (ref, set, &threadinfo)))
11531     display_thread_info (&threadinfo);
11532   return result;
11533 }
11534
11535 static void
11536 threadinfo_test_cmd (const char *cmd, int tty)
11537 {
11538   int athread = SAMPLE_THREAD;
11539   threadref thread;
11540   int set;
11541
11542   int_to_threadref (&thread, athread);
11543   printf_filtered ("Remote Threadinfo test\n");
11544   if (!get_and_display_threadinfo (&thread))
11545     printf_filtered ("FAIL cannot get thread info\n");
11546 }
11547
11548 static int
11549 thread_display_step (threadref *ref, void *context)
11550 {
11551   /* output_threadid(" threadstep ",ref); *//* simple test */
11552   return get_and_display_threadinfo (ref);
11553 }
11554
11555 static void
11556 threadlist_update_test_cmd (const char *cmd, int tty)
11557 {
11558   printf_filtered ("Remote Threadlist update test\n");
11559   remote_threadlist_iterator (thread_display_step, 0, CRAZY_MAX_THREADS);
11560 }
11561
11562 static void
11563 init_remote_threadtests (void)
11564 {
11565   add_com ("tlist", class_obscure, threadlist_test_cmd,
11566            _("Fetch and print the remote list of "
11567              "thread identifiers, one pkt only"));
11568   add_com ("tinfo", class_obscure, threadinfo_test_cmd,
11569            _("Fetch and display info about one thread"));
11570   add_com ("tset", class_obscure, threadset_test_cmd,
11571            _("Test setting to a different thread"));
11572   add_com ("tupd", class_obscure, threadlist_update_test_cmd,
11573            _("Iterate through updating all remote thread info"));
11574   add_com ("talive", class_obscure, threadalive_test,
11575            _(" Remote thread alive test "));
11576 }
11577
11578 #endif /* 0 */
11579
11580 /* Convert a thread ID to a string.  Returns the string in a static
11581    buffer.  */
11582
11583 const char *
11584 remote_target::pid_to_str (ptid_t ptid)
11585 {
11586   static char buf[64];
11587   struct remote_state *rs = get_remote_state ();
11588
11589   if (ptid_equal (ptid, null_ptid))
11590     return normal_pid_to_str (ptid);
11591   else if (ptid_is_pid (ptid))
11592     {
11593       /* Printing an inferior target id.  */
11594
11595       /* When multi-process extensions are off, there's no way in the
11596          remote protocol to know the remote process id, if there's any
11597          at all.  There's one exception --- when we're connected with
11598          target extended-remote, and we manually attached to a process
11599          with "attach PID".  We don't record anywhere a flag that
11600          allows us to distinguish that case from the case of
11601          connecting with extended-remote and the stub already being
11602          attached to a process, and reporting yes to qAttached, hence
11603          no smart special casing here.  */
11604       if (!remote_multi_process_p (rs))
11605         {
11606           xsnprintf (buf, sizeof buf, "Remote target");
11607           return buf;
11608         }
11609
11610       return normal_pid_to_str (ptid);
11611     }
11612   else
11613     {
11614       if (ptid_equal (magic_null_ptid, ptid))
11615         xsnprintf (buf, sizeof buf, "Thread <main>");
11616       else if (remote_multi_process_p (rs))
11617         if (ptid_get_lwp (ptid) == 0)
11618           return normal_pid_to_str (ptid);
11619         else
11620           xsnprintf (buf, sizeof buf, "Thread %d.%ld",
11621                      ptid_get_pid (ptid), ptid_get_lwp (ptid));
11622       else
11623         xsnprintf (buf, sizeof buf, "Thread %ld",
11624                    ptid_get_lwp (ptid));
11625       return buf;
11626     }
11627 }
11628
11629 /* Get the address of the thread local variable in OBJFILE which is
11630    stored at OFFSET within the thread local storage for thread PTID.  */
11631
11632 CORE_ADDR
11633 remote_target::get_thread_local_address (ptid_t ptid, CORE_ADDR lm,
11634                                          CORE_ADDR offset)
11635 {
11636   if (packet_support (PACKET_qGetTLSAddr) != PACKET_DISABLE)
11637     {
11638       struct remote_state *rs = get_remote_state ();
11639       char *p = rs->buf;
11640       char *endp = rs->buf + get_remote_packet_size ();
11641       enum packet_result result;
11642
11643       strcpy (p, "qGetTLSAddr:");
11644       p += strlen (p);
11645       p = write_ptid (p, endp, ptid);
11646       *p++ = ',';
11647       p += hexnumstr (p, offset);
11648       *p++ = ',';
11649       p += hexnumstr (p, lm);
11650       *p++ = '\0';
11651
11652       putpkt (rs->buf);
11653       getpkt (&rs->buf, &rs->buf_size, 0);
11654       result = packet_ok (rs->buf,
11655                           &remote_protocol_packets[PACKET_qGetTLSAddr]);
11656       if (result == PACKET_OK)
11657         {
11658           ULONGEST result;
11659
11660           unpack_varlen_hex (rs->buf, &result);
11661           return result;
11662         }
11663       else if (result == PACKET_UNKNOWN)
11664         throw_error (TLS_GENERIC_ERROR,
11665                      _("Remote target doesn't support qGetTLSAddr packet"));
11666       else
11667         throw_error (TLS_GENERIC_ERROR,
11668                      _("Remote target failed to process qGetTLSAddr request"));
11669     }
11670   else
11671     throw_error (TLS_GENERIC_ERROR,
11672                  _("TLS not supported or disabled on this target"));
11673   /* Not reached.  */
11674   return 0;
11675 }
11676
11677 /* Provide thread local base, i.e. Thread Information Block address.
11678    Returns 1 if ptid is found and thread_local_base is non zero.  */
11679
11680 bool
11681 remote_target::get_tib_address (ptid_t ptid, CORE_ADDR *addr)
11682 {
11683   if (packet_support (PACKET_qGetTIBAddr) != PACKET_DISABLE)
11684     {
11685       struct remote_state *rs = get_remote_state ();
11686       char *p = rs->buf;
11687       char *endp = rs->buf + get_remote_packet_size ();
11688       enum packet_result result;
11689
11690       strcpy (p, "qGetTIBAddr:");
11691       p += strlen (p);
11692       p = write_ptid (p, endp, ptid);
11693       *p++ = '\0';
11694
11695       putpkt (rs->buf);
11696       getpkt (&rs->buf, &rs->buf_size, 0);
11697       result = packet_ok (rs->buf,
11698                           &remote_protocol_packets[PACKET_qGetTIBAddr]);
11699       if (result == PACKET_OK)
11700         {
11701           ULONGEST result;
11702
11703           unpack_varlen_hex (rs->buf, &result);
11704           if (addr)
11705             *addr = (CORE_ADDR) result;
11706           return true;
11707         }
11708       else if (result == PACKET_UNKNOWN)
11709         error (_("Remote target doesn't support qGetTIBAddr packet"));
11710       else
11711         error (_("Remote target failed to process qGetTIBAddr request"));
11712     }
11713   else
11714     error (_("qGetTIBAddr not supported or disabled on this target"));
11715   /* Not reached.  */
11716   return false;
11717 }
11718
11719 /* Support for inferring a target description based on the current
11720    architecture and the size of a 'g' packet.  While the 'g' packet
11721    can have any size (since optional registers can be left off the
11722    end), some sizes are easily recognizable given knowledge of the
11723    approximate architecture.  */
11724
11725 struct remote_g_packet_guess
11726 {
11727   int bytes;
11728   const struct target_desc *tdesc;
11729 };
11730 typedef struct remote_g_packet_guess remote_g_packet_guess_s;
11731 DEF_VEC_O(remote_g_packet_guess_s);
11732
11733 struct remote_g_packet_data
11734 {
11735   VEC(remote_g_packet_guess_s) *guesses;
11736 };
11737
11738 static struct gdbarch_data *remote_g_packet_data_handle;
11739
11740 static void *
11741 remote_g_packet_data_init (struct obstack *obstack)
11742 {
11743   return OBSTACK_ZALLOC (obstack, struct remote_g_packet_data);
11744 }
11745
11746 void
11747 register_remote_g_packet_guess (struct gdbarch *gdbarch, int bytes,
11748                                 const struct target_desc *tdesc)
11749 {
11750   struct remote_g_packet_data *data
11751     = ((struct remote_g_packet_data *)
11752        gdbarch_data (gdbarch, remote_g_packet_data_handle));
11753   struct remote_g_packet_guess new_guess, *guess;
11754   int ix;
11755
11756   gdb_assert (tdesc != NULL);
11757
11758   for (ix = 0;
11759        VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11760        ix++)
11761     if (guess->bytes == bytes)
11762       internal_error (__FILE__, __LINE__,
11763                       _("Duplicate g packet description added for size %d"),
11764                       bytes);
11765
11766   new_guess.bytes = bytes;
11767   new_guess.tdesc = tdesc;
11768   VEC_safe_push (remote_g_packet_guess_s, data->guesses, &new_guess);
11769 }
11770
11771 /* Return 1 if remote_read_description would do anything on this target
11772    and architecture, 0 otherwise.  */
11773
11774 static int
11775 remote_read_description_p (struct target_ops *target)
11776 {
11777   struct remote_g_packet_data *data
11778     = ((struct remote_g_packet_data *)
11779        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11780
11781   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11782     return 1;
11783
11784   return 0;
11785 }
11786
11787 const struct target_desc *
11788 remote_target::read_description ()
11789 {
11790   struct remote_g_packet_data *data
11791     = ((struct remote_g_packet_data *)
11792        gdbarch_data (target_gdbarch (), remote_g_packet_data_handle));
11793
11794   /* Do not try this during initial connection, when we do not know
11795      whether there is a running but stopped thread.  */
11796   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
11797     return beneath ()->read_description ();
11798
11799   if (!VEC_empty (remote_g_packet_guess_s, data->guesses))
11800     {
11801       struct remote_g_packet_guess *guess;
11802       int ix;
11803       int bytes = send_g_packet ();
11804
11805       for (ix = 0;
11806            VEC_iterate (remote_g_packet_guess_s, data->guesses, ix, guess);
11807            ix++)
11808         if (guess->bytes == bytes)
11809           return guess->tdesc;
11810
11811       /* We discard the g packet.  A minor optimization would be to
11812          hold on to it, and fill the register cache once we have selected
11813          an architecture, but it's too tricky to do safely.  */
11814     }
11815
11816   return beneath ()->read_description ();
11817 }
11818
11819 /* Remote file transfer support.  This is host-initiated I/O, not
11820    target-initiated; for target-initiated, see remote-fileio.c.  */
11821
11822 /* If *LEFT is at least the length of STRING, copy STRING to
11823    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11824    decrease *LEFT.  Otherwise raise an error.  */
11825
11826 static void
11827 remote_buffer_add_string (char **buffer, int *left, const char *string)
11828 {
11829   int len = strlen (string);
11830
11831   if (len > *left)
11832     error (_("Packet too long for target."));
11833
11834   memcpy (*buffer, string, len);
11835   *buffer += len;
11836   *left -= len;
11837
11838   /* NUL-terminate the buffer as a convenience, if there is
11839      room.  */
11840   if (*left)
11841     **buffer = '\0';
11842 }
11843
11844 /* If *LEFT is large enough, hex encode LEN bytes from BYTES into
11845    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11846    decrease *LEFT.  Otherwise raise an error.  */
11847
11848 static void
11849 remote_buffer_add_bytes (char **buffer, int *left, const gdb_byte *bytes,
11850                          int len)
11851 {
11852   if (2 * len > *left)
11853     error (_("Packet too long for target."));
11854
11855   bin2hex (bytes, *buffer, len);
11856   *buffer += 2 * len;
11857   *left -= 2 * len;
11858
11859   /* NUL-terminate the buffer as a convenience, if there is
11860      room.  */
11861   if (*left)
11862     **buffer = '\0';
11863 }
11864
11865 /* If *LEFT is large enough, convert VALUE to hex and add it to
11866    *BUFFER, update *BUFFER to point to the new end of the buffer, and
11867    decrease *LEFT.  Otherwise raise an error.  */
11868
11869 static void
11870 remote_buffer_add_int (char **buffer, int *left, ULONGEST value)
11871 {
11872   int len = hexnumlen (value);
11873
11874   if (len > *left)
11875     error (_("Packet too long for target."));
11876
11877   hexnumstr (*buffer, value);
11878   *buffer += len;
11879   *left -= len;
11880
11881   /* NUL-terminate the buffer as a convenience, if there is
11882      room.  */
11883   if (*left)
11884     **buffer = '\0';
11885 }
11886
11887 /* Parse an I/O result packet from BUFFER.  Set RETCODE to the return
11888    value, *REMOTE_ERRNO to the remote error number or zero if none
11889    was included, and *ATTACHMENT to point to the start of the annex
11890    if any.  The length of the packet isn't needed here; there may
11891    be NUL bytes in BUFFER, but they will be after *ATTACHMENT.
11892
11893    Return 0 if the packet could be parsed, -1 if it could not.  If
11894    -1 is returned, the other variables may not be initialized.  */
11895
11896 static int
11897 remote_hostio_parse_result (char *buffer, int *retcode,
11898                             int *remote_errno, char **attachment)
11899 {
11900   char *p, *p2;
11901
11902   *remote_errno = 0;
11903   *attachment = NULL;
11904
11905   if (buffer[0] != 'F')
11906     return -1;
11907
11908   errno = 0;
11909   *retcode = strtol (&buffer[1], &p, 16);
11910   if (errno != 0 || p == &buffer[1])
11911     return -1;
11912
11913   /* Check for ",errno".  */
11914   if (*p == ',')
11915     {
11916       errno = 0;
11917       *remote_errno = strtol (p + 1, &p2, 16);
11918       if (errno != 0 || p + 1 == p2)
11919         return -1;
11920       p = p2;
11921     }
11922
11923   /* Check for ";attachment".  If there is no attachment, the
11924      packet should end here.  */
11925   if (*p == ';')
11926     {
11927       *attachment = p + 1;
11928       return 0;
11929     }
11930   else if (*p == '\0')
11931     return 0;
11932   else
11933     return -1;
11934 }
11935
11936 /* Send a prepared I/O packet to the target and read its response.
11937    The prepared packet is in the global RS->BUF before this function
11938    is called, and the answer is there when we return.
11939
11940    COMMAND_BYTES is the length of the request to send, which may include
11941    binary data.  WHICH_PACKET is the packet configuration to check
11942    before attempting a packet.  If an error occurs, *REMOTE_ERRNO
11943    is set to the error number and -1 is returned.  Otherwise the value
11944    returned by the function is returned.
11945
11946    ATTACHMENT and ATTACHMENT_LEN should be non-NULL if and only if an
11947    attachment is expected; an error will be reported if there's a
11948    mismatch.  If one is found, *ATTACHMENT will be set to point into
11949    the packet buffer and *ATTACHMENT_LEN will be set to the
11950    attachment's length.  */
11951
11952 int
11953 remote_target::remote_hostio_send_command (int command_bytes, int which_packet,
11954                                            int *remote_errno, char **attachment,
11955                                            int *attachment_len)
11956 {
11957   struct remote_state *rs = get_remote_state ();
11958   int ret, bytes_read;
11959   char *attachment_tmp;
11960
11961   if (packet_support (which_packet) == PACKET_DISABLE)
11962     {
11963       *remote_errno = FILEIO_ENOSYS;
11964       return -1;
11965     }
11966
11967   putpkt_binary (rs->buf, command_bytes);
11968   bytes_read = getpkt_sane (&rs->buf, &rs->buf_size, 0);
11969
11970   /* If it timed out, something is wrong.  Don't try to parse the
11971      buffer.  */
11972   if (bytes_read < 0)
11973     {
11974       *remote_errno = FILEIO_EINVAL;
11975       return -1;
11976     }
11977
11978   switch (packet_ok (rs->buf, &remote_protocol_packets[which_packet]))
11979     {
11980     case PACKET_ERROR:
11981       *remote_errno = FILEIO_EINVAL;
11982       return -1;
11983     case PACKET_UNKNOWN:
11984       *remote_errno = FILEIO_ENOSYS;
11985       return -1;
11986     case PACKET_OK:
11987       break;
11988     }
11989
11990   if (remote_hostio_parse_result (rs->buf, &ret, remote_errno,
11991                                   &attachment_tmp))
11992     {
11993       *remote_errno = FILEIO_EINVAL;
11994       return -1;
11995     }
11996
11997   /* Make sure we saw an attachment if and only if we expected one.  */
11998   if ((attachment_tmp == NULL && attachment != NULL)
11999       || (attachment_tmp != NULL && attachment == NULL))
12000     {
12001       *remote_errno = FILEIO_EINVAL;
12002       return -1;
12003     }
12004
12005   /* If an attachment was found, it must point into the packet buffer;
12006      work out how many bytes there were.  */
12007   if (attachment_tmp != NULL)
12008     {
12009       *attachment = attachment_tmp;
12010       *attachment_len = bytes_read - (*attachment - rs->buf);
12011     }
12012
12013   return ret;
12014 }
12015
12016 /* See declaration.h.  */
12017
12018 void
12019 readahead_cache::invalidate ()
12020 {
12021   this->fd = -1;
12022 }
12023
12024 /* See declaration.h.  */
12025
12026 void
12027 readahead_cache::invalidate_fd (int fd)
12028 {
12029   if (this->fd == fd)
12030     this->fd = -1;
12031 }
12032
12033 /* Set the filesystem remote_hostio functions that take FILENAME
12034    arguments will use.  Return 0 on success, or -1 if an error
12035    occurs (and set *REMOTE_ERRNO).  */
12036
12037 int
12038 remote_target::remote_hostio_set_filesystem (struct inferior *inf,
12039                                              int *remote_errno)
12040 {
12041   struct remote_state *rs = get_remote_state ();
12042   int required_pid = (inf == NULL || inf->fake_pid_p) ? 0 : inf->pid;
12043   char *p = rs->buf;
12044   int left = get_remote_packet_size () - 1;
12045   char arg[9];
12046   int ret;
12047
12048   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12049     return 0;
12050
12051   if (rs->fs_pid != -1 && required_pid == rs->fs_pid)
12052     return 0;
12053
12054   remote_buffer_add_string (&p, &left, "vFile:setfs:");
12055
12056   xsnprintf (arg, sizeof (arg), "%x", required_pid);
12057   remote_buffer_add_string (&p, &left, arg);
12058
12059   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_setfs,
12060                                     remote_errno, NULL, NULL);
12061
12062   if (packet_support (PACKET_vFile_setfs) == PACKET_DISABLE)
12063     return 0;
12064
12065   if (ret == 0)
12066     rs->fs_pid = required_pid;
12067
12068   return ret;
12069 }
12070
12071 /* Implementation of to_fileio_open.  */
12072
12073 int
12074 remote_target::remote_hostio_open (inferior *inf, const char *filename,
12075                                    int flags, int mode, int warn_if_slow,
12076                                    int *remote_errno)
12077 {
12078   struct remote_state *rs = get_remote_state ();
12079   char *p = rs->buf;
12080   int left = get_remote_packet_size () - 1;
12081
12082   if (warn_if_slow)
12083     {
12084       static int warning_issued = 0;
12085
12086       printf_unfiltered (_("Reading %s from remote target...\n"),
12087                          filename);
12088
12089       if (!warning_issued)
12090         {
12091           warning (_("File transfers from remote targets can be slow."
12092                      " Use \"set sysroot\" to access files locally"
12093                      " instead."));
12094           warning_issued = 1;
12095         }
12096     }
12097
12098   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12099     return -1;
12100
12101   remote_buffer_add_string (&p, &left, "vFile:open:");
12102
12103   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12104                            strlen (filename));
12105   remote_buffer_add_string (&p, &left, ",");
12106
12107   remote_buffer_add_int (&p, &left, flags);
12108   remote_buffer_add_string (&p, &left, ",");
12109
12110   remote_buffer_add_int (&p, &left, mode);
12111
12112   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_open,
12113                                      remote_errno, NULL, NULL);
12114 }
12115
12116 int
12117 remote_target::fileio_open (struct inferior *inf, const char *filename,
12118                             int flags, int mode, int warn_if_slow,
12119                             int *remote_errno)
12120 {
12121   return remote_hostio_open (inf, filename, flags, mode, warn_if_slow,
12122                              remote_errno);
12123 }
12124
12125 /* Implementation of to_fileio_pwrite.  */
12126
12127 int
12128 remote_target::remote_hostio_pwrite (int fd, const gdb_byte *write_buf, int len,
12129                                      ULONGEST offset, int *remote_errno)
12130 {
12131   struct remote_state *rs = get_remote_state ();
12132   char *p = rs->buf;
12133   int left = get_remote_packet_size ();
12134   int out_len;
12135
12136   rs->readahead_cache.invalidate_fd (fd);
12137
12138   remote_buffer_add_string (&p, &left, "vFile:pwrite:");
12139
12140   remote_buffer_add_int (&p, &left, fd);
12141   remote_buffer_add_string (&p, &left, ",");
12142
12143   remote_buffer_add_int (&p, &left, offset);
12144   remote_buffer_add_string (&p, &left, ",");
12145
12146   p += remote_escape_output (write_buf, len, 1, (gdb_byte *) p, &out_len,
12147                              get_remote_packet_size () - (p - rs->buf));
12148
12149   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_pwrite,
12150                                      remote_errno, NULL, NULL);
12151 }
12152
12153 int
12154 remote_target::fileio_pwrite (int fd, const gdb_byte *write_buf, int len,
12155                               ULONGEST offset, int *remote_errno)
12156 {
12157   return remote_hostio_pwrite (fd, write_buf, len, offset, remote_errno);
12158 }
12159
12160 /* Helper for the implementation of to_fileio_pread.  Read the file
12161    from the remote side with vFile:pread.  */
12162
12163 int
12164 remote_target::remote_hostio_pread_vFile (int fd, gdb_byte *read_buf, int len,
12165                                           ULONGEST offset, int *remote_errno)
12166 {
12167   struct remote_state *rs = get_remote_state ();
12168   char *p = rs->buf;
12169   char *attachment;
12170   int left = get_remote_packet_size ();
12171   int ret, attachment_len;
12172   int read_len;
12173
12174   remote_buffer_add_string (&p, &left, "vFile:pread:");
12175
12176   remote_buffer_add_int (&p, &left, fd);
12177   remote_buffer_add_string (&p, &left, ",");
12178
12179   remote_buffer_add_int (&p, &left, len);
12180   remote_buffer_add_string (&p, &left, ",");
12181
12182   remote_buffer_add_int (&p, &left, offset);
12183
12184   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_pread,
12185                                     remote_errno, &attachment,
12186                                     &attachment_len);
12187
12188   if (ret < 0)
12189     return ret;
12190
12191   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12192                                     read_buf, len);
12193   if (read_len != ret)
12194     error (_("Read returned %d, but %d bytes."), ret, (int) read_len);
12195
12196   return ret;
12197 }
12198
12199 /* See declaration.h.  */
12200
12201 int
12202 readahead_cache::pread (int fd, gdb_byte *read_buf, size_t len,
12203                         ULONGEST offset)
12204 {
12205   if (this->fd == fd
12206       && this->offset <= offset
12207       && offset < this->offset + this->bufsize)
12208     {
12209       ULONGEST max = this->offset + this->bufsize;
12210
12211       if (offset + len > max)
12212         len = max - offset;
12213
12214       memcpy (read_buf, this->buf + offset - this->offset, len);
12215       return len;
12216     }
12217
12218   return 0;
12219 }
12220
12221 /* Implementation of to_fileio_pread.  */
12222
12223 int
12224 remote_target::remote_hostio_pread (int fd, gdb_byte *read_buf, int len,
12225                                     ULONGEST offset, int *remote_errno)
12226 {
12227   int ret;
12228   struct remote_state *rs = get_remote_state ();
12229   readahead_cache *cache = &rs->readahead_cache;
12230
12231   ret = cache->pread (fd, read_buf, len, offset);
12232   if (ret > 0)
12233     {
12234       cache->hit_count++;
12235
12236       if (remote_debug)
12237         fprintf_unfiltered (gdb_stdlog, "readahead cache hit %s\n",
12238                             pulongest (cache->hit_count));
12239       return ret;
12240     }
12241
12242   cache->miss_count++;
12243   if (remote_debug)
12244     fprintf_unfiltered (gdb_stdlog, "readahead cache miss %s\n",
12245                         pulongest (cache->miss_count));
12246
12247   cache->fd = fd;
12248   cache->offset = offset;
12249   cache->bufsize = get_remote_packet_size ();
12250   cache->buf = (gdb_byte *) xrealloc (cache->buf, cache->bufsize);
12251
12252   ret = remote_hostio_pread_vFile (cache->fd, cache->buf, cache->bufsize,
12253                                    cache->offset, remote_errno);
12254   if (ret <= 0)
12255     {
12256       cache->invalidate_fd (fd);
12257       return ret;
12258     }
12259
12260   cache->bufsize = ret;
12261   return cache->pread (fd, read_buf, len, offset);
12262 }
12263
12264 int
12265 remote_target::fileio_pread (int fd, gdb_byte *read_buf, int len,
12266                              ULONGEST offset, int *remote_errno)
12267 {
12268   return remote_hostio_pread (fd, read_buf, len, offset, remote_errno);
12269 }
12270
12271 /* Implementation of to_fileio_close.  */
12272
12273 int
12274 remote_target::remote_hostio_close (int fd, int *remote_errno)
12275 {
12276   struct remote_state *rs = get_remote_state ();
12277   char *p = rs->buf;
12278   int left = get_remote_packet_size () - 1;
12279
12280   rs->readahead_cache.invalidate_fd (fd);
12281
12282   remote_buffer_add_string (&p, &left, "vFile:close:");
12283
12284   remote_buffer_add_int (&p, &left, fd);
12285
12286   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_close,
12287                                      remote_errno, NULL, NULL);
12288 }
12289
12290 int
12291 remote_target::fileio_close (int fd, int *remote_errno)
12292 {
12293   return remote_hostio_close (fd, remote_errno);
12294 }
12295
12296 /* Implementation of to_fileio_unlink.  */
12297
12298 int
12299 remote_target::remote_hostio_unlink (inferior *inf, const char *filename,
12300                                      int *remote_errno)
12301 {
12302   struct remote_state *rs = get_remote_state ();
12303   char *p = rs->buf;
12304   int left = get_remote_packet_size () - 1;
12305
12306   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12307     return -1;
12308
12309   remote_buffer_add_string (&p, &left, "vFile:unlink:");
12310
12311   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12312                            strlen (filename));
12313
12314   return remote_hostio_send_command (p - rs->buf, PACKET_vFile_unlink,
12315                                      remote_errno, NULL, NULL);
12316 }
12317
12318 int
12319 remote_target::fileio_unlink (struct inferior *inf, const char *filename,
12320                               int *remote_errno)
12321 {
12322   return remote_hostio_unlink (inf, filename, remote_errno);
12323 }
12324
12325 /* Implementation of to_fileio_readlink.  */
12326
12327 gdb::optional<std::string>
12328 remote_target::fileio_readlink (struct inferior *inf, const char *filename,
12329                                 int *remote_errno)
12330 {
12331   struct remote_state *rs = get_remote_state ();
12332   char *p = rs->buf;
12333   char *attachment;
12334   int left = get_remote_packet_size ();
12335   int len, attachment_len;
12336   int read_len;
12337
12338   if (remote_hostio_set_filesystem (inf, remote_errno) != 0)
12339     return {};
12340
12341   remote_buffer_add_string (&p, &left, "vFile:readlink:");
12342
12343   remote_buffer_add_bytes (&p, &left, (const gdb_byte *) filename,
12344                            strlen (filename));
12345
12346   len = remote_hostio_send_command (p - rs->buf, PACKET_vFile_readlink,
12347                                     remote_errno, &attachment,
12348                                     &attachment_len);
12349
12350   if (len < 0)
12351     return {};
12352
12353   std::string ret (len, '\0');
12354
12355   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12356                                     (gdb_byte *) &ret[0], len);
12357   if (read_len != len)
12358     error (_("Readlink returned %d, but %d bytes."), len, read_len);
12359
12360   return ret;
12361 }
12362
12363 /* Implementation of to_fileio_fstat.  */
12364
12365 int
12366 remote_target::fileio_fstat (int fd, struct stat *st, int *remote_errno)
12367 {
12368   struct remote_state *rs = get_remote_state ();
12369   char *p = rs->buf;
12370   int left = get_remote_packet_size ();
12371   int attachment_len, ret;
12372   char *attachment;
12373   struct fio_stat fst;
12374   int read_len;
12375
12376   remote_buffer_add_string (&p, &left, "vFile:fstat:");
12377
12378   remote_buffer_add_int (&p, &left, fd);
12379
12380   ret = remote_hostio_send_command (p - rs->buf, PACKET_vFile_fstat,
12381                                     remote_errno, &attachment,
12382                                     &attachment_len);
12383   if (ret < 0)
12384     {
12385       if (*remote_errno != FILEIO_ENOSYS)
12386         return ret;
12387
12388       /* Strictly we should return -1, ENOSYS here, but when
12389          "set sysroot remote:" was implemented in August 2008
12390          BFD's need for a stat function was sidestepped with
12391          this hack.  This was not remedied until March 2015
12392          so we retain the previous behavior to avoid breaking
12393          compatibility.
12394
12395          Note that the memset is a March 2015 addition; older
12396          GDBs set st_size *and nothing else* so the structure
12397          would have garbage in all other fields.  This might
12398          break something but retaining the previous behavior
12399          here would be just too wrong.  */
12400
12401       memset (st, 0, sizeof (struct stat));
12402       st->st_size = INT_MAX;
12403       return 0;
12404     }
12405
12406   read_len = remote_unescape_input ((gdb_byte *) attachment, attachment_len,
12407                                     (gdb_byte *) &fst, sizeof (fst));
12408
12409   if (read_len != ret)
12410     error (_("vFile:fstat returned %d, but %d bytes."), ret, read_len);
12411
12412   if (read_len != sizeof (fst))
12413     error (_("vFile:fstat returned %d bytes, but expecting %d."),
12414            read_len, (int) sizeof (fst));
12415
12416   remote_fileio_to_host_stat (&fst, st);
12417
12418   return 0;
12419 }
12420
12421 /* Implementation of to_filesystem_is_local.  */
12422
12423 bool
12424 remote_target::filesystem_is_local ()
12425 {
12426   /* Valgrind GDB presents itself as a remote target but works
12427      on the local filesystem: it does not implement remote get
12428      and users are not expected to set a sysroot.  To handle
12429      this case we treat the remote filesystem as local if the
12430      sysroot is exactly TARGET_SYSROOT_PREFIX and if the stub
12431      does not support vFile:open.  */
12432   if (strcmp (gdb_sysroot, TARGET_SYSROOT_PREFIX) == 0)
12433     {
12434       enum packet_support ps = packet_support (PACKET_vFile_open);
12435
12436       if (ps == PACKET_SUPPORT_UNKNOWN)
12437         {
12438           int fd, remote_errno;
12439
12440           /* Try opening a file to probe support.  The supplied
12441              filename is irrelevant, we only care about whether
12442              the stub recognizes the packet or not.  */
12443           fd = remote_hostio_open (NULL, "just probing",
12444                                    FILEIO_O_RDONLY, 0700, 0,
12445                                    &remote_errno);
12446
12447           if (fd >= 0)
12448             remote_hostio_close (fd, &remote_errno);
12449
12450           ps = packet_support (PACKET_vFile_open);
12451         }
12452
12453       if (ps == PACKET_DISABLE)
12454         {
12455           static int warning_issued = 0;
12456
12457           if (!warning_issued)
12458             {
12459               warning (_("remote target does not support file"
12460                          " transfer, attempting to access files"
12461                          " from local filesystem."));
12462               warning_issued = 1;
12463             }
12464
12465           return true;
12466         }
12467     }
12468
12469   return false;
12470 }
12471
12472 static int
12473 remote_fileio_errno_to_host (int errnum)
12474 {
12475   switch (errnum)
12476     {
12477       case FILEIO_EPERM:
12478         return EPERM;
12479       case FILEIO_ENOENT:
12480         return ENOENT;
12481       case FILEIO_EINTR:
12482         return EINTR;
12483       case FILEIO_EIO:
12484         return EIO;
12485       case FILEIO_EBADF:
12486         return EBADF;
12487       case FILEIO_EACCES:
12488         return EACCES;
12489       case FILEIO_EFAULT:
12490         return EFAULT;
12491       case FILEIO_EBUSY:
12492         return EBUSY;
12493       case FILEIO_EEXIST:
12494         return EEXIST;
12495       case FILEIO_ENODEV:
12496         return ENODEV;
12497       case FILEIO_ENOTDIR:
12498         return ENOTDIR;
12499       case FILEIO_EISDIR:
12500         return EISDIR;
12501       case FILEIO_EINVAL:
12502         return EINVAL;
12503       case FILEIO_ENFILE:
12504         return ENFILE;
12505       case FILEIO_EMFILE:
12506         return EMFILE;
12507       case FILEIO_EFBIG:
12508         return EFBIG;
12509       case FILEIO_ENOSPC:
12510         return ENOSPC;
12511       case FILEIO_ESPIPE:
12512         return ESPIPE;
12513       case FILEIO_EROFS:
12514         return EROFS;
12515       case FILEIO_ENOSYS:
12516         return ENOSYS;
12517       case FILEIO_ENAMETOOLONG:
12518         return ENAMETOOLONG;
12519     }
12520   return -1;
12521 }
12522
12523 static char *
12524 remote_hostio_error (int errnum)
12525 {
12526   int host_error = remote_fileio_errno_to_host (errnum);
12527
12528   if (host_error == -1)
12529     error (_("Unknown remote I/O error %d"), errnum);
12530   else
12531     error (_("Remote I/O error: %s"), safe_strerror (host_error));
12532 }
12533
12534 /* A RAII wrapper around a remote file descriptor.  */
12535
12536 class scoped_remote_fd
12537 {
12538 public:
12539   scoped_remote_fd (remote_target *remote, int fd)
12540     : m_remote (remote), m_fd (fd)
12541   {
12542   }
12543
12544   ~scoped_remote_fd ()
12545   {
12546     if (m_fd != -1)
12547       {
12548         try
12549           {
12550             int remote_errno;
12551             m_remote->remote_hostio_close (m_fd, &remote_errno);
12552           }
12553         catch (...)
12554           {
12555             /* Swallow exception before it escapes the dtor.  If
12556                something goes wrong, likely the connection is gone,
12557                and there's nothing else that can be done.  */
12558           }
12559       }
12560   }
12561
12562   DISABLE_COPY_AND_ASSIGN (scoped_remote_fd);
12563
12564   /* Release ownership of the file descriptor, and return it.  */
12565   int release () noexcept
12566   {
12567     int fd = m_fd;
12568     m_fd = -1;
12569     return fd;
12570   }
12571
12572   /* Return the owned file descriptor.  */
12573   int get () const noexcept
12574   {
12575     return m_fd;
12576   }
12577
12578 private:
12579   /* The remote target.  */
12580   remote_target *m_remote;
12581
12582   /* The owned remote I/O file descriptor.  */
12583   int m_fd;
12584 };
12585
12586 void
12587 remote_file_put (const char *local_file, const char *remote_file, int from_tty)
12588 {
12589   remote_target *remote = get_current_remote_target ();
12590
12591   if (remote == nullptr)
12592     error (_("command can only be used with remote target"));
12593
12594   remote->remote_file_put (local_file, remote_file, from_tty);
12595 }
12596
12597 void
12598 remote_target::remote_file_put (const char *local_file, const char *remote_file,
12599                                 int from_tty)
12600 {
12601   int retcode, remote_errno, bytes, io_size;
12602   int bytes_in_buffer;
12603   int saw_eof;
12604   ULONGEST offset;
12605
12606   gdb_file_up file = gdb_fopen_cloexec (local_file, "rb");
12607   if (file == NULL)
12608     perror_with_name (local_file);
12609
12610   scoped_remote_fd fd
12611     (this, remote_hostio_open (NULL,
12612                                remote_file, (FILEIO_O_WRONLY | FILEIO_O_CREAT
12613                                              | FILEIO_O_TRUNC),
12614                                0700, 0, &remote_errno));
12615   if (fd.get () == -1)
12616     remote_hostio_error (remote_errno);
12617
12618   /* Send up to this many bytes at once.  They won't all fit in the
12619      remote packet limit, so we'll transfer slightly fewer.  */
12620   io_size = get_remote_packet_size ();
12621   gdb::byte_vector buffer (io_size);
12622
12623   bytes_in_buffer = 0;
12624   saw_eof = 0;
12625   offset = 0;
12626   while (bytes_in_buffer || !saw_eof)
12627     {
12628       if (!saw_eof)
12629         {
12630           bytes = fread (buffer.data () + bytes_in_buffer, 1,
12631                          io_size - bytes_in_buffer,
12632                          file.get ());
12633           if (bytes == 0)
12634             {
12635               if (ferror (file.get ()))
12636                 error (_("Error reading %s."), local_file);
12637               else
12638                 {
12639                   /* EOF.  Unless there is something still in the
12640                      buffer from the last iteration, we are done.  */
12641                   saw_eof = 1;
12642                   if (bytes_in_buffer == 0)
12643                     break;
12644                 }
12645             }
12646         }
12647       else
12648         bytes = 0;
12649
12650       bytes += bytes_in_buffer;
12651       bytes_in_buffer = 0;
12652
12653       retcode = remote_hostio_pwrite (fd.get (), buffer.data (), bytes,
12654                                       offset, &remote_errno);
12655
12656       if (retcode < 0)
12657         remote_hostio_error (remote_errno);
12658       else if (retcode == 0)
12659         error (_("Remote write of %d bytes returned 0!"), bytes);
12660       else if (retcode < bytes)
12661         {
12662           /* Short write.  Save the rest of the read data for the next
12663              write.  */
12664           bytes_in_buffer = bytes - retcode;
12665           memmove (buffer.data (), buffer.data () + retcode, bytes_in_buffer);
12666         }
12667
12668       offset += retcode;
12669     }
12670
12671   if (remote_hostio_close (fd.release (), &remote_errno))
12672     remote_hostio_error (remote_errno);
12673
12674   if (from_tty)
12675     printf_filtered (_("Successfully sent file \"%s\".\n"), local_file);
12676 }
12677
12678 void
12679 remote_file_get (const char *remote_file, const char *local_file, int from_tty)
12680 {
12681   remote_target *remote = get_current_remote_target ();
12682
12683   if (remote == nullptr)
12684     error (_("command can only be used with remote target"));
12685
12686   remote->remote_file_get (remote_file, local_file, from_tty);
12687 }
12688
12689 void
12690 remote_target::remote_file_get (const char *remote_file, const char *local_file,
12691                                 int from_tty)
12692 {
12693   int remote_errno, bytes, io_size;
12694   ULONGEST offset;
12695
12696   scoped_remote_fd fd
12697     (this, remote_hostio_open (NULL,
12698                                remote_file, FILEIO_O_RDONLY, 0, 0,
12699                                &remote_errno));
12700   if (fd.get () == -1)
12701     remote_hostio_error (remote_errno);
12702
12703   gdb_file_up file = gdb_fopen_cloexec (local_file, "wb");
12704   if (file == NULL)
12705     perror_with_name (local_file);
12706
12707   /* Send up to this many bytes at once.  They won't all fit in the
12708      remote packet limit, so we'll transfer slightly fewer.  */
12709   io_size = get_remote_packet_size ();
12710   gdb::byte_vector buffer (io_size);
12711
12712   offset = 0;
12713   while (1)
12714     {
12715       bytes = remote_hostio_pread (fd.get (), buffer.data (), io_size, offset,
12716                                    &remote_errno);
12717       if (bytes == 0)
12718         /* Success, but no bytes, means end-of-file.  */
12719         break;
12720       if (bytes == -1)
12721         remote_hostio_error (remote_errno);
12722
12723       offset += bytes;
12724
12725       bytes = fwrite (buffer.data (), 1, bytes, file.get ());
12726       if (bytes == 0)
12727         perror_with_name (local_file);
12728     }
12729
12730   if (remote_hostio_close (fd.release (), &remote_errno))
12731     remote_hostio_error (remote_errno);
12732
12733   if (from_tty)
12734     printf_filtered (_("Successfully fetched file \"%s\".\n"), remote_file);
12735 }
12736
12737 void
12738 remote_file_delete (const char *remote_file, int from_tty)
12739 {
12740   remote_target *remote = get_current_remote_target ();
12741
12742   if (remote == nullptr)
12743     error (_("command can only be used with remote target"));
12744
12745   remote->remote_file_delete (remote_file, from_tty);
12746 }
12747
12748 void
12749 remote_target::remote_file_delete (const char *remote_file, int from_tty)
12750 {
12751   int retcode, remote_errno;
12752
12753   retcode = remote_hostio_unlink (NULL, remote_file, &remote_errno);
12754   if (retcode == -1)
12755     remote_hostio_error (remote_errno);
12756
12757   if (from_tty)
12758     printf_filtered (_("Successfully deleted file \"%s\".\n"), remote_file);
12759 }
12760
12761 static void
12762 remote_put_command (const char *args, int from_tty)
12763 {
12764   if (args == NULL)
12765     error_no_arg (_("file to put"));
12766
12767   gdb_argv argv (args);
12768   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12769     error (_("Invalid parameters to remote put"));
12770
12771   remote_file_put (argv[0], argv[1], from_tty);
12772 }
12773
12774 static void
12775 remote_get_command (const char *args, int from_tty)
12776 {
12777   if (args == NULL)
12778     error_no_arg (_("file to get"));
12779
12780   gdb_argv argv (args);
12781   if (argv[0] == NULL || argv[1] == NULL || argv[2] != NULL)
12782     error (_("Invalid parameters to remote get"));
12783
12784   remote_file_get (argv[0], argv[1], from_tty);
12785 }
12786
12787 static void
12788 remote_delete_command (const char *args, int from_tty)
12789 {
12790   if (args == NULL)
12791     error_no_arg (_("file to delete"));
12792
12793   gdb_argv argv (args);
12794   if (argv[0] == NULL || argv[1] != NULL)
12795     error (_("Invalid parameters to remote delete"));
12796
12797   remote_file_delete (argv[0], from_tty);
12798 }
12799
12800 static void
12801 remote_command (const char *args, int from_tty)
12802 {
12803   help_list (remote_cmdlist, "remote ", all_commands, gdb_stdout);
12804 }
12805
12806 bool
12807 remote_target::can_execute_reverse ()
12808 {
12809   if (packet_support (PACKET_bs) == PACKET_ENABLE
12810       || packet_support (PACKET_bc) == PACKET_ENABLE)
12811     return true;
12812   else
12813     return false;
12814 }
12815
12816 bool
12817 remote_target::supports_non_stop ()
12818 {
12819   return true;
12820 }
12821
12822 bool
12823 remote_target::supports_disable_randomization ()
12824 {
12825   /* Only supported in extended mode.  */
12826   return false;
12827 }
12828
12829 bool
12830 remote_target::supports_multi_process ()
12831 {
12832   struct remote_state *rs = get_remote_state ();
12833
12834   return remote_multi_process_p (rs);
12835 }
12836
12837 static int
12838 remote_supports_cond_tracepoints ()
12839 {
12840   return packet_support (PACKET_ConditionalTracepoints) == PACKET_ENABLE;
12841 }
12842
12843 bool
12844 remote_target::supports_evaluation_of_breakpoint_conditions ()
12845 {
12846   return packet_support (PACKET_ConditionalBreakpoints) == PACKET_ENABLE;
12847 }
12848
12849 static int
12850 remote_supports_fast_tracepoints ()
12851 {
12852   return packet_support (PACKET_FastTracepoints) == PACKET_ENABLE;
12853 }
12854
12855 static int
12856 remote_supports_static_tracepoints ()
12857 {
12858   return packet_support (PACKET_StaticTracepoints) == PACKET_ENABLE;
12859 }
12860
12861 static int
12862 remote_supports_install_in_trace ()
12863 {
12864   return packet_support (PACKET_InstallInTrace) == PACKET_ENABLE;
12865 }
12866
12867 bool
12868 remote_target::supports_enable_disable_tracepoint ()
12869 {
12870   return (packet_support (PACKET_EnableDisableTracepoints_feature)
12871           == PACKET_ENABLE);
12872 }
12873
12874 bool
12875 remote_target::supports_string_tracing ()
12876 {
12877   return packet_support (PACKET_tracenz_feature) == PACKET_ENABLE;
12878 }
12879
12880 bool
12881 remote_target::can_run_breakpoint_commands ()
12882 {
12883   return packet_support (PACKET_BreakpointCommands) == PACKET_ENABLE;
12884 }
12885
12886 void
12887 remote_target::trace_init ()
12888 {
12889   struct remote_state *rs = get_remote_state ();
12890
12891   putpkt ("QTinit");
12892   remote_get_noisy_reply ();
12893   if (strcmp (rs->buf, "OK") != 0)
12894     error (_("Target does not support this command."));
12895 }
12896
12897 /* Recursive routine to walk through command list including loops, and
12898    download packets for each command.  */
12899
12900 void
12901 remote_target::remote_download_command_source (int num, ULONGEST addr,
12902                                                struct command_line *cmds)
12903 {
12904   struct remote_state *rs = get_remote_state ();
12905   struct command_line *cmd;
12906
12907   for (cmd = cmds; cmd; cmd = cmd->next)
12908     {
12909       QUIT;     /* Allow user to bail out with ^C.  */
12910       strcpy (rs->buf, "QTDPsrc:");
12911       encode_source_string (num, addr, "cmd", cmd->line,
12912                             rs->buf + strlen (rs->buf),
12913                             rs->buf_size - strlen (rs->buf));
12914       putpkt (rs->buf);
12915       remote_get_noisy_reply ();
12916       if (strcmp (rs->buf, "OK"))
12917         warning (_("Target does not support source download."));
12918
12919       if (cmd->control_type == while_control
12920           || cmd->control_type == while_stepping_control)
12921         {
12922           remote_download_command_source (num, addr, cmd->body_list_0.get ());
12923
12924           QUIT; /* Allow user to bail out with ^C.  */
12925           strcpy (rs->buf, "QTDPsrc:");
12926           encode_source_string (num, addr, "cmd", "end",
12927                                 rs->buf + strlen (rs->buf),
12928                                 rs->buf_size - strlen (rs->buf));
12929           putpkt (rs->buf);
12930           remote_get_noisy_reply ();
12931           if (strcmp (rs->buf, "OK"))
12932             warning (_("Target does not support source download."));
12933         }
12934     }
12935 }
12936
12937 void
12938 remote_target::download_tracepoint (struct bp_location *loc)
12939 {
12940 #define BUF_SIZE 2048
12941
12942   CORE_ADDR tpaddr;
12943   char addrbuf[40];
12944   char buf[BUF_SIZE];
12945   std::vector<std::string> tdp_actions;
12946   std::vector<std::string> stepping_actions;
12947   char *pkt;
12948   struct breakpoint *b = loc->owner;
12949   struct tracepoint *t = (struct tracepoint *) b;
12950   struct remote_state *rs = get_remote_state ();
12951
12952   encode_actions_rsp (loc, &tdp_actions, &stepping_actions);
12953
12954   tpaddr = loc->address;
12955   sprintf_vma (addrbuf, tpaddr);
12956   xsnprintf (buf, BUF_SIZE, "QTDP:%x:%s:%c:%lx:%x", b->number,
12957              addrbuf, /* address */
12958              (b->enable_state == bp_enabled ? 'E' : 'D'),
12959              t->step_count, t->pass_count);
12960   /* Fast tracepoints are mostly handled by the target, but we can
12961      tell the target how big of an instruction block should be moved
12962      around.  */
12963   if (b->type == bp_fast_tracepoint)
12964     {
12965       /* Only test for support at download time; we may not know
12966          target capabilities at definition time.  */
12967       if (remote_supports_fast_tracepoints ())
12968         {
12969           if (gdbarch_fast_tracepoint_valid_at (loc->gdbarch, tpaddr,
12970                                                 NULL))
12971             xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":F%x",
12972                        gdb_insn_length (loc->gdbarch, tpaddr));
12973           else
12974             /* If it passed validation at definition but fails now,
12975                something is very wrong.  */
12976             internal_error (__FILE__, __LINE__,
12977                             _("Fast tracepoint not "
12978                               "valid during download"));
12979         }
12980       else
12981         /* Fast tracepoints are functionally identical to regular
12982            tracepoints, so don't take lack of support as a reason to
12983            give up on the trace run.  */
12984         warning (_("Target does not support fast tracepoints, "
12985                    "downloading %d as regular tracepoint"), b->number);
12986     }
12987   else if (b->type == bp_static_tracepoint)
12988     {
12989       /* Only test for support at download time; we may not know
12990          target capabilities at definition time.  */
12991       if (remote_supports_static_tracepoints ())
12992         {
12993           struct static_tracepoint_marker marker;
12994
12995           if (target_static_tracepoint_marker_at (tpaddr, &marker))
12996             strcat (buf, ":S");
12997           else
12998             error (_("Static tracepoint not valid during download"));
12999         }
13000       else
13001         /* Fast tracepoints are functionally identical to regular
13002            tracepoints, so don't take lack of support as a reason
13003            to give up on the trace run.  */
13004         error (_("Target does not support static tracepoints"));
13005     }
13006   /* If the tracepoint has a conditional, make it into an agent
13007      expression and append to the definition.  */
13008   if (loc->cond)
13009     {
13010       /* Only test support at download time, we may not know target
13011          capabilities at definition time.  */
13012       if (remote_supports_cond_tracepoints ())
13013         {
13014           agent_expr_up aexpr = gen_eval_for_expr (tpaddr, loc->cond.get ());
13015           xsnprintf (buf + strlen (buf), BUF_SIZE - strlen (buf), ":X%x,",
13016                      aexpr->len);
13017           pkt = buf + strlen (buf);
13018           for (int ndx = 0; ndx < aexpr->len; ++ndx)
13019             pkt = pack_hex_byte (pkt, aexpr->buf[ndx]);
13020           *pkt = '\0';
13021         }
13022       else
13023         warning (_("Target does not support conditional tracepoints, "
13024                    "ignoring tp %d cond"), b->number);
13025     }
13026
13027   if (b->commands || *default_collect)
13028     strcat (buf, "-");
13029   putpkt (buf);
13030   remote_get_noisy_reply ();
13031   if (strcmp (rs->buf, "OK"))
13032     error (_("Target does not support tracepoints."));
13033
13034   /* do_single_steps (t); */
13035   for (auto action_it = tdp_actions.begin ();
13036        action_it != tdp_actions.end (); action_it++)
13037     {
13038       QUIT;     /* Allow user to bail out with ^C.  */
13039
13040       bool has_more = (action_it != tdp_actions.end ()
13041                        || !stepping_actions.empty ());
13042
13043       xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%c",
13044                  b->number, addrbuf, /* address */
13045                  action_it->c_str (),
13046                  has_more ? '-' : 0);
13047       putpkt (buf);
13048       remote_get_noisy_reply ();
13049       if (strcmp (rs->buf, "OK"))
13050         error (_("Error on target while setting tracepoints."));
13051     }
13052
13053     for (auto action_it = stepping_actions.begin ();
13054          action_it != stepping_actions.end (); action_it++)
13055       {
13056         QUIT;   /* Allow user to bail out with ^C.  */
13057
13058         bool is_first = action_it == stepping_actions.begin ();
13059         bool has_more = action_it != stepping_actions.end ();
13060
13061         xsnprintf (buf, BUF_SIZE, "QTDP:-%x:%s:%s%s%s",
13062                    b->number, addrbuf, /* address */
13063                    is_first ? "S" : "",
13064                    action_it->c_str (),
13065                    has_more ? "-" : "");
13066         putpkt (buf);
13067         remote_get_noisy_reply ();
13068         if (strcmp (rs->buf, "OK"))
13069           error (_("Error on target while setting tracepoints."));
13070       }
13071
13072   if (packet_support (PACKET_TracepointSource) == PACKET_ENABLE)
13073     {
13074       if (b->location != NULL)
13075         {
13076           strcpy (buf, "QTDPsrc:");
13077           encode_source_string (b->number, loc->address, "at",
13078                                 event_location_to_string (b->location.get ()),
13079                                 buf + strlen (buf), 2048 - strlen (buf));
13080           putpkt (buf);
13081           remote_get_noisy_reply ();
13082           if (strcmp (rs->buf, "OK"))
13083             warning (_("Target does not support source download."));
13084         }
13085       if (b->cond_string)
13086         {
13087           strcpy (buf, "QTDPsrc:");
13088           encode_source_string (b->number, loc->address,
13089                                 "cond", b->cond_string, buf + strlen (buf),
13090                                 2048 - strlen (buf));
13091           putpkt (buf);
13092           remote_get_noisy_reply ();
13093           if (strcmp (rs->buf, "OK"))
13094             warning (_("Target does not support source download."));
13095         }
13096       remote_download_command_source (b->number, loc->address,
13097                                       breakpoint_commands (b));
13098     }
13099 }
13100
13101 bool
13102 remote_target::can_download_tracepoint ()
13103 {
13104   struct remote_state *rs = get_remote_state ();
13105   struct trace_status *ts;
13106   int status;
13107
13108   /* Don't try to install tracepoints until we've relocated our
13109      symbols, and fetched and merged the target's tracepoint list with
13110      ours.  */
13111   if (rs->starting_up)
13112     return false;
13113
13114   ts = current_trace_status ();
13115   status = get_trace_status (ts);
13116
13117   if (status == -1 || !ts->running_known || !ts->running)
13118     return false;
13119
13120   /* If we are in a tracing experiment, but remote stub doesn't support
13121      installing tracepoint in trace, we have to return.  */
13122   if (!remote_supports_install_in_trace ())
13123     return false;
13124
13125   return true;
13126 }
13127
13128
13129 void
13130 remote_target::download_trace_state_variable (const trace_state_variable &tsv)
13131 {
13132   struct remote_state *rs = get_remote_state ();
13133   char *p;
13134
13135   xsnprintf (rs->buf, get_remote_packet_size (), "QTDV:%x:%s:%x:",
13136              tsv.number, phex ((ULONGEST) tsv.initial_value, 8),
13137              tsv.builtin);
13138   p = rs->buf + strlen (rs->buf);
13139   if ((p - rs->buf) + tsv.name.length () * 2 >= get_remote_packet_size ())
13140     error (_("Trace state variable name too long for tsv definition packet"));
13141   p += 2 * bin2hex ((gdb_byte *) (tsv.name.data ()), p, tsv.name.length ());
13142   *p++ = '\0';
13143   putpkt (rs->buf);
13144   remote_get_noisy_reply ();
13145   if (*rs->buf == '\0')
13146     error (_("Target does not support this command."));
13147   if (strcmp (rs->buf, "OK") != 0)
13148     error (_("Error on target while downloading trace state variable."));
13149 }
13150
13151 void
13152 remote_target::enable_tracepoint (struct bp_location *location)
13153 {
13154   struct remote_state *rs = get_remote_state ();
13155   char addr_buf[40];
13156
13157   sprintf_vma (addr_buf, location->address);
13158   xsnprintf (rs->buf, get_remote_packet_size (), "QTEnable:%x:%s",
13159              location->owner->number, addr_buf);
13160   putpkt (rs->buf);
13161   remote_get_noisy_reply ();
13162   if (*rs->buf == '\0')
13163     error (_("Target does not support enabling tracepoints while a trace run is ongoing."));
13164   if (strcmp (rs->buf, "OK") != 0)
13165     error (_("Error on target while enabling tracepoint."));
13166 }
13167
13168 void
13169 remote_target::disable_tracepoint (struct bp_location *location)
13170 {
13171   struct remote_state *rs = get_remote_state ();
13172   char addr_buf[40];
13173
13174   sprintf_vma (addr_buf, location->address);
13175   xsnprintf (rs->buf, get_remote_packet_size (), "QTDisable:%x:%s",
13176              location->owner->number, addr_buf);
13177   putpkt (rs->buf);
13178   remote_get_noisy_reply ();
13179   if (*rs->buf == '\0')
13180     error (_("Target does not support disabling tracepoints while a trace run is ongoing."));
13181   if (strcmp (rs->buf, "OK") != 0)
13182     error (_("Error on target while disabling tracepoint."));
13183 }
13184
13185 void
13186 remote_target::trace_set_readonly_regions ()
13187 {
13188   asection *s;
13189   bfd *abfd = NULL;
13190   bfd_size_type size;
13191   bfd_vma vma;
13192   int anysecs = 0;
13193   int offset = 0;
13194
13195   if (!exec_bfd)
13196     return;                     /* No information to give.  */
13197
13198   struct remote_state *rs = get_remote_state ();
13199
13200   strcpy (rs->buf, "QTro");
13201   offset = strlen (rs->buf);
13202   for (s = exec_bfd->sections; s; s = s->next)
13203     {
13204       char tmp1[40], tmp2[40];
13205       int sec_length;
13206
13207       if ((s->flags & SEC_LOAD) == 0 ||
13208       /*  (s->flags & SEC_CODE) == 0 || */
13209           (s->flags & SEC_READONLY) == 0)
13210         continue;
13211
13212       anysecs = 1;
13213       vma = bfd_get_section_vma (abfd, s);
13214       size = bfd_get_section_size (s);
13215       sprintf_vma (tmp1, vma);
13216       sprintf_vma (tmp2, vma + size);
13217       sec_length = 1 + strlen (tmp1) + 1 + strlen (tmp2);
13218       if (offset + sec_length + 1 > rs->buf_size)
13219         {
13220           if (packet_support (PACKET_qXfer_traceframe_info) != PACKET_ENABLE)
13221             warning (_("\
13222 Too many sections for read-only sections definition packet."));
13223           break;
13224         }
13225       xsnprintf (rs->buf + offset, rs->buf_size - offset, ":%s,%s",
13226                  tmp1, tmp2);
13227       offset += sec_length;
13228     }
13229   if (anysecs)
13230     {
13231       putpkt (rs->buf);
13232       getpkt (&rs->buf, &rs->buf_size, 0);
13233     }
13234 }
13235
13236 void
13237 remote_target::trace_start ()
13238 {
13239   struct remote_state *rs = get_remote_state ();
13240
13241   putpkt ("QTStart");
13242   remote_get_noisy_reply ();
13243   if (*rs->buf == '\0')
13244     error (_("Target does not support this command."));
13245   if (strcmp (rs->buf, "OK") != 0)
13246     error (_("Bogus reply from target: %s"), rs->buf);
13247 }
13248
13249 int
13250 remote_target::get_trace_status (struct trace_status *ts)
13251 {
13252   /* Initialize it just to avoid a GCC false warning.  */
13253   char *p = NULL;
13254   /* FIXME we need to get register block size some other way.  */
13255   extern int trace_regblock_size;
13256   enum packet_result result;
13257   struct remote_state *rs = get_remote_state ();
13258
13259   if (packet_support (PACKET_qTStatus) == PACKET_DISABLE)
13260     return -1;
13261
13262   trace_regblock_size
13263     = rs->get_remote_arch_state (target_gdbarch ())->sizeof_g_packet;
13264
13265   putpkt ("qTStatus");
13266
13267   TRY
13268     {
13269       p = remote_get_noisy_reply ();
13270     }
13271   CATCH (ex, RETURN_MASK_ERROR)
13272     {
13273       if (ex.error != TARGET_CLOSE_ERROR)
13274         {
13275           exception_fprintf (gdb_stderr, ex, "qTStatus: ");
13276           return -1;
13277         }
13278       throw_exception (ex);
13279     }
13280   END_CATCH
13281
13282   result = packet_ok (p, &remote_protocol_packets[PACKET_qTStatus]);
13283
13284   /* If the remote target doesn't do tracing, flag it.  */
13285   if (result == PACKET_UNKNOWN)
13286     return -1;
13287
13288   /* We're working with a live target.  */
13289   ts->filename = NULL;
13290
13291   if (*p++ != 'T')
13292     error (_("Bogus trace status reply from target: %s"), rs->buf);
13293
13294   /* Function 'parse_trace_status' sets default value of each field of
13295      'ts' at first, so we don't have to do it here.  */
13296   parse_trace_status (p, ts);
13297
13298   return ts->running;
13299 }
13300
13301 void
13302 remote_target::get_tracepoint_status (struct breakpoint *bp,
13303                                       struct uploaded_tp *utp)
13304 {
13305   struct remote_state *rs = get_remote_state ();
13306   char *reply;
13307   struct bp_location *loc;
13308   struct tracepoint *tp = (struct tracepoint *) bp;
13309   size_t size = get_remote_packet_size ();
13310
13311   if (tp)
13312     {
13313       tp->hit_count = 0;
13314       tp->traceframe_usage = 0;
13315       for (loc = tp->loc; loc; loc = loc->next)
13316         {
13317           /* If the tracepoint was never downloaded, don't go asking for
13318              any status.  */
13319           if (tp->number_on_target == 0)
13320             continue;
13321           xsnprintf (rs->buf, size, "qTP:%x:%s", tp->number_on_target,
13322                      phex_nz (loc->address, 0));
13323           putpkt (rs->buf);
13324           reply = remote_get_noisy_reply ();
13325           if (reply && *reply)
13326             {
13327               if (*reply == 'V')
13328                 parse_tracepoint_status (reply + 1, bp, utp);
13329             }
13330         }
13331     }
13332   else if (utp)
13333     {
13334       utp->hit_count = 0;
13335       utp->traceframe_usage = 0;
13336       xsnprintf (rs->buf, size, "qTP:%x:%s", utp->number,
13337                  phex_nz (utp->addr, 0));
13338       putpkt (rs->buf);
13339       reply = remote_get_noisy_reply ();
13340       if (reply && *reply)
13341         {
13342           if (*reply == 'V')
13343             parse_tracepoint_status (reply + 1, bp, utp);
13344         }
13345     }
13346 }
13347
13348 void
13349 remote_target::trace_stop ()
13350 {
13351   struct remote_state *rs = get_remote_state ();
13352
13353   putpkt ("QTStop");
13354   remote_get_noisy_reply ();
13355   if (*rs->buf == '\0')
13356     error (_("Target does not support this command."));
13357   if (strcmp (rs->buf, "OK") != 0)
13358     error (_("Bogus reply from target: %s"), rs->buf);
13359 }
13360
13361 int
13362 remote_target::trace_find (enum trace_find_type type, int num,
13363                            CORE_ADDR addr1, CORE_ADDR addr2,
13364                            int *tpp)
13365 {
13366   struct remote_state *rs = get_remote_state ();
13367   char *endbuf = rs->buf + get_remote_packet_size ();
13368   char *p, *reply;
13369   int target_frameno = -1, target_tracept = -1;
13370
13371   /* Lookups other than by absolute frame number depend on the current
13372      trace selected, so make sure it is correct on the remote end
13373      first.  */
13374   if (type != tfind_number)
13375     set_remote_traceframe ();
13376
13377   p = rs->buf;
13378   strcpy (p, "QTFrame:");
13379   p = strchr (p, '\0');
13380   switch (type)
13381     {
13382     case tfind_number:
13383       xsnprintf (p, endbuf - p, "%x", num);
13384       break;
13385     case tfind_pc:
13386       xsnprintf (p, endbuf - p, "pc:%s", phex_nz (addr1, 0));
13387       break;
13388     case tfind_tp:
13389       xsnprintf (p, endbuf - p, "tdp:%x", num);
13390       break;
13391     case tfind_range:
13392       xsnprintf (p, endbuf - p, "range:%s:%s", phex_nz (addr1, 0),
13393                  phex_nz (addr2, 0));
13394       break;
13395     case tfind_outside:
13396       xsnprintf (p, endbuf - p, "outside:%s:%s", phex_nz (addr1, 0),
13397                  phex_nz (addr2, 0));
13398       break;
13399     default:
13400       error (_("Unknown trace find type %d"), type);
13401     }
13402
13403   putpkt (rs->buf);
13404   reply = remote_get_noisy_reply ();
13405   if (*reply == '\0')
13406     error (_("Target does not support this command."));
13407
13408   while (reply && *reply)
13409     switch (*reply)
13410       {
13411       case 'F':
13412         p = ++reply;
13413         target_frameno = (int) strtol (p, &reply, 16);
13414         if (reply == p)
13415           error (_("Unable to parse trace frame number"));
13416         /* Don't update our remote traceframe number cache on failure
13417            to select a remote traceframe.  */
13418         if (target_frameno == -1)
13419           return -1;
13420         break;
13421       case 'T':
13422         p = ++reply;
13423         target_tracept = (int) strtol (p, &reply, 16);
13424         if (reply == p)
13425           error (_("Unable to parse tracepoint number"));
13426         break;
13427       case 'O':         /* "OK"? */
13428         if (reply[1] == 'K' && reply[2] == '\0')
13429           reply += 2;
13430         else
13431           error (_("Bogus reply from target: %s"), reply);
13432         break;
13433       default:
13434         error (_("Bogus reply from target: %s"), reply);
13435       }
13436   if (tpp)
13437     *tpp = target_tracept;
13438
13439   rs->remote_traceframe_number = target_frameno;
13440   return target_frameno;
13441 }
13442
13443 bool
13444 remote_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
13445 {
13446   struct remote_state *rs = get_remote_state ();
13447   char *reply;
13448   ULONGEST uval;
13449
13450   set_remote_traceframe ();
13451
13452   xsnprintf (rs->buf, get_remote_packet_size (), "qTV:%x", tsvnum);
13453   putpkt (rs->buf);
13454   reply = remote_get_noisy_reply ();
13455   if (reply && *reply)
13456     {
13457       if (*reply == 'V')
13458         {
13459           unpack_varlen_hex (reply + 1, &uval);
13460           *val = (LONGEST) uval;
13461           return true;
13462         }
13463     }
13464   return false;
13465 }
13466
13467 int
13468 remote_target::save_trace_data (const char *filename)
13469 {
13470   struct remote_state *rs = get_remote_state ();
13471   char *p, *reply;
13472
13473   p = rs->buf;
13474   strcpy (p, "QTSave:");
13475   p += strlen (p);
13476   if ((p - rs->buf) + strlen (filename) * 2 >= get_remote_packet_size ())
13477     error (_("Remote file name too long for trace save packet"));
13478   p += 2 * bin2hex ((gdb_byte *) filename, p, strlen (filename));
13479   *p++ = '\0';
13480   putpkt (rs->buf);
13481   reply = remote_get_noisy_reply ();
13482   if (*reply == '\0')
13483     error (_("Target does not support this command."));
13484   if (strcmp (reply, "OK") != 0)
13485     error (_("Bogus reply from target: %s"), reply);
13486   return 0;
13487 }
13488
13489 /* This is basically a memory transfer, but needs to be its own packet
13490    because we don't know how the target actually organizes its trace
13491    memory, plus we want to be able to ask for as much as possible, but
13492    not be unhappy if we don't get as much as we ask for.  */
13493
13494 LONGEST
13495 remote_target::get_raw_trace_data (gdb_byte *buf, ULONGEST offset, LONGEST len)
13496 {
13497   struct remote_state *rs = get_remote_state ();
13498   char *reply;
13499   char *p;
13500   int rslt;
13501
13502   p = rs->buf;
13503   strcpy (p, "qTBuffer:");
13504   p += strlen (p);
13505   p += hexnumstr (p, offset);
13506   *p++ = ',';
13507   p += hexnumstr (p, len);
13508   *p++ = '\0';
13509
13510   putpkt (rs->buf);
13511   reply = remote_get_noisy_reply ();
13512   if (reply && *reply)
13513     {
13514       /* 'l' by itself means we're at the end of the buffer and
13515          there is nothing more to get.  */
13516       if (*reply == 'l')
13517         return 0;
13518
13519       /* Convert the reply into binary.  Limit the number of bytes to
13520          convert according to our passed-in buffer size, rather than
13521          what was returned in the packet; if the target is
13522          unexpectedly generous and gives us a bigger reply than we
13523          asked for, we don't want to crash.  */
13524       rslt = hex2bin (reply, buf, len);
13525       return rslt;
13526     }
13527
13528   /* Something went wrong, flag as an error.  */
13529   return -1;
13530 }
13531
13532 void
13533 remote_target::set_disconnected_tracing (int val)
13534 {
13535   struct remote_state *rs = get_remote_state ();
13536
13537   if (packet_support (PACKET_DisconnectedTracing_feature) == PACKET_ENABLE)
13538     {
13539       char *reply;
13540
13541       xsnprintf (rs->buf, get_remote_packet_size (), "QTDisconnected:%x", val);
13542       putpkt (rs->buf);
13543       reply = remote_get_noisy_reply ();
13544       if (*reply == '\0')
13545         error (_("Target does not support this command."));
13546       if (strcmp (reply, "OK") != 0)
13547         error (_("Bogus reply from target: %s"), reply);
13548     }
13549   else if (val)
13550     warning (_("Target does not support disconnected tracing."));
13551 }
13552
13553 int
13554 remote_target::core_of_thread (ptid_t ptid)
13555 {
13556   struct thread_info *info = find_thread_ptid (ptid);
13557
13558   if (info != NULL && info->priv != NULL)
13559     return get_remote_thread_info (info)->core;
13560
13561   return -1;
13562 }
13563
13564 void
13565 remote_target::set_circular_trace_buffer (int val)
13566 {
13567   struct remote_state *rs = get_remote_state ();
13568   char *reply;
13569
13570   xsnprintf (rs->buf, get_remote_packet_size (), "QTBuffer:circular:%x", val);
13571   putpkt (rs->buf);
13572   reply = remote_get_noisy_reply ();
13573   if (*reply == '\0')
13574     error (_("Target does not support this command."));
13575   if (strcmp (reply, "OK") != 0)
13576     error (_("Bogus reply from target: %s"), reply);
13577 }
13578
13579 traceframe_info_up
13580 remote_target::traceframe_info ()
13581 {
13582   gdb::optional<gdb::char_vector> text
13583     = target_read_stralloc (current_top_target (), TARGET_OBJECT_TRACEFRAME_INFO,
13584                             NULL);
13585   if (text)
13586     return parse_traceframe_info (text->data ());
13587
13588   return NULL;
13589 }
13590
13591 /* Handle the qTMinFTPILen packet.  Returns the minimum length of
13592    instruction on which a fast tracepoint may be placed.  Returns -1
13593    if the packet is not supported, and 0 if the minimum instruction
13594    length is unknown.  */
13595
13596 int
13597 remote_target::get_min_fast_tracepoint_insn_len ()
13598 {
13599   struct remote_state *rs = get_remote_state ();
13600   char *reply;
13601
13602   /* If we're not debugging a process yet, the IPA can't be
13603      loaded.  */
13604   if (!target_has_execution)
13605     return 0;
13606
13607   /* Make sure the remote is pointing at the right process.  */
13608   set_general_process ();
13609
13610   xsnprintf (rs->buf, get_remote_packet_size (), "qTMinFTPILen");
13611   putpkt (rs->buf);
13612   reply = remote_get_noisy_reply ();
13613   if (*reply == '\0')
13614     return -1;
13615   else
13616     {
13617       ULONGEST min_insn_len;
13618
13619       unpack_varlen_hex (reply, &min_insn_len);
13620
13621       return (int) min_insn_len;
13622     }
13623 }
13624
13625 void
13626 remote_target::set_trace_buffer_size (LONGEST val)
13627 {
13628   if (packet_support (PACKET_QTBuffer_size) != PACKET_DISABLE)
13629     {
13630       struct remote_state *rs = get_remote_state ();
13631       char *buf = rs->buf;
13632       char *endbuf = rs->buf + get_remote_packet_size ();
13633       enum packet_result result;
13634
13635       gdb_assert (val >= 0 || val == -1);
13636       buf += xsnprintf (buf, endbuf - buf, "QTBuffer:size:");
13637       /* Send -1 as literal "-1" to avoid host size dependency.  */
13638       if (val < 0)
13639         {
13640           *buf++ = '-';
13641           buf += hexnumstr (buf, (ULONGEST) -val);
13642         }
13643       else
13644         buf += hexnumstr (buf, (ULONGEST) val);
13645
13646       putpkt (rs->buf);
13647       remote_get_noisy_reply ();
13648       result = packet_ok (rs->buf,
13649                   &remote_protocol_packets[PACKET_QTBuffer_size]);
13650
13651       if (result != PACKET_OK)
13652         warning (_("Bogus reply from target: %s"), rs->buf);
13653     }
13654 }
13655
13656 bool
13657 remote_target::set_trace_notes (const char *user, const char *notes,
13658                                 const char *stop_notes)
13659 {
13660   struct remote_state *rs = get_remote_state ();
13661   char *reply;
13662   char *buf = rs->buf;
13663   char *endbuf = rs->buf + get_remote_packet_size ();
13664   int nbytes;
13665
13666   buf += xsnprintf (buf, endbuf - buf, "QTNotes:");
13667   if (user)
13668     {
13669       buf += xsnprintf (buf, endbuf - buf, "user:");
13670       nbytes = bin2hex ((gdb_byte *) user, buf, strlen (user));
13671       buf += 2 * nbytes;
13672       *buf++ = ';';
13673     }
13674   if (notes)
13675     {
13676       buf += xsnprintf (buf, endbuf - buf, "notes:");
13677       nbytes = bin2hex ((gdb_byte *) notes, buf, strlen (notes));
13678       buf += 2 * nbytes;
13679       *buf++ = ';';
13680     }
13681   if (stop_notes)
13682     {
13683       buf += xsnprintf (buf, endbuf - buf, "tstop:");
13684       nbytes = bin2hex ((gdb_byte *) stop_notes, buf, strlen (stop_notes));
13685       buf += 2 * nbytes;
13686       *buf++ = ';';
13687     }
13688   /* Ensure the buffer is terminated.  */
13689   *buf = '\0';
13690
13691   putpkt (rs->buf);
13692   reply = remote_get_noisy_reply ();
13693   if (*reply == '\0')
13694     return false;
13695
13696   if (strcmp (reply, "OK") != 0)
13697     error (_("Bogus reply from target: %s"), reply);
13698
13699   return true;
13700 }
13701
13702 bool
13703 remote_target::use_agent (bool use)
13704 {
13705   if (packet_support (PACKET_QAgent) != PACKET_DISABLE)
13706     {
13707       struct remote_state *rs = get_remote_state ();
13708
13709       /* If the stub supports QAgent.  */
13710       xsnprintf (rs->buf, get_remote_packet_size (), "QAgent:%d", use);
13711       putpkt (rs->buf);
13712       getpkt (&rs->buf, &rs->buf_size, 0);
13713
13714       if (strcmp (rs->buf, "OK") == 0)
13715         {
13716           ::use_agent = use;
13717           return true;
13718         }
13719     }
13720
13721   return false;
13722 }
13723
13724 bool
13725 remote_target::can_use_agent ()
13726 {
13727   return (packet_support (PACKET_QAgent) != PACKET_DISABLE);
13728 }
13729
13730 struct btrace_target_info
13731 {
13732   /* The ptid of the traced thread.  */
13733   ptid_t ptid;
13734
13735   /* The obtained branch trace configuration.  */
13736   struct btrace_config conf;
13737 };
13738
13739 /* Reset our idea of our target's btrace configuration.  */
13740
13741 static void
13742 remote_btrace_reset (remote_state *rs)
13743 {
13744   memset (&rs->btrace_config, 0, sizeof (rs->btrace_config));
13745 }
13746
13747 /* Synchronize the configuration with the target.  */
13748
13749 void
13750 remote_target::btrace_sync_conf (const btrace_config *conf)
13751 {
13752   struct packet_config *packet;
13753   struct remote_state *rs;
13754   char *buf, *pos, *endbuf;
13755
13756   rs = get_remote_state ();
13757   buf = rs->buf;
13758   endbuf = buf + get_remote_packet_size ();
13759
13760   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_bts_size];
13761   if (packet_config_support (packet) == PACKET_ENABLE
13762       && conf->bts.size != rs->btrace_config.bts.size)
13763     {
13764       pos = buf;
13765       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13766                         conf->bts.size);
13767
13768       putpkt (buf);
13769       getpkt (&buf, &rs->buf_size, 0);
13770
13771       if (packet_ok (buf, packet) == PACKET_ERROR)
13772         {
13773           if (buf[0] == 'E' && buf[1] == '.')
13774             error (_("Failed to configure the BTS buffer size: %s"), buf + 2);
13775           else
13776             error (_("Failed to configure the BTS buffer size."));
13777         }
13778
13779       rs->btrace_config.bts.size = conf->bts.size;
13780     }
13781
13782   packet = &remote_protocol_packets[PACKET_Qbtrace_conf_pt_size];
13783   if (packet_config_support (packet) == PACKET_ENABLE
13784       && conf->pt.size != rs->btrace_config.pt.size)
13785     {
13786       pos = buf;
13787       pos += xsnprintf (pos, endbuf - pos, "%s=0x%x", packet->name,
13788                         conf->pt.size);
13789
13790       putpkt (buf);
13791       getpkt (&buf, &rs->buf_size, 0);
13792
13793       if (packet_ok (buf, packet) == PACKET_ERROR)
13794         {
13795           if (buf[0] == 'E' && buf[1] == '.')
13796             error (_("Failed to configure the trace buffer size: %s"), buf + 2);
13797           else
13798             error (_("Failed to configure the trace buffer size."));
13799         }
13800
13801       rs->btrace_config.pt.size = conf->pt.size;
13802     }
13803 }
13804
13805 /* Read the current thread's btrace configuration from the target and
13806    store it into CONF.  */
13807
13808 static void
13809 btrace_read_config (struct btrace_config *conf)
13810 {
13811   gdb::optional<gdb::char_vector> xml
13812     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE_CONF, "");
13813   if (xml)
13814     parse_xml_btrace_conf (conf, xml->data ());
13815 }
13816
13817 /* Maybe reopen target btrace.  */
13818
13819 void
13820 remote_target::remote_btrace_maybe_reopen ()
13821 {
13822   struct remote_state *rs = get_remote_state ();
13823   struct thread_info *tp;
13824   int btrace_target_pushed = 0;
13825   int warned = 0;
13826
13827   scoped_restore_current_thread restore_thread;
13828
13829   ALL_NON_EXITED_THREADS (tp)
13830     {
13831       set_general_thread (tp->ptid);
13832
13833       memset (&rs->btrace_config, 0x00, sizeof (struct btrace_config));
13834       btrace_read_config (&rs->btrace_config);
13835
13836       if (rs->btrace_config.format == BTRACE_FORMAT_NONE)
13837         continue;
13838
13839 #if !defined (HAVE_LIBIPT)
13840       if (rs->btrace_config.format == BTRACE_FORMAT_PT)
13841         {
13842           if (!warned)
13843             {
13844               warned = 1;
13845               warning (_("Target is recording using Intel Processor Trace "
13846                          "but support was disabled at compile time."));
13847             }
13848
13849           continue;
13850         }
13851 #endif /* !defined (HAVE_LIBIPT) */
13852
13853       /* Push target, once, but before anything else happens.  This way our
13854          changes to the threads will be cleaned up by unpushing the target
13855          in case btrace_read_config () throws.  */
13856       if (!btrace_target_pushed)
13857         {
13858           btrace_target_pushed = 1;
13859           record_btrace_push_target ();
13860           printf_filtered (_("Target is recording using %s.\n"),
13861                            btrace_format_string (rs->btrace_config.format));
13862         }
13863
13864       tp->btrace.target = XCNEW (struct btrace_target_info);
13865       tp->btrace.target->ptid = tp->ptid;
13866       tp->btrace.target->conf = rs->btrace_config;
13867     }
13868 }
13869
13870 /* Enable branch tracing.  */
13871
13872 struct btrace_target_info *
13873 remote_target::enable_btrace (ptid_t ptid, const struct btrace_config *conf)
13874 {
13875   struct btrace_target_info *tinfo = NULL;
13876   struct packet_config *packet = NULL;
13877   struct remote_state *rs = get_remote_state ();
13878   char *buf = rs->buf;
13879   char *endbuf = rs->buf + get_remote_packet_size ();
13880
13881   switch (conf->format)
13882     {
13883       case BTRACE_FORMAT_BTS:
13884         packet = &remote_protocol_packets[PACKET_Qbtrace_bts];
13885         break;
13886
13887       case BTRACE_FORMAT_PT:
13888         packet = &remote_protocol_packets[PACKET_Qbtrace_pt];
13889         break;
13890     }
13891
13892   if (packet == NULL || packet_config_support (packet) != PACKET_ENABLE)
13893     error (_("Target does not support branch tracing."));
13894
13895   btrace_sync_conf (conf);
13896
13897   set_general_thread (ptid);
13898
13899   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13900   putpkt (rs->buf);
13901   getpkt (&rs->buf, &rs->buf_size, 0);
13902
13903   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13904     {
13905       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13906         error (_("Could not enable branch tracing for %s: %s"),
13907                target_pid_to_str (ptid), rs->buf + 2);
13908       else
13909         error (_("Could not enable branch tracing for %s."),
13910                target_pid_to_str (ptid));
13911     }
13912
13913   tinfo = XCNEW (struct btrace_target_info);
13914   tinfo->ptid = ptid;
13915
13916   /* If we fail to read the configuration, we lose some information, but the
13917      tracing itself is not impacted.  */
13918   TRY
13919     {
13920       btrace_read_config (&tinfo->conf);
13921     }
13922   CATCH (err, RETURN_MASK_ERROR)
13923     {
13924       if (err.message != NULL)
13925         warning ("%s", err.message);
13926     }
13927   END_CATCH
13928
13929   return tinfo;
13930 }
13931
13932 /* Disable branch tracing.  */
13933
13934 void
13935 remote_target::disable_btrace (struct btrace_target_info *tinfo)
13936 {
13937   struct packet_config *packet = &remote_protocol_packets[PACKET_Qbtrace_off];
13938   struct remote_state *rs = get_remote_state ();
13939   char *buf = rs->buf;
13940   char *endbuf = rs->buf + get_remote_packet_size ();
13941
13942   if (packet_config_support (packet) != PACKET_ENABLE)
13943     error (_("Target does not support branch tracing."));
13944
13945   set_general_thread (tinfo->ptid);
13946
13947   buf += xsnprintf (buf, endbuf - buf, "%s", packet->name);
13948   putpkt (rs->buf);
13949   getpkt (&rs->buf, &rs->buf_size, 0);
13950
13951   if (packet_ok (rs->buf, packet) == PACKET_ERROR)
13952     {
13953       if (rs->buf[0] == 'E' && rs->buf[1] == '.')
13954         error (_("Could not disable branch tracing for %s: %s"),
13955                target_pid_to_str (tinfo->ptid), rs->buf + 2);
13956       else
13957         error (_("Could not disable branch tracing for %s."),
13958                target_pid_to_str (tinfo->ptid));
13959     }
13960
13961   xfree (tinfo);
13962 }
13963
13964 /* Teardown branch tracing.  */
13965
13966 void
13967 remote_target::teardown_btrace (struct btrace_target_info *tinfo)
13968 {
13969   /* We must not talk to the target during teardown.  */
13970   xfree (tinfo);
13971 }
13972
13973 /* Read the branch trace.  */
13974
13975 enum btrace_error
13976 remote_target::read_btrace (struct btrace_data *btrace,
13977                             struct btrace_target_info *tinfo,
13978                             enum btrace_read_type type)
13979 {
13980   struct packet_config *packet = &remote_protocol_packets[PACKET_qXfer_btrace];
13981   const char *annex;
13982
13983   if (packet_config_support (packet) != PACKET_ENABLE)
13984     error (_("Target does not support branch tracing."));
13985
13986 #if !defined(HAVE_LIBEXPAT)
13987   error (_("Cannot process branch tracing result. XML parsing not supported."));
13988 #endif
13989
13990   switch (type)
13991     {
13992     case BTRACE_READ_ALL:
13993       annex = "all";
13994       break;
13995     case BTRACE_READ_NEW:
13996       annex = "new";
13997       break;
13998     case BTRACE_READ_DELTA:
13999       annex = "delta";
14000       break;
14001     default:
14002       internal_error (__FILE__, __LINE__,
14003                       _("Bad branch tracing read type: %u."),
14004                       (unsigned int) type);
14005     }
14006
14007   gdb::optional<gdb::char_vector> xml
14008     = target_read_stralloc (current_top_target (), TARGET_OBJECT_BTRACE, annex);
14009   if (!xml)
14010     return BTRACE_ERR_UNKNOWN;
14011
14012   parse_xml_btrace (btrace, xml->data ());
14013
14014   return BTRACE_ERR_NONE;
14015 }
14016
14017 const struct btrace_config *
14018 remote_target::btrace_conf (const struct btrace_target_info *tinfo)
14019 {
14020   return &tinfo->conf;
14021 }
14022
14023 bool
14024 remote_target::augmented_libraries_svr4_read ()
14025 {
14026   return (packet_support (PACKET_augmented_libraries_svr4_read_feature)
14027           == PACKET_ENABLE);
14028 }
14029
14030 /* Implementation of to_load.  */
14031
14032 void
14033 remote_target::load (const char *name, int from_tty)
14034 {
14035   generic_load (name, from_tty);
14036 }
14037
14038 /* Accepts an integer PID; returns a string representing a file that
14039    can be opened on the remote side to get the symbols for the child
14040    process.  Returns NULL if the operation is not supported.  */
14041
14042 char *
14043 remote_target::pid_to_exec_file (int pid)
14044 {
14045   static gdb::optional<gdb::char_vector> filename;
14046   struct inferior *inf;
14047   char *annex = NULL;
14048
14049   if (packet_support (PACKET_qXfer_exec_file) != PACKET_ENABLE)
14050     return NULL;
14051
14052   inf = find_inferior_pid (pid);
14053   if (inf == NULL)
14054     internal_error (__FILE__, __LINE__,
14055                     _("not currently attached to process %d"), pid);
14056
14057   if (!inf->fake_pid_p)
14058     {
14059       const int annex_size = 9;
14060
14061       annex = (char *) alloca (annex_size);
14062       xsnprintf (annex, annex_size, "%x", pid);
14063     }
14064
14065   filename = target_read_stralloc (current_top_target (),
14066                                    TARGET_OBJECT_EXEC_FILE, annex);
14067
14068   return filename ? filename->data () : nullptr;
14069 }
14070
14071 /* Implement the to_can_do_single_step target_ops method.  */
14072
14073 int
14074 remote_target::can_do_single_step ()
14075 {
14076   /* We can only tell whether target supports single step or not by
14077      supported s and S vCont actions if the stub supports vContSupported
14078      feature.  If the stub doesn't support vContSupported feature,
14079      we have conservatively to think target doesn't supports single
14080      step.  */
14081   if (packet_support (PACKET_vContSupported) == PACKET_ENABLE)
14082     {
14083       struct remote_state *rs = get_remote_state ();
14084
14085       if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14086         remote_vcont_probe ();
14087
14088       return rs->supports_vCont.s && rs->supports_vCont.S;
14089     }
14090   else
14091     return 0;
14092 }
14093
14094 /* Implementation of the to_execution_direction method for the remote
14095    target.  */
14096
14097 enum exec_direction_kind
14098 remote_target::execution_direction ()
14099 {
14100   struct remote_state *rs = get_remote_state ();
14101
14102   return rs->last_resume_exec_dir;
14103 }
14104
14105 /* Return pointer to the thread_info struct which corresponds to
14106    THREAD_HANDLE (having length HANDLE_LEN).  */
14107
14108 thread_info *
14109 remote_target::thread_handle_to_thread_info (const gdb_byte *thread_handle,
14110                                              int handle_len,
14111                                              inferior *inf)
14112 {
14113   struct thread_info *tp;
14114
14115   ALL_NON_EXITED_THREADS (tp)
14116     {
14117       remote_thread_info *priv = get_remote_thread_info (tp);
14118
14119       if (tp->inf == inf && priv != NULL)
14120         {
14121           if (handle_len != priv->thread_handle.size ())
14122             error (_("Thread handle size mismatch: %d vs %zu (from remote)"),
14123                    handle_len, priv->thread_handle.size ());
14124           if (memcmp (thread_handle, priv->thread_handle.data (),
14125                       handle_len) == 0)
14126             return tp;
14127         }
14128     }
14129
14130   return NULL;
14131 }
14132
14133 bool
14134 remote_target::can_async_p ()
14135 {
14136   struct remote_state *rs = get_remote_state ();
14137
14138   /* We don't go async if the user has explicitly prevented it with the
14139      "maint set target-async" command.  */
14140   if (!target_async_permitted)
14141     return false;
14142
14143   /* We're async whenever the serial device is.  */
14144   return serial_can_async_p (rs->remote_desc);
14145 }
14146
14147 bool
14148 remote_target::is_async_p ()
14149 {
14150   struct remote_state *rs = get_remote_state ();
14151
14152   if (!target_async_permitted)
14153     /* We only enable async when the user specifically asks for it.  */
14154     return false;
14155
14156   /* We're async whenever the serial device is.  */
14157   return serial_is_async_p (rs->remote_desc);
14158 }
14159
14160 /* Pass the SERIAL event on and up to the client.  One day this code
14161    will be able to delay notifying the client of an event until the
14162    point where an entire packet has been received.  */
14163
14164 static serial_event_ftype remote_async_serial_handler;
14165
14166 static void
14167 remote_async_serial_handler (struct serial *scb, void *context)
14168 {
14169   /* Don't propogate error information up to the client.  Instead let
14170      the client find out about the error by querying the target.  */
14171   inferior_event_handler (INF_REG_EVENT, NULL);
14172 }
14173
14174 static void
14175 remote_async_inferior_event_handler (gdb_client_data data)
14176 {
14177   inferior_event_handler (INF_REG_EVENT, data);
14178 }
14179
14180 void
14181 remote_target::async (int enable)
14182 {
14183   struct remote_state *rs = get_remote_state ();
14184
14185   if (enable)
14186     {
14187       serial_async (rs->remote_desc, remote_async_serial_handler, rs);
14188
14189       /* If there are pending events in the stop reply queue tell the
14190          event loop to process them.  */
14191       if (!QUEUE_is_empty (stop_reply_p, rs->stop_reply_queue))
14192         mark_async_event_handler (rs->remote_async_inferior_event_token);
14193       /* For simplicity, below we clear the pending events token
14194          without remembering whether it is marked, so here we always
14195          mark it.  If there's actually no pending notification to
14196          process, this ends up being a no-op (other than a spurious
14197          event-loop wakeup).  */
14198       if (target_is_non_stop_p ())
14199         mark_async_event_handler (rs->notif_state->get_pending_events_token);
14200     }
14201   else
14202     {
14203       serial_async (rs->remote_desc, NULL, NULL);
14204       /* If the core is disabling async, it doesn't want to be
14205          disturbed with target events.  Clear all async event sources
14206          too.  */
14207       clear_async_event_handler (rs->remote_async_inferior_event_token);
14208       if (target_is_non_stop_p ())
14209         clear_async_event_handler (rs->notif_state->get_pending_events_token);
14210     }
14211 }
14212
14213 /* Implementation of the to_thread_events method.  */
14214
14215 void
14216 remote_target::thread_events (int enable)
14217 {
14218   struct remote_state *rs = get_remote_state ();
14219   size_t size = get_remote_packet_size ();
14220
14221   if (packet_support (PACKET_QThreadEvents) == PACKET_DISABLE)
14222     return;
14223
14224   xsnprintf (rs->buf, size, "QThreadEvents:%x", enable ? 1 : 0);
14225   putpkt (rs->buf);
14226   getpkt (&rs->buf, &rs->buf_size, 0);
14227
14228   switch (packet_ok (rs->buf,
14229                      &remote_protocol_packets[PACKET_QThreadEvents]))
14230     {
14231     case PACKET_OK:
14232       if (strcmp (rs->buf, "OK") != 0)
14233         error (_("Remote refused setting thread events: %s"), rs->buf);
14234       break;
14235     case PACKET_ERROR:
14236       warning (_("Remote failure reply: %s"), rs->buf);
14237       break;
14238     case PACKET_UNKNOWN:
14239       break;
14240     }
14241 }
14242
14243 static void
14244 set_remote_cmd (const char *args, int from_tty)
14245 {
14246   help_list (remote_set_cmdlist, "set remote ", all_commands, gdb_stdout);
14247 }
14248
14249 static void
14250 show_remote_cmd (const char *args, int from_tty)
14251 {
14252   /* We can't just use cmd_show_list here, because we want to skip
14253      the redundant "show remote Z-packet" and the legacy aliases.  */
14254   struct cmd_list_element *list = remote_show_cmdlist;
14255   struct ui_out *uiout = current_uiout;
14256
14257   ui_out_emit_tuple tuple_emitter (uiout, "showlist");
14258   for (; list != NULL; list = list->next)
14259     if (strcmp (list->name, "Z-packet") == 0)
14260       continue;
14261     else if (list->type == not_set_cmd)
14262       /* Alias commands are exactly like the original, except they
14263          don't have the normal type.  */
14264       continue;
14265     else
14266       {
14267         ui_out_emit_tuple option_emitter (uiout, "option");
14268
14269         uiout->field_string ("name", list->name);
14270         uiout->text (":  ");
14271         if (list->type == show_cmd)
14272           do_show_command (NULL, from_tty, list);
14273         else
14274           cmd_func (list, NULL, from_tty);
14275       }
14276 }
14277
14278
14279 /* Function to be called whenever a new objfile (shlib) is detected.  */
14280 static void
14281 remote_new_objfile (struct objfile *objfile)
14282 {
14283   remote_target *remote = get_current_remote_target ();
14284
14285   if (remote != NULL)                   /* Have a remote connection.  */
14286     remote->remote_check_symbols ();
14287 }
14288
14289 /* Pull all the tracepoints defined on the target and create local
14290    data structures representing them.  We don't want to create real
14291    tracepoints yet, we don't want to mess up the user's existing
14292    collection.  */
14293   
14294 int
14295 remote_target::upload_tracepoints (struct uploaded_tp **utpp)
14296 {
14297   struct remote_state *rs = get_remote_state ();
14298   char *p;
14299
14300   /* Ask for a first packet of tracepoint definition.  */
14301   putpkt ("qTfP");
14302   getpkt (&rs->buf, &rs->buf_size, 0);
14303   p = rs->buf;
14304   while (*p && *p != 'l')
14305     {
14306       parse_tracepoint_definition (p, utpp);
14307       /* Ask for another packet of tracepoint definition.  */
14308       putpkt ("qTsP");
14309       getpkt (&rs->buf, &rs->buf_size, 0);
14310       p = rs->buf;
14311     }
14312   return 0;
14313 }
14314
14315 int
14316 remote_target::upload_trace_state_variables (struct uploaded_tsv **utsvp)
14317 {
14318   struct remote_state *rs = get_remote_state ();
14319   char *p;
14320
14321   /* Ask for a first packet of variable definition.  */
14322   putpkt ("qTfV");
14323   getpkt (&rs->buf, &rs->buf_size, 0);
14324   p = rs->buf;
14325   while (*p && *p != 'l')
14326     {
14327       parse_tsv_definition (p, utsvp);
14328       /* Ask for another packet of variable definition.  */
14329       putpkt ("qTsV");
14330       getpkt (&rs->buf, &rs->buf_size, 0);
14331       p = rs->buf;
14332     }
14333   return 0;
14334 }
14335
14336 /* The "set/show range-stepping" show hook.  */
14337
14338 static void
14339 show_range_stepping (struct ui_file *file, int from_tty,
14340                      struct cmd_list_element *c,
14341                      const char *value)
14342 {
14343   fprintf_filtered (file,
14344                     _("Debugger's willingness to use range stepping "
14345                       "is %s.\n"), value);
14346 }
14347
14348 /* Return true if the vCont;r action is supported by the remote
14349    stub.  */
14350
14351 bool
14352 remote_target::vcont_r_supported ()
14353 {
14354   if (packet_support (PACKET_vCont) == PACKET_SUPPORT_UNKNOWN)
14355     remote_vcont_probe ();
14356
14357   return (packet_support (PACKET_vCont) == PACKET_ENABLE
14358           && get_remote_state ()->supports_vCont.r);
14359 }
14360
14361 /* The "set/show range-stepping" set hook.  */
14362
14363 static void
14364 set_range_stepping (const char *ignore_args, int from_tty,
14365                     struct cmd_list_element *c)
14366 {
14367   /* When enabling, check whether range stepping is actually supported
14368      by the target, and warn if not.  */
14369   if (use_range_stepping)
14370     {
14371       remote_target *remote = get_current_remote_target ();
14372       if (remote == NULL
14373           || !remote->vcont_r_supported ())
14374         warning (_("Range stepping is not supported by the current target"));
14375     }
14376 }
14377
14378 void
14379 _initialize_remote (void)
14380 {
14381   struct cmd_list_element *cmd;
14382   const char *cmd_name;
14383
14384   /* architecture specific data */
14385   remote_g_packet_data_handle =
14386     gdbarch_data_register_pre_init (remote_g_packet_data_init);
14387
14388   remote_pspace_data
14389     = register_program_space_data_with_cleanup (NULL,
14390                                                 remote_pspace_data_cleanup);
14391
14392   add_target (remote_target_info, remote_target::open);
14393   add_target (extended_remote_target_info, extended_remote_target::open);
14394
14395   /* Hook into new objfile notification.  */
14396   gdb::observers::new_objfile.attach (remote_new_objfile);
14397
14398 #if 0
14399   init_remote_threadtests ();
14400 #endif
14401
14402   /* set/show remote ...  */
14403
14404   add_prefix_cmd ("remote", class_maintenance, set_remote_cmd, _("\
14405 Remote protocol specific variables\n\
14406 Configure various remote-protocol specific variables such as\n\
14407 the packets being used"),
14408                   &remote_set_cmdlist, "set remote ",
14409                   0 /* allow-unknown */, &setlist);
14410   add_prefix_cmd ("remote", class_maintenance, show_remote_cmd, _("\
14411 Remote protocol specific variables\n\
14412 Configure various remote-protocol specific variables such as\n\
14413 the packets being used"),
14414                   &remote_show_cmdlist, "show remote ",
14415                   0 /* allow-unknown */, &showlist);
14416
14417   add_cmd ("compare-sections", class_obscure, compare_sections_command, _("\
14418 Compare section data on target to the exec file.\n\
14419 Argument is a single section name (default: all loaded sections).\n\
14420 To compare only read-only loaded sections, specify the -r option."),
14421            &cmdlist);
14422
14423   add_cmd ("packet", class_maintenance, packet_command, _("\
14424 Send an arbitrary packet to a remote target.\n\
14425    maintenance packet TEXT\n\
14426 If GDB is talking to an inferior via the GDB serial protocol, then\n\
14427 this command sends the string TEXT to the inferior, and displays the\n\
14428 response packet.  GDB supplies the initial `$' character, and the\n\
14429 terminating `#' character and checksum."),
14430            &maintenancelist);
14431
14432   add_setshow_boolean_cmd ("remotebreak", no_class, &remote_break, _("\
14433 Set whether to send break if interrupted."), _("\
14434 Show whether to send break if interrupted."), _("\
14435 If set, a break, instead of a cntrl-c, is sent to the remote target."),
14436                            set_remotebreak, show_remotebreak,
14437                            &setlist, &showlist);
14438   cmd_name = "remotebreak";
14439   cmd = lookup_cmd (&cmd_name, setlist, "", -1, 1);
14440   deprecate_cmd (cmd, "set remote interrupt-sequence");
14441   cmd_name = "remotebreak"; /* needed because lookup_cmd updates the pointer */
14442   cmd = lookup_cmd (&cmd_name, showlist, "", -1, 1);
14443   deprecate_cmd (cmd, "show remote interrupt-sequence");
14444
14445   add_setshow_enum_cmd ("interrupt-sequence", class_support,
14446                         interrupt_sequence_modes, &interrupt_sequence_mode,
14447                         _("\
14448 Set interrupt sequence to remote target."), _("\
14449 Show interrupt sequence to remote target."), _("\
14450 Valid value is \"Ctrl-C\", \"BREAK\" or \"BREAK-g\". The default is \"Ctrl-C\"."),
14451                         NULL, show_interrupt_sequence,
14452                         &remote_set_cmdlist,
14453                         &remote_show_cmdlist);
14454
14455   add_setshow_boolean_cmd ("interrupt-on-connect", class_support,
14456                            &interrupt_on_connect, _("\
14457 Set whether interrupt-sequence is sent to remote target when gdb connects to."), _("            \
14458 Show whether interrupt-sequence is sent to remote target when gdb connects to."), _("           \
14459 If set, interrupt sequence is sent to remote target."),
14460                            NULL, NULL,
14461                            &remote_set_cmdlist, &remote_show_cmdlist);
14462
14463   /* Install commands for configuring memory read/write packets.  */
14464
14465   add_cmd ("remotewritesize", no_class, set_memory_write_packet_size, _("\
14466 Set the maximum number of bytes per memory write packet (deprecated)."),
14467            &setlist);
14468   add_cmd ("remotewritesize", no_class, show_memory_write_packet_size, _("\
14469 Show the maximum number of bytes per memory write packet (deprecated)."),
14470            &showlist);
14471   add_cmd ("memory-write-packet-size", no_class,
14472            set_memory_write_packet_size, _("\
14473 Set the maximum number of bytes per memory-write packet.\n\
14474 Specify the number of bytes in a packet or 0 (zero) for the\n\
14475 default packet size.  The actual limit is further reduced\n\
14476 dependent on the target.  Specify ``fixed'' to disable the\n\
14477 further restriction and ``limit'' to enable that restriction."),
14478            &remote_set_cmdlist);
14479   add_cmd ("memory-read-packet-size", no_class,
14480            set_memory_read_packet_size, _("\
14481 Set the maximum number of bytes per memory-read packet.\n\
14482 Specify the number of bytes in a packet or 0 (zero) for the\n\
14483 default packet size.  The actual limit is further reduced\n\
14484 dependent on the target.  Specify ``fixed'' to disable the\n\
14485 further restriction and ``limit'' to enable that restriction."),
14486            &remote_set_cmdlist);
14487   add_cmd ("memory-write-packet-size", no_class,
14488            show_memory_write_packet_size,
14489            _("Show the maximum number of bytes per memory-write packet."),
14490            &remote_show_cmdlist);
14491   add_cmd ("memory-read-packet-size", no_class,
14492            show_memory_read_packet_size,
14493            _("Show the maximum number of bytes per memory-read packet."),
14494            &remote_show_cmdlist);
14495
14496   add_setshow_zinteger_cmd ("hardware-watchpoint-limit", no_class,
14497                             &remote_hw_watchpoint_limit, _("\
14498 Set the maximum number of target hardware watchpoints."), _("\
14499 Show the maximum number of target hardware watchpoints."), _("\
14500 Specify a negative limit for unlimited."),
14501                             NULL, NULL, /* FIXME: i18n: The maximum
14502                                            number of target hardware
14503                                            watchpoints is %s.  */
14504                             &remote_set_cmdlist, &remote_show_cmdlist);
14505   add_setshow_zinteger_cmd ("hardware-watchpoint-length-limit", no_class,
14506                             &remote_hw_watchpoint_length_limit, _("\
14507 Set the maximum length (in bytes) of a target hardware watchpoint."), _("\
14508 Show the maximum length (in bytes) of a target hardware watchpoint."), _("\
14509 Specify a negative limit for unlimited."),
14510                             NULL, NULL, /* FIXME: i18n: The maximum
14511                                            length (in bytes) of a target
14512                                            hardware watchpoint is %s.  */
14513                             &remote_set_cmdlist, &remote_show_cmdlist);
14514   add_setshow_zinteger_cmd ("hardware-breakpoint-limit", no_class,
14515                             &remote_hw_breakpoint_limit, _("\
14516 Set the maximum number of target hardware breakpoints."), _("\
14517 Show the maximum number of target hardware breakpoints."), _("\
14518 Specify a negative limit for unlimited."),
14519                             NULL, NULL, /* FIXME: i18n: The maximum
14520                                            number of target hardware
14521                                            breakpoints is %s.  */
14522                             &remote_set_cmdlist, &remote_show_cmdlist);
14523
14524   add_setshow_zuinteger_cmd ("remoteaddresssize", class_obscure,
14525                              &remote_address_size, _("\
14526 Set the maximum size of the address (in bits) in a memory packet."), _("\
14527 Show the maximum size of the address (in bits) in a memory packet."), NULL,
14528                              NULL,
14529                              NULL, /* FIXME: i18n: */
14530                              &setlist, &showlist);
14531
14532   init_all_packet_configs ();
14533
14534   add_packet_config_cmd (&remote_protocol_packets[PACKET_X],
14535                          "X", "binary-download", 1);
14536
14537   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCont],
14538                          "vCont", "verbose-resume", 0);
14539
14540   add_packet_config_cmd (&remote_protocol_packets[PACKET_QPassSignals],
14541                          "QPassSignals", "pass-signals", 0);
14542
14543   add_packet_config_cmd (&remote_protocol_packets[PACKET_QCatchSyscalls],
14544                          "QCatchSyscalls", "catch-syscalls", 0);
14545
14546   add_packet_config_cmd (&remote_protocol_packets[PACKET_QProgramSignals],
14547                          "QProgramSignals", "program-signals", 0);
14548
14549   add_packet_config_cmd (&remote_protocol_packets[PACKET_QSetWorkingDir],
14550                          "QSetWorkingDir", "set-working-dir", 0);
14551
14552   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartupWithShell],
14553                          "QStartupWithShell", "startup-with-shell", 0);
14554
14555   add_packet_config_cmd (&remote_protocol_packets
14556                          [PACKET_QEnvironmentHexEncoded],
14557                          "QEnvironmentHexEncoded", "environment-hex-encoded",
14558                          0);
14559
14560   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentReset],
14561                          "QEnvironmentReset", "environment-reset",
14562                          0);
14563
14564   add_packet_config_cmd (&remote_protocol_packets[PACKET_QEnvironmentUnset],
14565                          "QEnvironmentUnset", "environment-unset",
14566                          0);
14567
14568   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSymbol],
14569                          "qSymbol", "symbol-lookup", 0);
14570
14571   add_packet_config_cmd (&remote_protocol_packets[PACKET_P],
14572                          "P", "set-register", 1);
14573
14574   add_packet_config_cmd (&remote_protocol_packets[PACKET_p],
14575                          "p", "fetch-register", 1);
14576
14577   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z0],
14578                          "Z0", "software-breakpoint", 0);
14579
14580   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z1],
14581                          "Z1", "hardware-breakpoint", 0);
14582
14583   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z2],
14584                          "Z2", "write-watchpoint", 0);
14585
14586   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z3],
14587                          "Z3", "read-watchpoint", 0);
14588
14589   add_packet_config_cmd (&remote_protocol_packets[PACKET_Z4],
14590                          "Z4", "access-watchpoint", 0);
14591
14592   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_auxv],
14593                          "qXfer:auxv:read", "read-aux-vector", 0);
14594
14595   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_exec_file],
14596                          "qXfer:exec-file:read", "pid-to-exec-file", 0);
14597
14598   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_features],
14599                          "qXfer:features:read", "target-features", 0);
14600
14601   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries],
14602                          "qXfer:libraries:read", "library-info", 0);
14603
14604   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_libraries_svr4],
14605                          "qXfer:libraries-svr4:read", "library-info-svr4", 0);
14606
14607   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_memory_map],
14608                          "qXfer:memory-map:read", "memory-map", 0);
14609
14610   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_read],
14611                          "qXfer:spu:read", "read-spu-object", 0);
14612
14613   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_spu_write],
14614                          "qXfer:spu:write", "write-spu-object", 0);
14615
14616   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_osdata],
14617                         "qXfer:osdata:read", "osdata", 0);
14618
14619   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_threads],
14620                          "qXfer:threads:read", "threads", 0);
14621
14622   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_read],
14623                          "qXfer:siginfo:read", "read-siginfo-object", 0);
14624
14625   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_siginfo_write],
14626                          "qXfer:siginfo:write", "write-siginfo-object", 0);
14627
14628   add_packet_config_cmd
14629     (&remote_protocol_packets[PACKET_qXfer_traceframe_info],
14630      "qXfer:traceframe-info:read", "traceframe-info", 0);
14631
14632   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_uib],
14633                          "qXfer:uib:read", "unwind-info-block", 0);
14634
14635   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTLSAddr],
14636                          "qGetTLSAddr", "get-thread-local-storage-address",
14637                          0);
14638
14639   add_packet_config_cmd (&remote_protocol_packets[PACKET_qGetTIBAddr],
14640                          "qGetTIBAddr", "get-thread-information-block-address",
14641                          0);
14642
14643   add_packet_config_cmd (&remote_protocol_packets[PACKET_bc],
14644                          "bc", "reverse-continue", 0);
14645
14646   add_packet_config_cmd (&remote_protocol_packets[PACKET_bs],
14647                          "bs", "reverse-step", 0);
14648
14649   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSupported],
14650                          "qSupported", "supported-packets", 0);
14651
14652   add_packet_config_cmd (&remote_protocol_packets[PACKET_qSearch_memory],
14653                          "qSearch:memory", "search-memory", 0);
14654
14655   add_packet_config_cmd (&remote_protocol_packets[PACKET_qTStatus],
14656                          "qTStatus", "trace-status", 0);
14657
14658   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_setfs],
14659                          "vFile:setfs", "hostio-setfs", 0);
14660
14661   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_open],
14662                          "vFile:open", "hostio-open", 0);
14663
14664   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pread],
14665                          "vFile:pread", "hostio-pread", 0);
14666
14667   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_pwrite],
14668                          "vFile:pwrite", "hostio-pwrite", 0);
14669
14670   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_close],
14671                          "vFile:close", "hostio-close", 0);
14672
14673   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_unlink],
14674                          "vFile:unlink", "hostio-unlink", 0);
14675
14676   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_readlink],
14677                          "vFile:readlink", "hostio-readlink", 0);
14678
14679   add_packet_config_cmd (&remote_protocol_packets[PACKET_vFile_fstat],
14680                          "vFile:fstat", "hostio-fstat", 0);
14681
14682   add_packet_config_cmd (&remote_protocol_packets[PACKET_vAttach],
14683                          "vAttach", "attach", 0);
14684
14685   add_packet_config_cmd (&remote_protocol_packets[PACKET_vRun],
14686                          "vRun", "run", 0);
14687
14688   add_packet_config_cmd (&remote_protocol_packets[PACKET_QStartNoAckMode],
14689                          "QStartNoAckMode", "noack", 0);
14690
14691   add_packet_config_cmd (&remote_protocol_packets[PACKET_vKill],
14692                          "vKill", "kill", 0);
14693
14694   add_packet_config_cmd (&remote_protocol_packets[PACKET_qAttached],
14695                          "qAttached", "query-attached", 0);
14696
14697   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalTracepoints],
14698                          "ConditionalTracepoints",
14699                          "conditional-tracepoints", 0);
14700
14701   add_packet_config_cmd (&remote_protocol_packets[PACKET_ConditionalBreakpoints],
14702                          "ConditionalBreakpoints",
14703                          "conditional-breakpoints", 0);
14704
14705   add_packet_config_cmd (&remote_protocol_packets[PACKET_BreakpointCommands],
14706                          "BreakpointCommands",
14707                          "breakpoint-commands", 0);
14708
14709   add_packet_config_cmd (&remote_protocol_packets[PACKET_FastTracepoints],
14710                          "FastTracepoints", "fast-tracepoints", 0);
14711
14712   add_packet_config_cmd (&remote_protocol_packets[PACKET_TracepointSource],
14713                          "TracepointSource", "TracepointSource", 0);
14714
14715   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAllow],
14716                          "QAllow", "allow", 0);
14717
14718   add_packet_config_cmd (&remote_protocol_packets[PACKET_StaticTracepoints],
14719                          "StaticTracepoints", "static-tracepoints", 0);
14720
14721   add_packet_config_cmd (&remote_protocol_packets[PACKET_InstallInTrace],
14722                          "InstallInTrace", "install-in-trace", 0);
14723
14724   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_statictrace_read],
14725                          "qXfer:statictrace:read", "read-sdata-object", 0);
14726
14727   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_fdpic],
14728                          "qXfer:fdpic:read", "read-fdpic-loadmap", 0);
14729
14730   add_packet_config_cmd (&remote_protocol_packets[PACKET_QDisableRandomization],
14731                          "QDisableRandomization", "disable-randomization", 0);
14732
14733   add_packet_config_cmd (&remote_protocol_packets[PACKET_QAgent],
14734                          "QAgent", "agent", 0);
14735
14736   add_packet_config_cmd (&remote_protocol_packets[PACKET_QTBuffer_size],
14737                          "QTBuffer:size", "trace-buffer-size", 0);
14738
14739   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_off],
14740        "Qbtrace:off", "disable-btrace", 0);
14741
14742   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_bts],
14743        "Qbtrace:bts", "enable-btrace-bts", 0);
14744
14745   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_pt],
14746        "Qbtrace:pt", "enable-btrace-pt", 0);
14747
14748   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace],
14749        "qXfer:btrace", "read-btrace", 0);
14750
14751   add_packet_config_cmd (&remote_protocol_packets[PACKET_qXfer_btrace_conf],
14752        "qXfer:btrace-conf", "read-btrace-conf", 0);
14753
14754   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_bts_size],
14755        "Qbtrace-conf:bts:size", "btrace-conf-bts-size", 0);
14756
14757   add_packet_config_cmd (&remote_protocol_packets[PACKET_multiprocess_feature],
14758        "multiprocess-feature", "multiprocess-feature", 0);
14759
14760   add_packet_config_cmd (&remote_protocol_packets[PACKET_swbreak_feature],
14761                          "swbreak-feature", "swbreak-feature", 0);
14762
14763   add_packet_config_cmd (&remote_protocol_packets[PACKET_hwbreak_feature],
14764                          "hwbreak-feature", "hwbreak-feature", 0);
14765
14766   add_packet_config_cmd (&remote_protocol_packets[PACKET_fork_event_feature],
14767                          "fork-event-feature", "fork-event-feature", 0);
14768
14769   add_packet_config_cmd (&remote_protocol_packets[PACKET_vfork_event_feature],
14770                          "vfork-event-feature", "vfork-event-feature", 0);
14771
14772   add_packet_config_cmd (&remote_protocol_packets[PACKET_Qbtrace_conf_pt_size],
14773        "Qbtrace-conf:pt:size", "btrace-conf-pt-size", 0);
14774
14775   add_packet_config_cmd (&remote_protocol_packets[PACKET_vContSupported],
14776                          "vContSupported", "verbose-resume-supported", 0);
14777
14778   add_packet_config_cmd (&remote_protocol_packets[PACKET_exec_event_feature],
14779                          "exec-event-feature", "exec-event-feature", 0);
14780
14781   add_packet_config_cmd (&remote_protocol_packets[PACKET_vCtrlC],
14782                          "vCtrlC", "ctrl-c", 0);
14783
14784   add_packet_config_cmd (&remote_protocol_packets[PACKET_QThreadEvents],
14785                          "QThreadEvents", "thread-events", 0);
14786
14787   add_packet_config_cmd (&remote_protocol_packets[PACKET_no_resumed],
14788                          "N stop reply", "no-resumed-stop-reply", 0);
14789
14790   /* Assert that we've registered "set remote foo-packet" commands
14791      for all packet configs.  */
14792   {
14793     int i;
14794
14795     for (i = 0; i < PACKET_MAX; i++)
14796       {
14797         /* Ideally all configs would have a command associated.  Some
14798            still don't though.  */
14799         int excepted;
14800
14801         switch (i)
14802           {
14803           case PACKET_QNonStop:
14804           case PACKET_EnableDisableTracepoints_feature:
14805           case PACKET_tracenz_feature:
14806           case PACKET_DisconnectedTracing_feature:
14807           case PACKET_augmented_libraries_svr4_read_feature:
14808           case PACKET_qCRC:
14809             /* Additions to this list need to be well justified:
14810                pre-existing packets are OK; new packets are not.  */
14811             excepted = 1;
14812             break;
14813           default:
14814             excepted = 0;
14815             break;
14816           }
14817
14818         /* This catches both forgetting to add a config command, and
14819            forgetting to remove a packet from the exception list.  */
14820         gdb_assert (excepted == (remote_protocol_packets[i].name == NULL));
14821       }
14822   }
14823
14824   /* Keep the old ``set remote Z-packet ...'' working.  Each individual
14825      Z sub-packet has its own set and show commands, but users may
14826      have sets to this variable in their .gdbinit files (or in their
14827      documentation).  */
14828   add_setshow_auto_boolean_cmd ("Z-packet", class_obscure,
14829                                 &remote_Z_packet_detect, _("\
14830 Set use of remote protocol `Z' packets"), _("\
14831 Show use of remote protocol `Z' packets "), _("\
14832 When set, GDB will attempt to use the remote breakpoint and watchpoint\n\
14833 packets."),
14834                                 set_remote_protocol_Z_packet_cmd,
14835                                 show_remote_protocol_Z_packet_cmd,
14836                                 /* FIXME: i18n: Use of remote protocol
14837                                    `Z' packets is %s.  */
14838                                 &remote_set_cmdlist, &remote_show_cmdlist);
14839
14840   add_prefix_cmd ("remote", class_files, remote_command, _("\
14841 Manipulate files on the remote system\n\
14842 Transfer files to and from the remote target system."),
14843                   &remote_cmdlist, "remote ",
14844                   0 /* allow-unknown */, &cmdlist);
14845
14846   add_cmd ("put", class_files, remote_put_command,
14847            _("Copy a local file to the remote system."),
14848            &remote_cmdlist);
14849
14850   add_cmd ("get", class_files, remote_get_command,
14851            _("Copy a remote file to the local system."),
14852            &remote_cmdlist);
14853
14854   add_cmd ("delete", class_files, remote_delete_command,
14855            _("Delete a remote file."),
14856            &remote_cmdlist);
14857
14858   add_setshow_string_noescape_cmd ("exec-file", class_files,
14859                                    &remote_exec_file_var, _("\
14860 Set the remote pathname for \"run\""), _("\
14861 Show the remote pathname for \"run\""), NULL,
14862                                    set_remote_exec_file,
14863                                    show_remote_exec_file,
14864                                    &remote_set_cmdlist,
14865                                    &remote_show_cmdlist);
14866
14867   add_setshow_boolean_cmd ("range-stepping", class_run,
14868                            &use_range_stepping, _("\
14869 Enable or disable range stepping."), _("\
14870 Show whether target-assisted range stepping is enabled."), _("\
14871 If on, and the target supports it, when stepping a source line, GDB\n\
14872 tells the target to step the corresponding range of addresses itself instead\n\
14873 of issuing multiple single-steps.  This speeds up source level\n\
14874 stepping.  If off, GDB always issues single-steps, even if range\n\
14875 stepping is supported by the target.  The default is on."),
14876                            set_range_stepping,
14877                            show_range_stepping,
14878                            &setlist,
14879                            &showlist);
14880
14881   /* Eventually initialize fileio.  See fileio.c */
14882   initialize_remote_fileio (remote_set_cmdlist, remote_show_cmdlist);
14883
14884   /* Take advantage of the fact that the TID field is not used, to tag
14885      special ptids with it set to != 0.  */
14886   magic_null_ptid = ptid_build (42000, -1, 1);
14887   not_sent_ptid = ptid_build (42000, -2, 1);
14888   any_thread_ptid = ptid_build (42000, 0, 1);
14889 }